3 * https://www.mediawiki.org/wiki/OOUI
5 * Copyright 2011–2019 OOUI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: 2019-04-24T18:29:08Z
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 'ooui-' + OO
.ui
.elementId
;
75 * Check if an element is focusable.
76 * Inspired by :focusable in jQueryUI v1.11.4 - 2015-04-14
78 * @param {jQuery} $element Element to test
79 * @return {boolean} Element is focusable
81 OO
.ui
.isFocusableElement = function ( $element
) {
83 element
= $element
[ 0 ];
85 // Anything disabled is not focusable
86 if ( element
.disabled
) {
90 // Check if the element is visible
92 // This is quicker than calling $element.is( ':visible' )
93 $.expr
.pseudos
.visible( element
) &&
94 // Check that all parents are visible
95 !$element
.parents().addBack().filter( function () {
96 return $.css( this, 'visibility' ) === 'hidden';
102 // Check if the element is ContentEditable, which is the string 'true'
103 if ( element
.contentEditable
=== 'true' ) {
107 // Anything with a non-negative numeric tabIndex is focusable.
108 // Use .prop to avoid browser bugs
109 if ( $element
.prop( 'tabIndex' ) >= 0 ) {
113 // Some element types are naturally focusable
114 // (indexOf is much faster than regex in Chrome and about the
115 // same in FF: https://jsperf.com/regex-vs-indexof-array2)
116 nodeName
= element
.nodeName
.toLowerCase();
117 if ( [ 'input', 'select', 'textarea', 'button', 'object' ].indexOf( nodeName
) !== -1 ) {
121 // Links and areas are focusable if they have an href
122 if ( ( nodeName
=== 'a' || nodeName
=== 'area' ) && $element
.attr( 'href' ) !== undefined ) {
130 * Find a focusable child.
132 * @param {jQuery} $container Container to search in
133 * @param {boolean} [backwards] Search backwards
134 * @return {jQuery} Focusable child, or an empty jQuery object if none found
136 OO
.ui
.findFocusable = function ( $container
, backwards
) {
137 var $focusable
= $( [] ),
138 // $focusableCandidates is a superset of things that
139 // could get matched by isFocusableElement
140 $focusableCandidates
= $container
141 .find( 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]' );
144 $focusableCandidates
= Array
.prototype.reverse
.call( $focusableCandidates
);
147 $focusableCandidates
.each( function () {
148 var $this = $( this );
149 if ( OO
.ui
.isFocusableElement( $this ) ) {
158 * Get the user's language and any fallback languages.
160 * These language codes are used to localize user interface elements in the user's language.
162 * In environments that provide a localization system, this function should be overridden to
163 * return the user's language(s). The default implementation returns English (en) only.
165 * @return {string[]} Language codes, in descending order of priority
167 OO
.ui
.getUserLanguages = function () {
172 * Get a value in an object keyed by language code.
174 * @param {Object.<string,Mixed>} obj Object keyed by language code
175 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
176 * @param {string} [fallback] Fallback code, used if no matching language can be found
177 * @return {Mixed} Local value
179 OO
.ui
.getLocalValue = function ( obj
, lang
, fallback
) {
182 // Requested language
186 // Known user language
187 langs
= OO
.ui
.getUserLanguages();
188 for ( i
= 0, len
= langs
.length
; i
< len
; i
++ ) {
195 if ( obj
[ fallback
] ) {
196 return obj
[ fallback
];
198 // First existing language
199 for ( lang
in obj
) {
207 * Check if a node is contained within another node.
209 * Similar to jQuery#contains except a list of containers can be supplied
210 * and a boolean argument allows you to include the container in the match list
212 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
213 * @param {HTMLElement} contained Node to find
214 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match,
215 * otherwise only match descendants
216 * @return {boolean} The node is in the list of target nodes
218 OO
.ui
.contains = function ( containers
, contained
, matchContainers
) {
220 if ( !Array
.isArray( containers
) ) {
221 containers
= [ containers
];
223 for ( i
= containers
.length
- 1; i
>= 0; i
-- ) {
225 ( matchContainers
&& contained
=== containers
[ i
] ) ||
226 $.contains( containers
[ i
], contained
)
235 * Return a function, that, as long as it continues to be invoked, will not
236 * be triggered. The function will be called after it stops being called for
237 * N milliseconds. If `immediate` is passed, trigger the function on the
238 * leading edge, instead of the trailing.
240 * Ported from: http://underscorejs.org/underscore.js
242 * @param {Function} func Function to debounce
243 * @param {number} [wait=0] Wait period in milliseconds
244 * @param {boolean} [immediate] Trigger on leading edge
245 * @return {Function} Debounced function
247 OO
.ui
.debounce = function ( func
, wait
, immediate
) {
252 later = function () {
255 func
.apply( context
, args
);
258 if ( immediate
&& !timeout
) {
259 func
.apply( context
, args
);
261 if ( !timeout
|| wait
) {
262 clearTimeout( timeout
);
263 timeout
= setTimeout( later
, wait
);
269 * Puts a console warning with provided message.
271 * @param {string} message Message
273 OO
.ui
.warnDeprecation = function ( message
) {
274 if ( OO
.getProp( window
, 'console', 'warn' ) !== undefined ) {
275 // eslint-disable-next-line no-console
276 console
.warn( message
);
281 * Returns a function, that, when invoked, will only be triggered at most once
282 * during a given window of time. If called again during that window, it will
283 * wait until the window ends and then trigger itself again.
285 * As it's not knowable to the caller whether the function will actually run
286 * when the wrapper is called, return values from the function are entirely
289 * @param {Function} func Function to throttle
290 * @param {number} wait Throttle window length, in milliseconds
291 * @return {Function} Throttled function
293 OO
.ui
.throttle = function ( func
, wait
) {
294 var context
, args
, timeout
,
298 previous
= Date
.now();
299 func
.apply( context
, args
);
302 // Check how long it's been since the last time the function was
303 // called, and whether it's more or less than the requested throttle
304 // period. If it's less, run the function immediately. If it's more,
305 // set a timeout for the remaining time -- but don't replace an
306 // existing timeout, since that'd indefinitely prolong the wait.
307 var remaining
= wait
- ( Date
.now() - previous
);
310 if ( remaining
<= 0 ) {
311 // Note: unless wait was ridiculously large, this means we'll
312 // automatically run the first time the function was called in a
313 // given period. (If you provide a wait period larger than the
314 // current Unix timestamp, you *deserve* unexpected behavior.)
315 clearTimeout( timeout
);
317 } else if ( !timeout
) {
318 timeout
= setTimeout( run
, remaining
);
324 * A (possibly faster) way to get the current timestamp as an integer.
326 * @deprecated Since 0.31.1; use `Date.now()` instead.
327 * @return {number} Current timestamp, in milliseconds since the Unix epoch
329 OO
.ui
.now = function () {
330 OO
.ui
.warnDeprecation( 'OO.ui.now() is deprecated, use Date.now() instead' );
335 * Reconstitute a JavaScript object corresponding to a widget created by
336 * the PHP implementation.
338 * This is an alias for `OO.ui.Element.static.infuse()`.
340 * @param {string|HTMLElement|jQuery} idOrNode
341 * A DOM id (if a string) or node for the widget to infuse.
342 * @param {Object} [config] Configuration options
343 * @return {OO.ui.Element}
344 * The `OO.ui.Element` corresponding to this (infusable) document node.
346 OO
.ui
.infuse = function ( idOrNode
, config
) {
347 return OO
.ui
.Element
.static.infuse( idOrNode
, config
);
351 * Get a localized message.
353 * After the message key, message parameters may optionally be passed. In the default
354 * implementation, any occurrences of $1 are replaced with the first parameter, $2 with the
355 * second parameter, etc.
356 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long
357 * as they support unnamed, ordered message parameters.
359 * In environments that provide a localization system, this function should be overridden to
360 * return the message translated in the user's language. The default implementation always
361 * returns English messages. An example of doing this with
362 * [jQuery.i18n](https://github.com/wikimedia/jquery.i18n) follows.
365 * var i, iLen, button,
366 * messagePath = 'oojs-ui/dist/i18n/',
367 * languages = [ $.i18n().locale, 'ur', 'en' ],
370 * for ( i = 0, iLen = languages.length; i < iLen; i++ ) {
371 * languageMap[ languages[ i ] ] = messagePath + languages[ i ].toLowerCase() + '.json';
374 * $.i18n().load( languageMap ).done( function() {
375 * // Replace the built-in `msg` only once we've loaded the internationalization.
376 * // OOUI uses `OO.ui.deferMsg` for all initially-loaded messages. So long as
377 * // you put off creating any widgets until this promise is complete, no English
378 * // will be displayed.
379 * OO.ui.msg = $.i18n;
381 * // A button displaying "OK" in the default locale
382 * button = new OO.ui.ButtonWidget( {
383 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
386 * $( document.body ).append( button.$element );
388 * // A button displaying "OK" in Urdu
389 * $.i18n().locale = 'ur';
390 * button = new OO.ui.ButtonWidget( {
391 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
394 * $( document.body ).append( button.$element );
397 * @param {string} key Message key
398 * @param {...Mixed} [params] Message parameters
399 * @return {string} Translated message with parameters substituted
401 OO
.ui
.msg = function ( key
) {
402 // `OO.ui.msg.messages` is defined in code generated during the build process
403 var messages
= OO
.ui
.msg
.messages
,
404 message
= messages
[ key
],
405 params
= Array
.prototype.slice
.call( arguments
, 1 );
406 if ( typeof message
=== 'string' ) {
407 // Perform $1 substitution
408 message
= message
.replace( /\$(\d+)/g, function ( unused
, n
) {
409 var i
= parseInt( n
, 10 );
410 return params
[ i
- 1 ] !== undefined ? params
[ i
- 1 ] : '$' + n
;
413 // Return placeholder if message not found
414 message
= '[' + key
+ ']';
420 * Package a message and arguments for deferred resolution.
422 * Use this when you are statically specifying a message and the message may not yet be present.
424 * @param {string} key Message key
425 * @param {...Mixed} [params] Message parameters
426 * @return {Function} Function that returns the resolved message when executed
428 OO
.ui
.deferMsg = function () {
429 var args
= arguments
;
431 return OO
.ui
.msg
.apply( OO
.ui
, args
);
438 * If the message is a function it will be executed, otherwise it will pass through directly.
440 * @param {Function|string} msg Deferred message, or message text
441 * @return {string} Resolved message
443 OO
.ui
.resolveMsg = function ( msg
) {
444 if ( typeof msg
=== 'function' ) {
451 * @param {string} url
454 OO
.ui
.isSafeUrl = function ( url
) {
455 // Keep this function in sync with php/Tag.php
456 var i
, protocolWhitelist
;
458 function stringStartsWith( haystack
, needle
) {
459 return haystack
.substr( 0, needle
.length
) === needle
;
462 protocolWhitelist
= [
463 'bitcoin', 'ftp', 'ftps', 'geo', 'git', 'gopher', 'http', 'https', 'irc', 'ircs',
464 'magnet', 'mailto', 'mms', 'news', 'nntp', 'redis', 'sftp', 'sip', 'sips', 'sms', 'ssh',
465 'svn', 'tel', 'telnet', 'urn', 'worldwind', 'xmpp'
472 for ( i
= 0; i
< protocolWhitelist
.length
; i
++ ) {
473 if ( stringStartsWith( url
, protocolWhitelist
[ i
] + ':' ) ) {
478 // This matches '//' too
479 if ( stringStartsWith( url
, '/' ) || stringStartsWith( url
, './' ) ) {
482 if ( stringStartsWith( url
, '?' ) || stringStartsWith( url
, '#' ) ) {
490 * Check if the user has a 'mobile' device.
492 * For our purposes this means the user is primarily using an
493 * on-screen keyboard, touch input instead of a mouse and may
494 * have a physically small display.
496 * It is left up to implementors to decide how to compute this
497 * so the default implementation always returns false.
499 * @return {boolean} User is on a mobile device
501 OO
.ui
.isMobile = function () {
506 * Get the additional spacing that should be taken into account when displaying elements that are
507 * clipped to the viewport, e.g. dropdown menus and popups. This is meant to be overridden to avoid
508 * such menus overlapping any fixed headers/toolbars/navigation used by the site.
510 * @return {Object} Object with the properties 'top', 'right', 'bottom', 'left', each representing
511 * the extra spacing from that edge of viewport (in pixels)
513 OO
.ui
.getViewportSpacing = function () {
523 * Get the default overlay, which is used by various widgets when they are passed `$overlay: true`.
524 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
526 * @return {jQuery} Default overlay node
528 OO
.ui
.getDefaultOverlay = function () {
529 if ( !OO
.ui
.$defaultOverlay
) {
530 OO
.ui
.$defaultOverlay
= $( '<div>' ).addClass( 'oo-ui-defaultOverlay' );
531 $( document
.body
).append( OO
.ui
.$defaultOverlay
);
533 return OO
.ui
.$defaultOverlay
;
537 * Message store for the default implementation of OO.ui.msg.
539 * Environments that provide a localization system should not use this, but should override
540 * OO.ui.msg altogether.
544 OO
.ui
.msg
.messages
= {
545 "ooui-outline-control-move-down": "Move item down",
546 "ooui-outline-control-move-up": "Move item up",
547 "ooui-outline-control-remove": "Remove item",
548 "ooui-toolbar-more": "More",
549 "ooui-toolgroup-expand": "More",
550 "ooui-toolgroup-collapse": "Fewer",
551 "ooui-item-remove": "Remove",
552 "ooui-dialog-message-accept": "OK",
553 "ooui-dialog-message-reject": "Cancel",
554 "ooui-dialog-process-error": "Something went wrong",
555 "ooui-dialog-process-dismiss": "Dismiss",
556 "ooui-dialog-process-retry": "Try again",
557 "ooui-dialog-process-continue": "Continue",
558 "ooui-combobox-button-label": "Dropdown for combobox",
559 "ooui-selectfile-button-select": "Select a file",
560 "ooui-selectfile-not-supported": "File selection is not supported",
561 "ooui-selectfile-placeholder": "No file is selected",
562 "ooui-selectfile-dragdrop-placeholder": "Drop file here",
563 "ooui-field-help": "Help"
571 * Namespace for OOUI mixins.
573 * Mixins are named according to the type of object they are intended to
574 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
575 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
576 * is intended to be mixed in to an instance of OO.ui.Widget.
584 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
585 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not
586 * have events connected to them and can't be interacted with.
592 * @param {Object} [config] Configuration options
593 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are
594 * added to the top level (e.g., the outermost div) of the element. See the
595 * [OOUI documentation on MediaWiki][2] for an example.
596 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches#cssExample
597 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
598 * @cfg {string} [text] Text to insert
599 * @cfg {Array} [content] An array of content elements to append (after #text).
600 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
601 * Instances of OO.ui.Element will have their $element appended.
602 * @cfg {jQuery} [$content] Content elements to append (after #text).
603 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
604 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number,
606 * Data can also be specified with the #setData method.
608 OO
.ui
.Element
= function OoUiElement( config
) {
609 if ( OO
.ui
.isDemo
) {
610 this.initialConfig
= config
;
612 // Configuration initialization
613 config
= config
|| {};
616 this.$ = function () {
617 OO
.ui
.warnDeprecation( 'this.$ is deprecated, use global $ instead' );
618 return $.apply( this, arguments
);
620 this.elementId
= null;
622 this.data
= config
.data
;
623 this.$element
= config
.$element
||
624 $( document
.createElement( this.getTagName() ) );
625 this.elementGroup
= null;
628 if ( Array
.isArray( config
.classes
) ) {
629 this.$element
.addClass( config
.classes
);
632 this.setElementId( config
.id
);
635 this.$element
.text( config
.text
);
637 if ( config
.content
) {
638 // The `content` property treats plain strings as text; use an
639 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
640 // appropriate $element appended.
641 this.$element
.append( config
.content
.map( function ( v
) {
642 if ( typeof v
=== 'string' ) {
643 // Escape string so it is properly represented in HTML.
644 // Don't create empty text nodes for empty strings.
645 return v
? document
.createTextNode( v
) : undefined;
646 } else if ( v
instanceof OO
.ui
.HtmlSnippet
) {
649 } else if ( v
instanceof OO
.ui
.Element
) {
655 if ( config
.$content
) {
656 // The `$content` property treats plain strings as HTML.
657 this.$element
.append( config
.$content
);
663 OO
.initClass( OO
.ui
.Element
);
665 /* Static Properties */
668 * The name of the HTML tag used by the element.
670 * The static value may be ignored if the #getTagName method is overridden.
676 OO
.ui
.Element
.static.tagName
= 'div';
681 * Reconstitute a JavaScript object corresponding to a widget created
682 * by the PHP implementation.
684 * @param {string|HTMLElement|jQuery} idOrNode
685 * A DOM id (if a string) or node for the widget to infuse.
686 * @param {Object} [config] Configuration options
687 * @return {OO.ui.Element}
688 * The `OO.ui.Element` corresponding to this (infusable) document node.
689 * For `Tag` objects emitted on the HTML side (used occasionally for content)
690 * the value returned is a newly-created Element wrapping around the existing
693 OO
.ui
.Element
.static.infuse = function ( idOrNode
, config
) {
694 var obj
= OO
.ui
.Element
.static.unsafeInfuse( idOrNode
, config
, false );
696 if ( typeof idOrNode
=== 'string' ) {
697 // IDs deprecated since 0.29.7
698 OO
.ui
.warnDeprecation(
699 'Passing a string ID to infuse is deprecated. Use an HTMLElement or jQuery collection instead.'
702 // Verify that the type matches up.
703 // FIXME: uncomment after T89721 is fixed, see T90929.
705 if ( !( obj instanceof this['class'] ) ) {
706 throw new Error( 'Infusion type mismatch!' );
713 * Implementation helper for `infuse`; skips the type check and has an
714 * extra property so that only the top-level invocation touches the DOM.
717 * @param {string|HTMLElement|jQuery} idOrNode
718 * @param {Object} [config] Configuration options
719 * @param {jQuery.Promise} [domPromise] A promise that will be resolved
720 * when the top-level widget of this infusion is inserted into DOM,
721 * replacing the original node; only used internally.
722 * @return {OO.ui.Element}
724 OO
.ui
.Element
.static.unsafeInfuse = function ( idOrNode
, config
, domPromise
) {
725 // look for a cached result of a previous infusion.
726 var id
, $elem
, error
, data
, cls
, parts
, parent
, obj
, top
, state
, infusedChildren
;
727 if ( typeof idOrNode
=== 'string' ) {
729 $elem
= $( document
.getElementById( id
) );
731 $elem
= $( idOrNode
);
732 id
= $elem
.attr( 'id' );
734 if ( !$elem
.length
) {
735 if ( typeof idOrNode
=== 'string' ) {
736 error
= 'Widget not found: ' + idOrNode
;
737 } else if ( idOrNode
&& idOrNode
.selector
) {
738 error
= 'Widget not found: ' + idOrNode
.selector
;
740 error
= 'Widget not found';
742 throw new Error( error
);
744 if ( $elem
[ 0 ].oouiInfused
) {
745 $elem
= $elem
[ 0 ].oouiInfused
;
747 data
= $elem
.data( 'ooui-infused' );
750 if ( data
=== true ) {
751 throw new Error( 'Circular dependency! ' + id
);
754 // Pick up dynamic state, like focus, value of form inputs, scroll position, etc.
755 state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
756 // Restore dynamic state after the new element is re-inserted into DOM under
758 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
759 infusedChildren
= $elem
.data( 'ooui-infused-children' );
760 if ( infusedChildren
&& infusedChildren
.length
) {
761 infusedChildren
.forEach( function ( data
) {
762 var state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
763 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
769 data
= $elem
.attr( 'data-ooui' );
771 throw new Error( 'No infusion data found: ' + id
);
774 data
= JSON
.parse( data
);
778 if ( !( data
&& data
._
) ) {
779 throw new Error( 'No valid infusion data found: ' + id
);
781 if ( data
._
=== 'Tag' ) {
782 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
783 return new OO
.ui
.Element( $.extend( {}, config
, { $element
: $elem
} ) );
785 parts
= data
._
.split( '.' );
786 cls
= OO
.getProp
.apply( OO
, [ window
].concat( parts
) );
787 if ( cls
=== undefined ) {
788 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
791 // Verify that we're creating an OO.ui.Element instance
794 while ( parent
!== undefined ) {
795 if ( parent
=== OO
.ui
.Element
) {
800 parent
= parent
.parent
;
803 if ( parent
!== OO
.ui
.Element
) {
804 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
809 domPromise
= top
.promise();
811 $elem
.data( 'ooui-infused', true ); // prevent loops
812 data
.id
= id
; // implicit
813 infusedChildren
= [];
814 data
= OO
.copy( data
, null, function deserialize( value
) {
816 if ( OO
.isPlainObject( value
) ) {
818 infused
= OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, config
, domPromise
);
819 infusedChildren
.push( infused
);
820 // Flatten the structure
821 infusedChildren
.push
.apply(
823 infused
.$element
.data( 'ooui-infused-children' ) || []
825 infused
.$element
.removeData( 'ooui-infused-children' );
828 if ( value
.html
!== undefined ) {
829 return new OO
.ui
.HtmlSnippet( value
.html
);
833 // allow widgets to reuse parts of the DOM
834 data
= cls
.static.reusePreInfuseDOM( $elem
[ 0 ], data
);
835 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
836 state
= cls
.static.gatherPreInfuseState( $elem
[ 0 ], data
);
838 // eslint-disable-next-line new-cap
839 obj
= new cls( $.extend( {}, config
, data
) );
840 // If anyone is holding a reference to the old DOM element,
841 // let's allow them to OO.ui.infuse() it and do what they expect, see T105828.
842 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
843 $elem
[ 0 ].oouiInfused
= obj
.$element
;
844 // now replace old DOM with this new DOM.
846 // An efficient constructor might be able to reuse the entire DOM tree of the original
847 // element, so only mutate the DOM if we need to.
848 if ( $elem
[ 0 ] !== obj
.$element
[ 0 ] ) {
849 $elem
.replaceWith( obj
.$element
);
853 obj
.$element
.data( 'ooui-infused', obj
);
854 obj
.$element
.data( 'ooui-infused-children', infusedChildren
);
855 // set the 'data-ooui' attribute so we can identify infused widgets
856 obj
.$element
.attr( 'data-ooui', '' );
857 // restore dynamic state after the new element is inserted into DOM
858 domPromise
.done( obj
.restorePreInfuseState
.bind( obj
, state
) );
863 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
865 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
866 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
867 * constructor, which will be given the enhanced config.
870 * @param {HTMLElement} node
871 * @param {Object} config
874 OO
.ui
.Element
.static.reusePreInfuseDOM = function ( node
, config
) {
879 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of an HTML DOM
880 * node (and its children) that represent an Element of the same class and the given configuration,
881 * generated by the PHP implementation.
883 * This method is called just before `node` is detached from the DOM. The return value of this
884 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
885 * is inserted into DOM to replace `node`.
888 * @param {HTMLElement} node
889 * @param {Object} config
892 OO
.ui
.Element
.static.gatherPreInfuseState = function () {
897 * Get a jQuery function within a specific document.
900 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
901 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
903 * @return {Function} Bound jQuery function
905 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
906 function wrapper( selector
) {
907 return $( selector
, wrapper
.context
);
910 wrapper
.context
= this.getDocument( context
);
913 wrapper
.$iframe
= $iframe
;
920 * Get the document of an element.
923 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
924 * @return {HTMLDocument|null} Document object
926 OO
.ui
.Element
.static.getDocument = function ( obj
) {
927 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
928 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
929 // Empty jQuery selections might have a context
936 ( obj
.nodeType
=== Node
.DOCUMENT_NODE
&& obj
) ||
941 * Get the window of an element or document.
944 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
945 * @return {Window} Window object
947 OO
.ui
.Element
.static.getWindow = function ( obj
) {
948 var doc
= this.getDocument( obj
);
949 return doc
.defaultView
;
953 * Get the direction of an element or document.
956 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
957 * @return {string} Text direction, either 'ltr' or 'rtl'
959 OO
.ui
.Element
.static.getDir = function ( obj
) {
962 if ( obj
instanceof $ ) {
965 isDoc
= obj
.nodeType
=== Node
.DOCUMENT_NODE
;
966 isWin
= obj
.document
!== undefined;
967 if ( isDoc
|| isWin
) {
973 return $( obj
).css( 'direction' );
977 * Get the offset between two frames.
979 * TODO: Make this function not use recursion.
982 * @param {Window} from Window of the child frame
983 * @param {Window} [to=window] Window of the parent frame
984 * @param {Object} [offset] Offset to start with, used internally
985 * @return {Object} Offset object, containing left and top properties
987 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
988 var i
, len
, frames
, frame
, rect
;
994 offset
= { top
: 0, left
: 0 };
996 if ( from.parent
=== from ) {
1000 // Get iframe element
1001 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
1002 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
1003 if ( frames
[ i
].contentWindow
=== from ) {
1004 frame
= frames
[ i
];
1009 // Recursively accumulate offset values
1011 rect
= frame
.getBoundingClientRect();
1012 offset
.left
+= rect
.left
;
1013 offset
.top
+= rect
.top
;
1014 if ( from !== to
) {
1015 this.getFrameOffset( from.parent
, offset
);
1022 * Get the offset between two elements.
1024 * The two elements may be in a different frame, but in that case the frame $element is in must
1025 * be contained in the frame $anchor is in.
1028 * @param {jQuery} $element Element whose position to get
1029 * @param {jQuery} $anchor Element to get $element's position relative to
1030 * @return {Object} Translated position coordinates, containing top and left properties
1032 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
1033 var iframe
, iframePos
,
1034 pos
= $element
.offset(),
1035 anchorPos
= $anchor
.offset(),
1036 elementDocument
= this.getDocument( $element
),
1037 anchorDocument
= this.getDocument( $anchor
);
1039 // If $element isn't in the same document as $anchor, traverse up
1040 while ( elementDocument
!== anchorDocument
) {
1041 iframe
= elementDocument
.defaultView
.frameElement
;
1043 throw new Error( '$element frame is not contained in $anchor frame' );
1045 iframePos
= $( iframe
).offset();
1046 pos
.left
+= iframePos
.left
;
1047 pos
.top
+= iframePos
.top
;
1048 elementDocument
= iframe
.ownerDocument
;
1050 pos
.left
-= anchorPos
.left
;
1051 pos
.top
-= anchorPos
.top
;
1056 * Get element border sizes.
1059 * @param {HTMLElement} el Element to measure
1060 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1062 OO
.ui
.Element
.static.getBorders = function ( el
) {
1063 var doc
= el
.ownerDocument
,
1064 win
= doc
.defaultView
,
1065 style
= win
.getComputedStyle( el
, null ),
1067 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
1068 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
1069 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
1070 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
1081 * Get dimensions of an element or window.
1084 * @param {HTMLElement|Window} el Element to measure
1085 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1087 OO
.ui
.Element
.static.getDimensions = function ( el
) {
1089 doc
= el
.ownerDocument
|| el
.document
,
1090 win
= doc
.defaultView
;
1092 if ( win
=== el
|| el
=== doc
.documentElement
) {
1095 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
1097 top
: $win
.scrollTop(),
1098 left
: $win
.scrollLeft()
1100 scrollbar
: { right
: 0, bottom
: 0 },
1104 bottom
: $win
.innerHeight(),
1105 right
: $win
.innerWidth()
1111 borders
: this.getBorders( el
),
1113 top
: $el
.scrollTop(),
1114 left
: $el
.scrollLeft()
1117 right
: $el
.innerWidth() - el
.clientWidth
,
1118 bottom
: $el
.innerHeight() - el
.clientHeight
1120 rect
: el
.getBoundingClientRect()
1126 * Get the number of pixels that an element's content is scrolled to the left.
1128 * Adapted from <https://github.com/othree/jquery.rtl-scroll-type>.
1129 * Original code copyright 2012 Wei-Ko Kao, licensed under the MIT License.
1131 * This function smooths out browser inconsistencies (nicely described in the README at
1132 * <https://github.com/othree/jquery.rtl-scroll-type>) and produces a result consistent
1133 * with Firefox's 'scrollLeft', which seems the sanest.
1137 * @param {HTMLElement|Window} el Element to measure
1138 * @return {number} Scroll position from the left.
1139 * If the element's direction is LTR, this is a positive number between `0` (initial scroll
1140 * position) and `el.scrollWidth - el.clientWidth` (furthest possible scroll position).
1141 * If the element's direction is RTL, this is a negative number between `0` (initial scroll
1142 * position) and `-el.scrollWidth + el.clientWidth` (furthest possible scroll position).
1144 OO
.ui
.Element
.static.getScrollLeft
= ( function () {
1145 var rtlScrollType
= null;
1148 var $definer
= $( '<div>' ).attr( {
1150 style
: 'font-size: 14px; width: 4px; height: 1px; position: absolute; top: -1000px; overflow: scroll;'
1152 definer
= $definer
[ 0 ];
1154 $definer
.appendTo( 'body' );
1155 if ( definer
.scrollLeft
> 0 ) {
1157 rtlScrollType
= 'default';
1159 definer
.scrollLeft
= 1;
1160 if ( definer
.scrollLeft
=== 0 ) {
1161 // Firefox, old Opera
1162 rtlScrollType
= 'negative';
1164 // Internet Explorer, Edge
1165 rtlScrollType
= 'reverse';
1171 return function getScrollLeft( el
) {
1172 var isRoot
= el
.window
=== el
||
1173 el
=== el
.ownerDocument
.body
||
1174 el
=== el
.ownerDocument
.documentElement
,
1175 scrollLeft
= isRoot
? $( window
).scrollLeft() : el
.scrollLeft
,
1176 // All browsers use the correct scroll type ('negative') on the root, so don't
1177 // do any fixups when looking at the root element
1178 direction
= isRoot
? 'ltr' : $( el
).css( 'direction' );
1180 if ( direction
=== 'rtl' ) {
1181 if ( rtlScrollType
=== null ) {
1184 if ( rtlScrollType
=== 'reverse' ) {
1185 scrollLeft
= -scrollLeft
;
1186 } else if ( rtlScrollType
=== 'default' ) {
1187 scrollLeft
= scrollLeft
- el
.scrollWidth
+ el
.clientWidth
;
1196 * Get the root scrollable element of given element's document.
1198 * On Blink-based browsers (Chrome etc.), `document.documentElement` can't be used to get or set
1199 * the scrollTop property; instead we have to use `document.body`. Changing and testing the value
1200 * lets us use 'body' or 'documentElement' based on what is working.
1202 * https://code.google.com/p/chromium/issues/detail?id=303131
1205 * @param {HTMLElement} el Element to find root scrollable parent for
1206 * @return {HTMLElement} Scrollable parent, `document.body` or `document.documentElement`
1207 * depending on browser
1209 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1210 var scrollTop
, body
;
1212 if ( OO
.ui
.scrollableElement
=== undefined ) {
1213 body
= el
.ownerDocument
.body
;
1214 scrollTop
= body
.scrollTop
;
1217 // In some browsers (observed in Chrome 56 on Linux Mint 18.1),
1218 // body.scrollTop doesn't become exactly 1, but a fractional value like 0.76
1219 if ( Math
.round( body
.scrollTop
) === 1 ) {
1220 body
.scrollTop
= scrollTop
;
1221 OO
.ui
.scrollableElement
= 'body';
1223 OO
.ui
.scrollableElement
= 'documentElement';
1227 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1231 * Get closest scrollable container.
1233 * Traverses up until either a scrollable element or the root is reached, in which case the root
1234 * scrollable element will be returned (see #getRootScrollableElement).
1237 * @param {HTMLElement} el Element to find scrollable container for
1238 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1239 * @return {HTMLElement} Closest scrollable container
1241 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1243 // Browsers do not correctly return the computed value of 'overflow' when 'overflow-x' and
1244 // 'overflow-y' have different values, so we need to check the separate properties.
1245 props
= [ 'overflow-x', 'overflow-y' ],
1246 $parent
= $( el
).parent();
1248 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1249 props
= [ 'overflow-' + dimension
];
1252 // Special case for the document root (which doesn't really have any scrollable container,
1253 // since it is the ultimate scrollable container, but this is probably saner than null or
1255 if ( $( el
).is( 'html, body' ) ) {
1256 return this.getRootScrollableElement( el
);
1259 while ( $parent
.length
) {
1260 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1261 return $parent
[ 0 ];
1265 val
= $parent
.css( props
[ i
] );
1266 // We assume that elements with 'overflow' (in any direction) set to 'hidden' will
1267 // never be scrolled in that direction, but they can actually be scrolled
1268 // programatically. The user can unintentionally perform a scroll in such case even if
1269 // the application doesn't scroll programatically, e.g. when jumping to an anchor, or
1270 // when using built-in find functionality.
1271 // This could cause funny issues...
1272 if ( val
=== 'auto' || val
=== 'scroll' ) {
1273 return $parent
[ 0 ];
1276 $parent
= $parent
.parent();
1278 // The element is unattached... return something mostly sane
1279 return this.getRootScrollableElement( el
);
1283 * Scroll element into view.
1286 * @param {HTMLElement|Object} elOrPosition Element to scroll into view
1287 * @param {Object} [config] Configuration options
1288 * @param {string} [config.animate=true] Animate to the new scroll offset.
1289 * @param {string} [config.duration='fast'] jQuery animation duration value
1290 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1291 * to scroll in both directions
1292 * @param {Object} [config.padding] Additional padding on the container to scroll past.
1293 * Object containing any of 'top', 'bottom', 'left', or 'right' as numbers.
1294 * @param {Object} [config.scrollContainer] Scroll container. Defaults to
1295 * getClosestScrollableContainer of the element.
1296 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1298 OO
.ui
.Element
.static.scrollIntoView = function ( elOrPosition
, config
) {
1299 var position
, animations
, container
, $container
, elementPosition
, containerDimensions
,
1300 $window
, padding
, animate
, method
,
1301 deferred
= $.Deferred();
1303 // Configuration initialization
1304 config
= config
|| {};
1306 padding
= $.extend( {
1311 }, config
.padding
);
1313 animate
= config
.animate
!== false;
1316 elementPosition
= elOrPosition
instanceof HTMLElement
?
1317 this.getDimensions( elOrPosition
).rect
:
1319 container
= config
.scrollContainer
|| (
1320 elOrPosition
instanceof HTMLElement
?
1321 this.getClosestScrollableContainer( elOrPosition
, config
.direction
) :
1322 // No scrollContainer or element
1323 this.getClosestScrollableContainer( document
.body
)
1325 $container
= $( container
);
1326 containerDimensions
= this.getDimensions( container
);
1327 $window
= $( this.getWindow( container
) );
1329 // Compute the element's position relative to the container
1330 if ( $container
.is( 'html, body' ) ) {
1331 // If the scrollable container is the root, this is easy
1333 top
: elementPosition
.top
,
1334 bottom
: $window
.innerHeight() - elementPosition
.bottom
,
1335 left
: elementPosition
.left
,
1336 right
: $window
.innerWidth() - elementPosition
.right
1339 // Otherwise, we have to subtract el's coordinates from container's coordinates
1341 top
: elementPosition
.top
-
1342 ( containerDimensions
.rect
.top
+ containerDimensions
.borders
.top
),
1343 bottom
: containerDimensions
.rect
.bottom
- containerDimensions
.borders
.bottom
-
1344 containerDimensions
.scrollbar
.bottom
- elementPosition
.bottom
,
1345 left
: elementPosition
.left
-
1346 ( containerDimensions
.rect
.left
+ containerDimensions
.borders
.left
),
1347 right
: containerDimensions
.rect
.right
- containerDimensions
.borders
.right
-
1348 containerDimensions
.scrollbar
.right
- elementPosition
.right
1352 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1353 if ( position
.top
< padding
.top
) {
1354 animations
.scrollTop
= containerDimensions
.scroll
.top
+ position
.top
- padding
.top
;
1355 } else if ( position
.bottom
< padding
.bottom
) {
1356 animations
.scrollTop
= containerDimensions
.scroll
.top
+
1357 // Scroll the bottom into view, but not at the expense
1358 // of scrolling the top out of view
1359 Math
.min( position
.top
- padding
.top
, -position
.bottom
+ padding
.bottom
);
1362 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1363 if ( position
.left
< padding
.left
) {
1364 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ position
.left
- padding
.left
;
1365 } else if ( position
.right
< padding
.right
) {
1366 animations
.scrollLeft
= containerDimensions
.scroll
.left
+
1367 // Scroll the right into view, but not at the expense
1368 // of scrolling the left out of view
1369 Math
.min( position
.left
- padding
.left
, -position
.right
+ padding
.right
);
1372 if ( !$.isEmptyObject( animations
) ) {
1374 // eslint-disable-next-line no-jquery/no-animate
1375 $container
.stop( true ).animate( animations
, config
.duration
=== undefined ? 'fast' : config
.duration
);
1376 $container
.queue( function ( next
) {
1381 $container
.stop( true );
1382 for ( method
in animations
) {
1383 $container
[ method
]( animations
[ method
] );
1390 return deferred
.promise();
1394 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1395 * and reserve space for them, because it probably doesn't.
1397 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1398 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1399 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a
1400 * reflow, and then reattach (or show) them back.
1403 * @param {HTMLElement} el Element to reconsider the scrollbars on
1405 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1406 var i
, len
, scrollLeft
, scrollTop
, nodes
= [];
1407 // Save scroll position
1408 scrollLeft
= el
.scrollLeft
;
1409 scrollTop
= el
.scrollTop
;
1410 // Detach all children
1411 while ( el
.firstChild
) {
1412 nodes
.push( el
.firstChild
);
1413 el
.removeChild( el
.firstChild
);
1416 // eslint-disable-next-line no-void
1417 void el
.offsetHeight
;
1418 // Reattach all children
1419 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1420 el
.appendChild( nodes
[ i
] );
1422 // Restore scroll position (no-op if scrollbars disappeared)
1423 el
.scrollLeft
= scrollLeft
;
1424 el
.scrollTop
= scrollTop
;
1430 * Toggle visibility of an element.
1432 * @param {boolean} [show] Make element visible, omit to toggle visibility
1435 * @return {OO.ui.Element} The element, for chaining
1437 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1438 show
= show
=== undefined ? !this.visible
: !!show
;
1440 if ( show
!== this.isVisible() ) {
1441 this.visible
= show
;
1442 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1443 this.emit( 'toggle', show
);
1450 * Check if element is visible.
1452 * @return {boolean} element is visible
1454 OO
.ui
.Element
.prototype.isVisible = function () {
1455 return this.visible
;
1461 * @return {Mixed} Element data
1463 OO
.ui
.Element
.prototype.getData = function () {
1470 * @param {Mixed} data Element data
1472 * @return {OO.ui.Element} The element, for chaining
1474 OO
.ui
.Element
.prototype.setData = function ( data
) {
1480 * Set the element has an 'id' attribute.
1482 * @param {string} id
1484 * @return {OO.ui.Element} The element, for chaining
1486 OO
.ui
.Element
.prototype.setElementId = function ( id
) {
1487 this.elementId
= id
;
1488 this.$element
.attr( 'id', id
);
1493 * Ensure that the element has an 'id' attribute, setting it to an unique value if it's missing,
1494 * and return its value.
1498 OO
.ui
.Element
.prototype.getElementId = function () {
1499 if ( this.elementId
=== null ) {
1500 this.setElementId( OO
.ui
.generateElementId() );
1502 return this.elementId
;
1506 * Check if element supports one or more methods.
1508 * @param {string|string[]} methods Method or list of methods to check
1509 * @return {boolean} All methods are supported
1511 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1515 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1516 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1517 if ( typeof this[ methods
[ i
] ] === 'function' ) {
1522 return methods
.length
=== support
;
1526 * Update the theme-provided classes.
1528 * @localdoc This is called in element mixins and widget classes any time state changes.
1529 * Updating is debounced, minimizing overhead of changing multiple attributes and
1530 * guaranteeing that theme updates do not occur within an element's constructor
1532 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1533 OO
.ui
.theme
.queueUpdateElementClasses( this );
1537 * Get the HTML tag name.
1539 * Override this method to base the result on instance information.
1541 * @return {string} HTML tag name
1543 OO
.ui
.Element
.prototype.getTagName = function () {
1544 return this.constructor.static.tagName
;
1548 * Check if the element is attached to the DOM
1550 * @return {boolean} The element is attached to the DOM
1552 OO
.ui
.Element
.prototype.isElementAttached = function () {
1553 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1557 * Get the DOM document.
1559 * @return {HTMLDocument} Document object
1561 OO
.ui
.Element
.prototype.getElementDocument = function () {
1562 // Don't cache this in other ways either because subclasses could can change this.$element
1563 return OO
.ui
.Element
.static.getDocument( this.$element
);
1567 * Get the DOM window.
1569 * @return {Window} Window object
1571 OO
.ui
.Element
.prototype.getElementWindow = function () {
1572 return OO
.ui
.Element
.static.getWindow( this.$element
);
1576 * Get closest scrollable container.
1578 * @return {HTMLElement} Closest scrollable container
1580 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1581 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1585 * Get group element is in.
1587 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1589 OO
.ui
.Element
.prototype.getElementGroup = function () {
1590 return this.elementGroup
;
1594 * Set group element is in.
1596 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1598 * @return {OO.ui.Element} The element, for chaining
1600 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1601 this.elementGroup
= group
;
1606 * Scroll element into view.
1608 * @param {Object} [config] Configuration options
1609 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1611 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1613 !this.isElementAttached() ||
1614 !this.isVisible() ||
1615 ( this.getElementGroup() && !this.getElementGroup().isVisible() )
1617 return $.Deferred().resolve();
1619 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1623 * Restore the pre-infusion dynamic state for this widget.
1625 * This method is called after #$element has been inserted into DOM. The parameter is the return
1626 * value of #gatherPreInfuseState.
1629 * @param {Object} state
1631 OO
.ui
.Element
.prototype.restorePreInfuseState = function () {
1635 * Wraps an HTML snippet for use with configuration values which default
1636 * to strings. This bypasses the default html-escaping done to string
1642 * @param {string} [content] HTML content
1644 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
1646 this.content
= content
;
1651 OO
.initClass( OO
.ui
.HtmlSnippet
);
1658 * @return {string} Unchanged HTML snippet.
1660 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
1661 return this.content
;
1665 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in
1666 * a way that is centrally controlled and can be updated dynamically. Layouts can be, and usually
1668 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout},
1669 * {@link OO.ui.FormLayout FormLayout}, {@link OO.ui.PanelLayout PanelLayout},
1670 * {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1671 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout}
1672 * for more information and examples.
1676 * @extends OO.ui.Element
1677 * @mixins OO.EventEmitter
1680 * @param {Object} [config] Configuration options
1682 OO
.ui
.Layout
= function OoUiLayout( config
) {
1683 // Configuration initialization
1684 config
= config
|| {};
1686 // Parent constructor
1687 OO
.ui
.Layout
.parent
.call( this, config
);
1689 // Mixin constructors
1690 OO
.EventEmitter
.call( this );
1693 this.$element
.addClass( 'oo-ui-layout' );
1698 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1699 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1704 * Reset scroll offsets
1707 * @return {OO.ui.Layout} The layout, for chaining
1709 OO
.ui
.Layout
.prototype.resetScroll = function () {
1710 this.$element
[ 0 ].scrollTop
= 0;
1711 // TODO: Reset scrollLeft in an RTL-aware manner, see OO.ui.Element.static.getScrollLeft.
1717 * Widgets are compositions of one or more OOUI elements that users can both view
1718 * and interact with. All widgets can be configured and modified via a standard API,
1719 * and their state can change dynamically according to a model.
1723 * @extends OO.ui.Element
1724 * @mixins OO.EventEmitter
1727 * @param {Object} [config] Configuration options
1728 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1729 * appearance reflects this state.
1731 OO
.ui
.Widget
= function OoUiWidget( config
) {
1732 // Initialize config
1733 config
= $.extend( { disabled
: false }, config
);
1735 // Parent constructor
1736 OO
.ui
.Widget
.parent
.call( this, config
);
1738 // Mixin constructors
1739 OO
.EventEmitter
.call( this );
1742 this.disabled
= null;
1743 this.wasDisabled
= null;
1746 this.$element
.addClass( 'oo-ui-widget' );
1747 this.setDisabled( !!config
.disabled
);
1752 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1753 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1760 * A 'disable' event is emitted when the disabled state of the widget changes
1761 * (i.e. on disable **and** enable).
1763 * @param {boolean} disabled Widget is disabled
1769 * A 'toggle' event is emitted when the visibility of the widget changes.
1771 * @param {boolean} visible Widget is visible
1777 * Check if the widget is disabled.
1779 * @return {boolean} Widget is disabled
1781 OO
.ui
.Widget
.prototype.isDisabled = function () {
1782 return this.disabled
;
1786 * Set the 'disabled' state of the widget.
1788 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1790 * @param {boolean} disabled Disable widget
1792 * @return {OO.ui.Widget} The widget, for chaining
1794 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
1797 this.disabled
= !!disabled
;
1798 isDisabled
= this.isDisabled();
1799 if ( isDisabled
!== this.wasDisabled
) {
1800 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
1801 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
1802 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
1803 this.emit( 'disable', isDisabled
);
1804 this.updateThemeClasses();
1806 this.wasDisabled
= isDisabled
;
1812 * Update the disabled state, in case of changes in parent widget.
1815 * @return {OO.ui.Widget} The widget, for chaining
1817 OO
.ui
.Widget
.prototype.updateDisabled = function () {
1818 this.setDisabled( this.disabled
);
1823 * Get an ID of a labelable node which is part of this widget, if any, to be used for `<label for>`
1826 * If this function returns null, the widget should have a meaningful #simulateLabelClick method
1829 * @return {string|null} The ID of the labelable element
1831 OO
.ui
.Widget
.prototype.getInputId = function () {
1836 * Simulate the behavior of clicking on a label (a HTML `<label>` element) bound to this input.
1837 * HTML only allows `<label>` to act on specific "labelable" elements; complex widgets might need to
1838 * override this method to provide intuitive, accessible behavior.
1840 * By default, this does nothing. OO.ui.mixin.TabIndexedElement overrides it for focusable widgets.
1841 * Individual widgets may override it too.
1843 * This method is called by OO.ui.LabelWidget and OO.ui.FieldLayout. It should not be called
1846 OO
.ui
.Widget
.prototype.simulateLabelClick = function () {
1857 OO
.ui
.Theme
= function OoUiTheme() {
1858 this.elementClassesQueue
= [];
1859 this.debouncedUpdateQueuedElementClasses
= OO
.ui
.debounce( this.updateQueuedElementClasses
);
1864 OO
.initClass( OO
.ui
.Theme
);
1869 * Get a list of classes to be applied to a widget.
1871 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
1872 * otherwise state transitions will not work properly.
1874 * @param {OO.ui.Element} element Element for which to get classes
1875 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1877 OO
.ui
.Theme
.prototype.getElementClasses = function () {
1878 return { on
: [], off
: [] };
1882 * Update CSS classes provided by the theme.
1884 * For elements with theme logic hooks, this should be called any time there's a state change.
1886 * @param {OO.ui.Element} element Element for which to update classes
1888 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
1889 var $elements
= $( [] ),
1890 classes
= this.getElementClasses( element
);
1892 if ( element
.$icon
) {
1893 $elements
= $elements
.add( element
.$icon
);
1895 if ( element
.$indicator
) {
1896 $elements
= $elements
.add( element
.$indicator
);
1900 .removeClass( classes
.off
)
1901 .addClass( classes
.on
);
1907 OO
.ui
.Theme
.prototype.updateQueuedElementClasses = function () {
1909 for ( i
= 0; i
< this.elementClassesQueue
.length
; i
++ ) {
1910 this.updateElementClasses( this.elementClassesQueue
[ i
] );
1913 this.elementClassesQueue
= [];
1917 * Queue #updateElementClasses to be called for this element.
1919 * @localdoc QUnit tests override this method to directly call #queueUpdateElementClasses,
1920 * to make them synchronous.
1922 * @param {OO.ui.Element} element Element for which to update classes
1924 OO
.ui
.Theme
.prototype.queueUpdateElementClasses = function ( element
) {
1925 // Keep items in the queue unique. Use lastIndexOf to start checking from the end because that's
1926 // the most common case (this method is often called repeatedly for the same element).
1927 if ( this.elementClassesQueue
.lastIndexOf( element
) !== -1 ) {
1930 this.elementClassesQueue
.push( element
);
1931 this.debouncedUpdateQueuedElementClasses();
1935 * Get the transition duration in milliseconds for dialogs opening/closing
1937 * The dialog should be fully rendered this many milliseconds after the
1938 * ready process has executed.
1940 * @return {number} Transition duration in milliseconds
1942 OO
.ui
.Theme
.prototype.getDialogTransitionDuration = function () {
1947 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
1948 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
1949 * order in which users will navigate through the focusable elements via the Tab key.
1952 * // TabIndexedElement is mixed into the ButtonWidget class
1953 * // to provide a tabIndex property.
1954 * var button1 = new OO.ui.ButtonWidget( {
1958 * button2 = new OO.ui.ButtonWidget( {
1962 * button3 = new OO.ui.ButtonWidget( {
1966 * button4 = new OO.ui.ButtonWidget( {
1970 * $( document.body ).append(
1981 * @param {Object} [config] Configuration options
1982 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
1983 * the functionality is applied to the element created by the class ($element). If a different
1984 * element is specified, the tabindex functionality will be applied to it instead.
1985 * @cfg {string|number|null} [tabIndex=0] Number that specifies the element’s position in the
1986 * tab-navigation order (e.g., 1 for the first focusable element). Use 0 to use the default
1987 * navigation order; use -1 to remove the element from the tab-navigation flow.
1989 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
1990 // Configuration initialization
1991 config
= $.extend( { tabIndex
: 0 }, config
);
1994 this.$tabIndexed
= null;
1995 this.tabIndex
= null;
1998 this.connect( this, {
1999 disable
: 'onTabIndexedElementDisable'
2003 this.setTabIndex( config
.tabIndex
);
2004 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
2009 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
2014 * Set the element that should use the tabindex functionality.
2016 * This method is used to retarget a tabindex mixin so that its functionality applies
2017 * to the specified element. If an element is currently using the functionality, the mixin’s
2018 * effect on that element is removed before the new element is set up.
2020 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
2022 * @return {OO.ui.Element} The element, for chaining
2024 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
2025 var tabIndex
= this.tabIndex
;
2026 // Remove attributes from old $tabIndexed
2027 this.setTabIndex( null );
2028 // Force update of new $tabIndexed
2029 this.$tabIndexed
= $tabIndexed
;
2030 this.tabIndex
= tabIndex
;
2031 return this.updateTabIndex();
2035 * Set the value of the tabindex.
2037 * @param {string|number|null} tabIndex Tabindex value, or `null` for no tabindex
2039 * @return {OO.ui.Element} The element, for chaining
2041 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
2042 tabIndex
= /^-?\d+$/.test( tabIndex
) ? Number( tabIndex
) : null;
2044 if ( this.tabIndex
!== tabIndex
) {
2045 this.tabIndex
= tabIndex
;
2046 this.updateTabIndex();
2053 * Update the `tabindex` attribute, in case of changes to tab index or
2058 * @return {OO.ui.Element} The element, for chaining
2060 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
2061 if ( this.$tabIndexed
) {
2062 if ( this.tabIndex
!== null ) {
2063 // Do not index over disabled elements
2064 this.$tabIndexed
.attr( {
2065 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
2066 // Support: ChromeVox and NVDA
2067 // These do not seem to inherit aria-disabled from parent elements
2068 'aria-disabled': this.isDisabled().toString()
2071 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
2078 * Handle disable events.
2081 * @param {boolean} disabled Element is disabled
2083 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
2084 this.updateTabIndex();
2088 * Get the value of the tabindex.
2090 * @return {number|null} Tabindex value
2092 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
2093 return this.tabIndex
;
2097 * Get an ID of a focusable element of this widget, if any, to be used for `<label for>` value.
2099 * If the element already has an ID then that is returned, otherwise unique ID is
2100 * generated, set on the element, and returned.
2102 * @return {string|null} The ID of the focusable element
2104 OO
.ui
.mixin
.TabIndexedElement
.prototype.getInputId = function () {
2107 if ( !this.$tabIndexed
) {
2110 if ( !this.isLabelableNode( this.$tabIndexed
) ) {
2114 id
= this.$tabIndexed
.attr( 'id' );
2115 if ( id
=== undefined ) {
2116 id
= OO
.ui
.generateElementId();
2117 this.$tabIndexed
.attr( 'id', id
);
2124 * Whether the node is 'labelable' according to the HTML spec
2125 * (i.e., whether it can be interacted with through a `<label for="…">`).
2126 * See: <https://html.spec.whatwg.org/multipage/forms.html#category-label>.
2129 * @param {jQuery} $node
2132 OO
.ui
.mixin
.TabIndexedElement
.prototype.isLabelableNode = function ( $node
) {
2134 labelableTags
= [ 'button', 'meter', 'output', 'progress', 'select', 'textarea' ],
2135 tagName
= ( $node
.prop( 'tagName' ) || '' ).toLowerCase();
2137 if ( tagName
=== 'input' && $node
.attr( 'type' ) !== 'hidden' ) {
2140 if ( labelableTags
.indexOf( tagName
) !== -1 ) {
2147 * Focus this element.
2150 * @return {OO.ui.Element} The element, for chaining
2152 OO
.ui
.mixin
.TabIndexedElement
.prototype.focus = function () {
2153 if ( !this.isDisabled() ) {
2154 this.$tabIndexed
.trigger( 'focus' );
2160 * Blur this element.
2163 * @return {OO.ui.Element} The element, for chaining
2165 OO
.ui
.mixin
.TabIndexedElement
.prototype.blur = function () {
2166 this.$tabIndexed
.trigger( 'blur' );
2171 * @inheritdoc OO.ui.Widget
2173 OO
.ui
.mixin
.TabIndexedElement
.prototype.simulateLabelClick = function () {
2178 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
2179 * interface element that can be configured with access keys for keyboard interaction.
2180 * See the [OOUI documentation on MediaWiki] [1] for examples.
2182 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches#Buttons
2188 * @param {Object} [config] Configuration options
2189 * @cfg {jQuery} [$button] The button element created by the class.
2190 * If this configuration is omitted, the button element will use a generated `<a>`.
2191 * @cfg {boolean} [framed=true] Render the button with a frame
2193 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
2194 // Configuration initialization
2195 config
= config
|| {};
2198 this.$button
= null;
2200 this.active
= config
.active
!== undefined && config
.active
;
2201 this.onDocumentMouseUpHandler
= this.onDocumentMouseUp
.bind( this );
2202 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
2203 this.onDocumentKeyUpHandler
= this.onDocumentKeyUp
.bind( this );
2204 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
2205 this.onClickHandler
= this.onClick
.bind( this );
2206 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
2209 this.$element
.addClass( 'oo-ui-buttonElement' );
2210 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
2211 this.setButtonElement( config
.$button
|| $( '<a>' ) );
2216 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
2218 /* Static Properties */
2221 * Cancel mouse down events.
2223 * This property is usually set to `true` to prevent the focus from changing when the button is
2225 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and
2226 * {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} use a value of `false` so that dragging
2227 * behavior is possible and mousedown events can be handled by a parent widget.
2231 * @property {boolean}
2233 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
2238 * A 'click' event is emitted when the button element is clicked.
2246 * Set the button element.
2248 * This method is used to retarget a button mixin so that its functionality applies to
2249 * the specified button element instead of the one created by the class. If a button element
2250 * is already set, the method will remove the mixin’s effect on that element.
2252 * @param {jQuery} $button Element to use as button
2254 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
2255 if ( this.$button
) {
2257 .removeClass( 'oo-ui-buttonElement-button' )
2258 .removeAttr( 'role accesskey' )
2260 mousedown
: this.onMouseDownHandler
,
2261 keydown
: this.onKeyDownHandler
,
2262 click
: this.onClickHandler
,
2263 keypress
: this.onKeyPressHandler
2267 this.$button
= $button
2268 .addClass( 'oo-ui-buttonElement-button' )
2270 mousedown
: this.onMouseDownHandler
,
2271 keydown
: this.onKeyDownHandler
,
2272 click
: this.onClickHandler
,
2273 keypress
: this.onKeyPressHandler
2276 // Add `role="button"` on `<a>` elements, where it's needed
2277 // `toUpperCase()` is added for XHTML documents
2278 if ( this.$button
.prop( 'tagName' ).toUpperCase() === 'A' ) {
2279 this.$button
.attr( 'role', 'button' );
2284 * Handles mouse down events.
2287 * @param {jQuery.Event} e Mouse down event
2288 * @return {undefined|boolean} False to prevent default if event is handled
2290 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
2291 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
2294 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
2295 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
2296 // reliably remove the pressed class
2297 this.getElementDocument().addEventListener( 'mouseup', this.onDocumentMouseUpHandler
, true );
2298 // Prevent change of focus unless specifically configured otherwise
2299 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
2305 * Handles document mouse up events.
2308 * @param {MouseEvent} e Mouse up event
2310 OO
.ui
.mixin
.ButtonElement
.prototype.onDocumentMouseUp = function ( e
) {
2311 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
2314 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
2315 // Stop listening for mouseup, since we only needed this once
2316 this.getElementDocument().removeEventListener( 'mouseup', this.onDocumentMouseUpHandler
, true );
2320 * Handles mouse click events.
2323 * @param {jQuery.Event} e Mouse click event
2325 * @return {undefined|boolean} False to prevent default if event is handled
2327 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
2328 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
2329 if ( this.emit( 'click' ) ) {
2336 * Handles key down events.
2339 * @param {jQuery.Event} e Key down event
2341 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
2342 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2345 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
2346 // Run the keyup handler no matter where the key is when the button is let go, so we can
2347 // reliably remove the pressed class
2348 this.getElementDocument().addEventListener( 'keyup', this.onDocumentKeyUpHandler
, true );
2352 * Handles document key up events.
2355 * @param {KeyboardEvent} e Key up event
2357 OO
.ui
.mixin
.ButtonElement
.prototype.onDocumentKeyUp = function ( e
) {
2358 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2361 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
2362 // Stop listening for keyup, since we only needed this once
2363 this.getElementDocument().removeEventListener( 'keyup', this.onDocumentKeyUpHandler
, true );
2367 * Handles key press events.
2370 * @param {jQuery.Event} e Key press event
2372 * @return {undefined|boolean} False to prevent default if event is handled
2374 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
2375 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
2376 if ( this.emit( 'click' ) ) {
2383 * Check if button has a frame.
2385 * @return {boolean} Button is framed
2387 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
2392 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame
2395 * @param {boolean} [framed] Make button framed, omit to toggle
2397 * @return {OO.ui.Element} The element, for chaining
2399 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
2400 framed
= framed
=== undefined ? !this.framed
: !!framed
;
2401 if ( framed
!== this.framed
) {
2402 this.framed
= framed
;
2404 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
2405 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
2406 this.updateThemeClasses();
2413 * Set the button's active state.
2415 * The active state can be set on:
2417 * - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected
2418 * - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on
2419 * - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page
2422 * @param {boolean} value Make button active
2424 * @return {OO.ui.Element} The element, for chaining
2426 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
2427 this.active
= !!value
;
2428 this.$element
.toggleClass( 'oo-ui-buttonElement-active', this.active
);
2429 this.updateThemeClasses();
2434 * Check if the button is active
2437 * @return {boolean} The button is active
2439 OO
.ui
.mixin
.ButtonElement
.prototype.isActive = function () {
2444 * Any OOUI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
2445 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
2446 * items from the group is done through the interface the class provides.
2447 * For more information, please see the [OOUI documentation on MediaWiki] [1].
2449 * [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Groups
2452 * @mixins OO.EmitterList
2456 * @param {Object} [config] Configuration options
2457 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
2458 * is omitted, the group element will use a generated `<div>`.
2460 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
2461 // Configuration initialization
2462 config
= config
|| {};
2464 // Mixin constructors
2465 OO
.EmitterList
.call( this, config
);
2471 this.setGroupElement( config
.$group
|| $( '<div>' ) );
2476 OO
.mixinClass( OO
.ui
.mixin
.GroupElement
, OO
.EmitterList
);
2483 * A change event is emitted when the set of selected items changes.
2485 * @param {OO.ui.Element[]} items Items currently in the group
2491 * Set the group element.
2493 * If an element is already set, items will be moved to the new element.
2495 * @param {jQuery} $group Element to use as group
2497 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
2500 this.$group
= $group
;
2501 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2502 this.$group
.append( this.items
[ i
].$element
);
2507 * Find an item by its data.
2509 * Only the first item with matching data will be returned. To return all matching items,
2510 * use the #findItemsFromData method.
2512 * @param {Object} data Item data to search for
2513 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2515 OO
.ui
.mixin
.GroupElement
.prototype.findItemFromData = function ( data
) {
2517 hash
= OO
.getHash( data
);
2519 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2520 item
= this.items
[ i
];
2521 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2530 * Find items by their data.
2532 * All items with matching data will be returned. To return only the first match, use the
2533 * #findItemFromData method instead.
2535 * @param {Object} data Item data to search for
2536 * @return {OO.ui.Element[]} Items with equivalent data
2538 OO
.ui
.mixin
.GroupElement
.prototype.findItemsFromData = function ( data
) {
2540 hash
= OO
.getHash( data
),
2543 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2544 item
= this.items
[ i
];
2545 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2554 * Add items to the group.
2556 * Items will be added to the end of the group array unless the optional `index` parameter
2557 * specifies a different insertion point. Adding an existing item will move it to the end of the
2558 * array or the point specified by the `index`.
2560 * @param {OO.ui.Element[]} items An array of items to add to the group
2561 * @param {number} [index] Index of the insertion point
2563 * @return {OO.ui.Element} The element, for chaining
2565 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
2567 if ( items
.length
=== 0 ) {
2572 OO
.EmitterList
.prototype.addItems
.call( this, items
, index
);
2574 this.emit( 'change', this.getItems() );
2581 OO
.ui
.mixin
.GroupElement
.prototype.moveItem = function ( items
, newIndex
) {
2582 // insertItemElements expects this.items to not have been modified yet, so call before the mixin
2583 this.insertItemElements( items
, newIndex
);
2586 newIndex
= OO
.EmitterList
.prototype.moveItem
.call( this, items
, newIndex
);
2594 OO
.ui
.mixin
.GroupElement
.prototype.insertItem = function ( item
, index
) {
2595 item
.setElementGroup( this );
2596 this.insertItemElements( item
, index
);
2599 index
= OO
.EmitterList
.prototype.insertItem
.call( this, item
, index
);
2605 * Insert elements into the group
2608 * @param {OO.ui.Element} itemWidget Item to insert
2609 * @param {number} index Insertion index
2611 OO
.ui
.mixin
.GroupElement
.prototype.insertItemElements = function ( itemWidget
, index
) {
2612 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
2613 this.$group
.append( itemWidget
.$element
);
2614 } else if ( index
=== 0 ) {
2615 this.$group
.prepend( itemWidget
.$element
);
2617 this.items
[ index
].$element
.before( itemWidget
.$element
);
2622 * Remove the specified items from a group.
2624 * Removed items are detached (not removed) from the DOM so that they may be reused.
2625 * To remove all items from a group, you may wish to use the #clearItems method instead.
2627 * @param {OO.ui.Element[]} items An array of items to remove
2629 * @return {OO.ui.Element} The element, for chaining
2631 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
2632 var i
, len
, item
, index
;
2634 if ( items
.length
=== 0 ) {
2638 // Remove specific items elements
2639 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
2641 index
= this.items
.indexOf( item
);
2642 if ( index
!== -1 ) {
2643 item
.setElementGroup( null );
2644 item
.$element
.detach();
2649 OO
.EmitterList
.prototype.removeItems
.call( this, items
);
2651 this.emit( 'change', this.getItems() );
2656 * Clear all items from the group.
2658 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2659 * To remove only a subset of items from a group, use the #removeItems method.
2662 * @return {OO.ui.Element} The element, for chaining
2664 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
2667 // Remove all item elements
2668 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2669 this.items
[ i
].setElementGroup( null );
2670 this.items
[ i
].$element
.detach();
2674 OO
.EmitterList
.prototype.clearItems
.call( this );
2676 this.emit( 'change', this.getItems() );
2681 * LabelElement is often mixed into other classes to generate a label, which
2682 * helps identify the function of an interface element.
2683 * See the [OOUI documentation on MediaWiki] [1] for more information.
2685 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
2691 * @param {Object} [config] Configuration options
2692 * @cfg {jQuery} [$label] The label element created by the class. If this
2693 * configuration is omitted, the label element will use a generated `<span>`.
2694 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be
2695 * specified as a plaintext string, a jQuery selection of elements, or a function that will
2696 * produce a string in the future. See the [OOUI documentation on MediaWiki] [2] for examples.
2697 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
2698 * @cfg {boolean} [invisibleLabel] Whether the label should be visually hidden (but still
2699 * accessible to screen-readers).
2701 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
2702 // Configuration initialization
2703 config
= config
|| {};
2708 this.invisibleLabel
= null;
2711 this.setLabel( config
.label
|| this.constructor.static.label
);
2712 this.setLabelElement( config
.$label
|| $( '<span>' ) );
2713 this.setInvisibleLabel( config
.invisibleLabel
);
2718 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
2723 * @event labelChange
2724 * @param {string} value
2727 /* Static Properties */
2730 * The label text. The label can be specified as a plaintext string, a function that will
2731 * produce a string in the future, or `null` for no label. The static value will
2732 * be overridden if a label is specified with the #label config option.
2736 * @property {string|Function|null}
2738 OO
.ui
.mixin
.LabelElement
.static.label
= null;
2740 /* Static methods */
2743 * Highlight the first occurrence of the query in the given text
2745 * @param {string} text Text
2746 * @param {string} query Query to find
2747 * @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
2748 * @return {jQuery} Text with the first match of the query
2749 * sub-string wrapped in highlighted span
2751 OO
.ui
.mixin
.LabelElement
.static.highlightQuery = function ( text
, query
, compare
) {
2754 $result
= $( '<span>' );
2758 qLen
= query
.length
;
2759 for ( i
= 0; offset
=== -1 && i
<= tLen
- qLen
; i
++ ) {
2760 if ( compare( query
, text
.slice( i
, i
+ qLen
) ) === 0 ) {
2765 offset
= text
.toLowerCase().indexOf( query
.toLowerCase() );
2768 if ( !query
.length
|| offset
=== -1 ) {
2769 $result
.text( text
);
2772 document
.createTextNode( text
.slice( 0, offset
) ),
2774 .addClass( 'oo-ui-labelElement-label-highlight' )
2775 .text( text
.slice( offset
, offset
+ query
.length
) ),
2776 document
.createTextNode( text
.slice( offset
+ query
.length
) )
2779 return $result
.contents();
2785 * Set the label element.
2787 * If an element is already set, it will be cleaned up before setting up the new element.
2789 * @param {jQuery} $label Element to use as label
2791 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
2792 if ( this.$label
) {
2793 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
2796 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
2797 this.setLabelContent( this.label
);
2803 * An empty string will result in the label being hidden. A string containing only whitespace will
2804 * be converted to a single ` `.
2806 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that
2807 * returns nodes or text; or null for no label
2809 * @return {OO.ui.Element} The element, for chaining
2811 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
2812 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
2813 label
= ( ( typeof label
=== 'string' || label
instanceof $ ) && label
.length
) || ( label
instanceof OO
.ui
.HtmlSnippet
&& label
.toString().length
) ? label
: null;
2815 if ( this.label
!== label
) {
2816 if ( this.$label
) {
2817 this.setLabelContent( label
);
2820 this.emit( 'labelChange' );
2823 this.$element
.toggleClass( 'oo-ui-labelElement', !!this.label
&& !this.invisibleLabel
);
2829 * Set whether the label should be visually hidden (but still accessible to screen-readers).
2831 * @param {boolean} invisibleLabel
2833 * @return {OO.ui.Element} The element, for chaining
2835 OO
.ui
.mixin
.LabelElement
.prototype.setInvisibleLabel = function ( invisibleLabel
) {
2836 invisibleLabel
= !!invisibleLabel
;
2838 if ( this.invisibleLabel
!== invisibleLabel
) {
2839 this.invisibleLabel
= invisibleLabel
;
2840 this.emit( 'labelChange' );
2843 this.$label
.toggleClass( 'oo-ui-labelElement-invisible', this.invisibleLabel
);
2844 // Pretend that there is no label, a lot of CSS has been written with this assumption
2845 this.$element
.toggleClass( 'oo-ui-labelElement', !!this.label
&& !this.invisibleLabel
);
2851 * Set the label as plain text with a highlighted query
2853 * @param {string} text Text label to set
2854 * @param {string} query Substring of text to highlight
2855 * @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
2857 * @return {OO.ui.Element} The element, for chaining
2859 OO
.ui
.mixin
.LabelElement
.prototype.setHighlightedQuery = function ( text
, query
, compare
) {
2860 return this.setLabel( this.constructor.static.highlightQuery( text
, query
, compare
) );
2866 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
2867 * text; or null for no label
2869 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
2874 * Set the content of the label.
2876 * Do not call this method until after the label element has been set by #setLabelElement.
2879 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
2880 * text; or null for no label
2882 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
2883 if ( typeof label
=== 'string' ) {
2884 if ( label
.match( /^\s*$/ ) ) {
2885 // Convert whitespace only string to a single non-breaking space
2886 this.$label
.html( ' ' );
2888 this.$label
.text( label
);
2890 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
2891 this.$label
.html( label
.toString() );
2892 } else if ( label
instanceof $ ) {
2893 this.$label
.empty().append( label
);
2895 this.$label
.empty();
2900 * IconElement is often mixed into other classes to generate an icon.
2901 * Icons are graphics, about the size of normal text. They are used to aid the user
2902 * in locating a control or to convey information in a space-efficient way. See the
2903 * [OOUI documentation on MediaWiki] [1] for a list of icons
2904 * included in the library.
2906 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
2912 * @param {Object} [config] Configuration options
2913 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2914 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2915 * the icon element be set to an existing icon instead of the one generated by this class, set a
2916 * value using a jQuery selection. For example:
2918 * // Use a <div> tag instead of a <span>
2919 * $icon: $( '<div>' )
2920 * // Use an existing icon element instead of the one generated by the class
2921 * $icon: this.$element
2922 * // Use an icon element from a child widget
2923 * $icon: this.childwidget.$element
2924 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a
2925 * map of symbolic names. A map is used for i18n purposes and contains a `default` icon
2926 * name and additional names keyed by language code. The `default` name is used when no icon is
2927 * keyed by the user's language.
2929 * Example of an i18n map:
2931 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2932 * See the [OOUI documentation on MediaWiki] [2] for a list of icons included in the library.
2933 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
2935 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
2936 // Configuration initialization
2937 config
= config
|| {};
2944 this.setIcon( config
.icon
|| this.constructor.static.icon
);
2945 this.setIconElement( config
.$icon
|| $( '<span>' ) );
2950 OO
.initClass( OO
.ui
.mixin
.IconElement
);
2952 /* Static Properties */
2955 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map
2956 * is used for i18n purposes and contains a `default` icon name and additional names keyed by
2957 * language code. The `default` name is used when no icon is keyed by the user's language.
2959 * Example of an i18n map:
2961 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2963 * Note: the static property will be overridden if the #icon configuration is used.
2967 * @property {Object|string}
2969 OO
.ui
.mixin
.IconElement
.static.icon
= null;
2972 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2973 * function that returns title text, or `null` for no title.
2975 * The static property will be overridden if the #iconTitle configuration is used.
2979 * @property {string|Function|null}
2981 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
2986 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2987 * applies to the specified icon element instead of the one created by the class. If an icon
2988 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2989 * and mixin methods will no longer affect the element.
2991 * @param {jQuery} $icon Element to use as icon
2993 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
2996 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
2997 .removeAttr( 'title' );
3001 .addClass( 'oo-ui-iconElement-icon' )
3002 .toggleClass( 'oo-ui-iconElement-noIcon', !this.icon
)
3003 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
3004 if ( this.iconTitle
!== null ) {
3005 this.$icon
.attr( 'title', this.iconTitle
);
3008 this.updateThemeClasses();
3012 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
3013 * The icon parameter can also be set to a map of icon names. See the #icon config setting
3016 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
3017 * by language code, or `null` to remove the icon.
3019 * @return {OO.ui.Element} The element, for chaining
3021 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
3022 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
3023 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
3025 if ( this.icon
!== icon
) {
3027 if ( this.icon
!== null ) {
3028 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
3030 if ( icon
!== null ) {
3031 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
3037 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
3039 this.$icon
.toggleClass( 'oo-ui-iconElement-noIcon', !this.icon
);
3041 this.updateThemeClasses();
3047 * Get the symbolic name of the icon.
3049 * @return {string} Icon name
3051 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
3056 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
3058 * @return {string} Icon title text
3061 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
3062 return this.iconTitle
;
3066 * IndicatorElement is often mixed into other classes to generate an indicator.
3067 * Indicators are small graphics that are generally used in two ways:
3069 * - To draw attention to the status of an item. For example, an indicator might be
3070 * used to show that an item in a list has errors that need to be resolved.
3071 * - To clarify the function of a control that acts in an exceptional way (a button
3072 * that opens a menu instead of performing an action directly, for example).
3074 * For a list of indicators included in the library, please see the
3075 * [OOUI documentation on MediaWiki] [1].
3077 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3083 * @param {Object} [config] Configuration options
3084 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
3085 * configuration is omitted, the indicator element will use a generated `<span>`.
3086 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3087 * See the [OOUI documentation on MediaWiki][2] for a list of indicators included
3089 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3091 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
3092 // Configuration initialization
3093 config
= config
|| {};
3096 this.$indicator
= null;
3097 this.indicator
= null;
3100 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
3101 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
3106 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
3108 /* Static Properties */
3111 * Symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3112 * The static property will be overridden if the #indicator configuration is used.
3116 * @property {string|null}
3118 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
3121 * A text string used as the indicator title, a function that returns title text, or `null`
3122 * for no title. The static property will be overridden if the #indicatorTitle configuration is
3127 * @property {string|Function|null}
3129 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
3134 * Set the indicator element.
3136 * If an element is already set, it will be cleaned up before setting up the new element.
3138 * @param {jQuery} $indicator Element to use as indicator
3140 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
3141 if ( this.$indicator
) {
3143 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
3144 .removeAttr( 'title' );
3147 this.$indicator
= $indicator
3148 .addClass( 'oo-ui-indicatorElement-indicator' )
3149 .toggleClass( 'oo-ui-indicatorElement-noIndicator', !this.indicator
)
3150 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
3151 if ( this.indicatorTitle
!== null ) {
3152 this.$indicator
.attr( 'title', this.indicatorTitle
);
3155 this.updateThemeClasses();
3159 * Set the indicator by its symbolic name: ‘clear’, ‘down’, ‘required’, ‘search’, ‘up’. Use `null`
3160 * to remove the indicator.
3162 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
3164 * @return {OO.ui.Element} The element, for chaining
3166 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
3167 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
3169 if ( this.indicator
!== indicator
) {
3170 if ( this.$indicator
) {
3171 if ( this.indicator
!== null ) {
3172 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
3174 if ( indicator
!== null ) {
3175 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
3178 this.indicator
= indicator
;
3181 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
3182 if ( this.$indicator
) {
3183 this.$indicator
.toggleClass( 'oo-ui-indicatorElement-noIndicator', !this.indicator
);
3185 this.updateThemeClasses();
3191 * Get the symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3193 * @return {string} Symbolic name of indicator
3195 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
3196 return this.indicator
;
3200 * Get the indicator title.
3202 * The title is displayed when a user moves the mouse over the indicator.
3204 * @return {string} Indicator title text
3207 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
3208 return this.indicatorTitle
;
3212 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
3213 * additional functionality to an element created by another class. The class provides
3214 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
3215 * which are used to customize the look and feel of a widget to better describe its
3216 * importance and functionality.
3218 * The library currently contains the following styling flags for general use:
3220 * - **progressive**: Progressive styling is applied to convey that the widget will move the user
3221 * forward in a process.
3222 * - **destructive**: Destructive styling is applied to convey that the widget will remove
3225 * The flags affect the appearance of the buttons:
3228 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
3229 * var button1 = new OO.ui.ButtonWidget( {
3230 * label: 'Progressive',
3231 * flags: 'progressive'
3233 * button2 = new OO.ui.ButtonWidget( {
3234 * label: 'Destructive',
3235 * flags: 'destructive'
3237 * $( document.body ).append( button1.$element, button2.$element );
3239 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an
3240 * action, use these flags: **primary** and **safe**.
3241 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
3243 * [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
3249 * @param {Object} [config] Configuration options
3250 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'progressive' or 'primary')
3252 * Please see the [OOUI documentation on MediaWiki] [2] for more information about available flags.
3253 * [2]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
3254 * @cfg {jQuery} [$flagged] The flagged element. By default,
3255 * the flagged functionality is applied to the element created by the class ($element).
3256 * If a different element is specified, the flagged functionality will be applied to it instead.
3258 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
3259 // Configuration initialization
3260 config
= config
|| {};
3264 this.$flagged
= null;
3267 this.setFlags( config
.flags
|| this.constructor.static.flags
);
3268 this.setFlaggedElement( config
.$flagged
|| this.$element
);
3273 OO
.initClass( OO
.ui
.mixin
.FlaggedElement
);
3279 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
3280 * parameter contains the name of each modified flag and indicates whether it was
3283 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
3284 * that the flag was added, `false` that the flag was removed.
3287 /* Static Properties */
3290 * Initial value to pass to setFlags if no value is provided in config.
3294 * @property {string|string[]|Object.<string, boolean>}
3296 OO
.ui
.mixin
.FlaggedElement
.static.flags
= null;
3301 * Set the flagged element.
3303 * This method is used to retarget a flagged mixin so that its functionality applies to the
3304 * specified element.
3305 * If an element is already set, the method will remove the mixin’s effect on that element.
3307 * @param {jQuery} $flagged Element that should be flagged
3309 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
3310 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
3311 return 'oo-ui-flaggedElement-' + flag
;
3314 if ( this.$flagged
) {
3315 this.$flagged
.removeClass( classNames
);
3318 this.$flagged
= $flagged
.addClass( classNames
);
3322 * Check if the specified flag is set.
3324 * @param {string} flag Name of flag
3325 * @return {boolean} The flag is set
3327 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
3328 // This may be called before the constructor, thus before this.flags is set
3329 return this.flags
&& ( flag
in this.flags
);
3333 * Get the names of all flags set.
3335 * @return {string[]} Flag names
3337 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
3338 // This may be called before the constructor, thus before this.flags is set
3339 return Object
.keys( this.flags
|| {} );
3346 * @return {OO.ui.Element} The element, for chaining
3349 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
3350 var flag
, className
,
3353 classPrefix
= 'oo-ui-flaggedElement-';
3355 for ( flag
in this.flags
) {
3356 className
= classPrefix
+ flag
;
3357 changes
[ flag
] = false;
3358 delete this.flags
[ flag
];
3359 remove
.push( className
);
3362 if ( this.$flagged
) {
3363 this.$flagged
.removeClass( remove
);
3366 this.updateThemeClasses();
3367 this.emit( 'flag', changes
);
3373 * Add one or more flags.
3375 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
3376 * or an object keyed by flag name with a boolean value that indicates whether the flag should
3377 * be added (`true`) or removed (`false`).
3379 * @return {OO.ui.Element} The element, for chaining
3382 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
3383 var i
, len
, flag
, className
,
3387 classPrefix
= 'oo-ui-flaggedElement-';
3389 if ( typeof flags
=== 'string' ) {
3390 className
= classPrefix
+ flags
;
3392 if ( !this.flags
[ flags
] ) {
3393 this.flags
[ flags
] = true;
3394 add
.push( className
);
3396 } else if ( Array
.isArray( flags
) ) {
3397 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
3399 className
= classPrefix
+ flag
;
3401 if ( !this.flags
[ flag
] ) {
3402 changes
[ flag
] = true;
3403 this.flags
[ flag
] = true;
3404 add
.push( className
);
3407 } else if ( OO
.isPlainObject( flags
) ) {
3408 for ( flag
in flags
) {
3409 className
= classPrefix
+ flag
;
3410 if ( flags
[ flag
] ) {
3412 if ( !this.flags
[ flag
] ) {
3413 changes
[ flag
] = true;
3414 this.flags
[ flag
] = true;
3415 add
.push( className
);
3419 if ( this.flags
[ flag
] ) {
3420 changes
[ flag
] = false;
3421 delete this.flags
[ flag
];
3422 remove
.push( className
);
3428 if ( this.$flagged
) {
3431 .removeClass( remove
);
3434 this.updateThemeClasses();
3435 this.emit( 'flag', changes
);
3441 * TitledElement is mixed into other classes to provide a `title` attribute.
3442 * Titles are rendered by the browser and are made visible when the user moves
3443 * the mouse over the element. Titles are not visible on touch devices.
3446 * // TitledElement provides a `title` attribute to the
3447 * // ButtonWidget class.
3448 * var button = new OO.ui.ButtonWidget( {
3449 * label: 'Button with Title',
3450 * title: 'I am a button'
3452 * $( document.body ).append( button.$element );
3458 * @param {Object} [config] Configuration options
3459 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
3460 * If this config is omitted, the title functionality is applied to $element, the
3461 * element created by the class.
3462 * @cfg {string|Function} [title] The title text or a function that returns text. If
3463 * this config is omitted, the value of the {@link #static-title static title} property is used.
3465 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
3466 // Configuration initialization
3467 config
= config
|| {};
3470 this.$titled
= null;
3474 this.setTitle( config
.title
!== undefined ? config
.title
: this.constructor.static.title
);
3475 this.setTitledElement( config
.$titled
|| this.$element
);
3480 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
3482 /* Static Properties */
3485 * The title text, a function that returns text, or `null` for no title. The value of the static
3486 * property is overridden if the #title config option is used.
3488 * If the element has a default title (e.g. `<input type=file>`), `null` will allow that title to be
3489 * shown. Use empty string to suppress it.
3493 * @property {string|Function|null}
3495 OO
.ui
.mixin
.TitledElement
.static.title
= null;
3500 * Set the titled element.
3502 * This method is used to retarget a TitledElement mixin so that its functionality applies to the
3503 * specified element.
3504 * If an element is already set, the mixin’s effect on that element is removed before the new
3505 * element is set up.
3507 * @param {jQuery} $titled Element that should use the 'titled' functionality
3509 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
3510 if ( this.$titled
) {
3511 this.$titled
.removeAttr( 'title' );
3514 this.$titled
= $titled
;
3521 * @param {string|Function|null} title Title text, a function that returns text, or `null`
3524 * @return {OO.ui.Element} The element, for chaining
3526 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
3527 title
= typeof title
=== 'function' ? OO
.ui
.resolveMsg( title
) : title
;
3528 title
= typeof title
=== 'string' ? title
: null;
3530 if ( this.title
!== title
) {
3539 * Update the title attribute, in case of changes to title or accessKey.
3543 * @return {OO.ui.Element} The element, for chaining
3545 OO
.ui
.mixin
.TitledElement
.prototype.updateTitle = function () {
3546 var title
= this.getTitle();
3547 if ( this.$titled
) {
3548 if ( title
!== null ) {
3549 // Only if this is an AccessKeyedElement
3550 if ( this.formatTitleWithAccessKey
) {
3551 title
= this.formatTitleWithAccessKey( title
);
3553 this.$titled
.attr( 'title', title
);
3555 this.$titled
.removeAttr( 'title' );
3564 * @return {string} Title string
3566 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
3571 * AccessKeyedElement is mixed into other classes to provide an `accesskey` HTML attribute.
3572 * Access keys allow an user to go to a specific element by using
3573 * a shortcut combination of a browser specific keys + the key
3577 * // AccessKeyedElement provides an `accesskey` attribute to the
3578 * // ButtonWidget class.
3579 * var button = new OO.ui.ButtonWidget( {
3580 * label: 'Button with access key',
3583 * $( document.body ).append( button.$element );
3589 * @param {Object} [config] Configuration options
3590 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3591 * If this config is omitted, the access key functionality is applied to $element, the
3592 * element created by the class.
3593 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3594 * this config is omitted, no access key will be added.
3596 OO
.ui
.mixin
.AccessKeyedElement
= function OoUiMixinAccessKeyedElement( config
) {
3597 // Configuration initialization
3598 config
= config
|| {};
3601 this.$accessKeyed
= null;
3602 this.accessKey
= null;
3605 this.setAccessKey( config
.accessKey
|| null );
3606 this.setAccessKeyedElement( config
.$accessKeyed
|| this.$element
);
3608 // If this is also a TitledElement and it initialized before we did, we may have
3609 // to update the title with the access key
3610 if ( this.updateTitle
) {
3617 OO
.initClass( OO
.ui
.mixin
.AccessKeyedElement
);
3619 /* Static Properties */
3622 * The access key, a function that returns a key, or `null` for no access key.
3626 * @property {string|Function|null}
3628 OO
.ui
.mixin
.AccessKeyedElement
.static.accessKey
= null;
3633 * Set the access keyed element.
3635 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to
3636 * the specified element.
3637 * If an element is already set, the mixin's effect on that element is removed before the new
3638 * element is set up.
3640 * @param {jQuery} $accessKeyed Element that should use the 'access keyed' functionality
3642 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKeyedElement = function ( $accessKeyed
) {
3643 if ( this.$accessKeyed
) {
3644 this.$accessKeyed
.removeAttr( 'accesskey' );
3647 this.$accessKeyed
= $accessKeyed
;
3648 if ( this.accessKey
) {
3649 this.$accessKeyed
.attr( 'accesskey', this.accessKey
);
3656 * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no
3659 * @return {OO.ui.Element} The element, for chaining
3661 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKey = function ( accessKey
) {
3662 accessKey
= typeof accessKey
=== 'string' ? OO
.ui
.resolveMsg( accessKey
) : null;
3664 if ( this.accessKey
!== accessKey
) {
3665 if ( this.$accessKeyed
) {
3666 if ( accessKey
!== null ) {
3667 this.$accessKeyed
.attr( 'accesskey', accessKey
);
3669 this.$accessKeyed
.removeAttr( 'accesskey' );
3672 this.accessKey
= accessKey
;
3674 // Only if this is a TitledElement
3675 if ( this.updateTitle
) {
3686 * @return {string} accessKey string
3688 OO
.ui
.mixin
.AccessKeyedElement
.prototype.getAccessKey = function () {
3689 return this.accessKey
;
3693 * Add information about the access key to the element's tooltip label.
3694 * (This is only public for hacky usage in FieldLayout.)
3696 * @param {string} title Tooltip label for `title` attribute
3699 OO
.ui
.mixin
.AccessKeyedElement
.prototype.formatTitleWithAccessKey = function ( title
) {
3702 if ( !this.$accessKeyed
) {
3703 // Not initialized yet; the constructor will call updateTitle() which will rerun this
3707 // Use jquery.accessKeyLabel if available to show modifiers, otherwise just display the
3709 if ( $.fn
.updateTooltipAccessKeys
&& $.fn
.updateTooltipAccessKeys
.getAccessKeyLabel
) {
3710 accessKey
= $.fn
.updateTooltipAccessKeys
.getAccessKeyLabel( this.$accessKeyed
[ 0 ] );
3712 accessKey
= this.getAccessKey();
3715 title
+= ' [' + accessKey
+ ']';
3721 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3722 * feels, and functionality can be customized via the class’s configuration options
3723 * and methods. Please see the [OOUI documentation on MediaWiki] [1] for more information
3726 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches
3729 * // A button widget.
3730 * var button = new OO.ui.ButtonWidget( {
3731 * label: 'Button with Icon',
3735 * $( document.body ).append( button.$element );
3737 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3740 * @extends OO.ui.Widget
3741 * @mixins OO.ui.mixin.ButtonElement
3742 * @mixins OO.ui.mixin.IconElement
3743 * @mixins OO.ui.mixin.IndicatorElement
3744 * @mixins OO.ui.mixin.LabelElement
3745 * @mixins OO.ui.mixin.TitledElement
3746 * @mixins OO.ui.mixin.FlaggedElement
3747 * @mixins OO.ui.mixin.TabIndexedElement
3748 * @mixins OO.ui.mixin.AccessKeyedElement
3751 * @param {Object} [config] Configuration options
3752 * @cfg {boolean} [active=false] Whether button should be shown as active
3753 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3754 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3755 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3757 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
3758 // Configuration initialization
3759 config
= config
|| {};
3761 // Parent constructor
3762 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
3764 // Mixin constructors
3765 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
3766 OO
.ui
.mixin
.IconElement
.call( this, config
);
3767 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
3768 OO
.ui
.mixin
.LabelElement
.call( this, config
);
3769 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {
3770 $titled
: this.$button
3772 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
3773 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {
3774 $tabIndexed
: this.$button
3776 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {
3777 $accessKeyed
: this.$button
3783 this.noFollow
= false;
3786 this.connect( this, {
3787 disable
: 'onDisable'
3791 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
3793 .addClass( 'oo-ui-buttonWidget' )
3794 .append( this.$button
);
3795 this.setActive( config
.active
);
3796 this.setHref( config
.href
);
3797 this.setTarget( config
.target
);
3798 this.setNoFollow( config
.noFollow
);
3803 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
3804 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
3805 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
3806 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
3807 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
3808 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
3809 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
3810 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
3811 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
3813 /* Static Properties */
3819 OO
.ui
.ButtonWidget
.static.cancelButtonMouseDownEvents
= false;
3825 OO
.ui
.ButtonWidget
.static.tagName
= 'span';
3830 * Get hyperlink location.
3832 * @return {string} Hyperlink location
3834 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
3839 * Get hyperlink target.
3841 * @return {string} Hyperlink target
3843 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
3848 * Get search engine traversal hint.
3850 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3852 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
3853 return this.noFollow
;
3857 * Set hyperlink location.
3859 * @param {string|null} href Hyperlink location, null to remove
3861 * @return {OO.ui.Widget} The widget, for chaining
3863 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
3864 href
= typeof href
=== 'string' ? href
: null;
3865 if ( href
!== null && !OO
.ui
.isSafeUrl( href
) ) {
3869 if ( href
!== this.href
) {
3878 * Update the `href` attribute, in case of changes to href or
3883 * @return {OO.ui.Widget} The widget, for chaining
3885 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
3886 if ( this.href
!== null && !this.isDisabled() ) {
3887 this.$button
.attr( 'href', this.href
);
3889 this.$button
.removeAttr( 'href' );
3896 * Handle disable events.
3899 * @param {boolean} disabled Element is disabled
3901 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
3906 * Set hyperlink target.
3908 * @param {string|null} target Hyperlink target, null to remove
3909 * @return {OO.ui.Widget} The widget, for chaining
3911 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
3912 target
= typeof target
=== 'string' ? target
: null;
3914 if ( target
!== this.target
) {
3915 this.target
= target
;
3916 if ( target
!== null ) {
3917 this.$button
.attr( 'target', target
);
3919 this.$button
.removeAttr( 'target' );
3927 * Set search engine traversal hint.
3929 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3930 * @return {OO.ui.Widget} The widget, for chaining
3932 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
3933 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
3935 if ( noFollow
!== this.noFollow
) {
3936 this.noFollow
= noFollow
;
3938 this.$button
.attr( 'rel', 'nofollow' );
3940 this.$button
.removeAttr( 'rel' );
3947 // Override method visibility hints from ButtonElement
3958 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3959 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3960 * removed, and cleared from the group.
3963 * // A ButtonGroupWidget with two buttons.
3964 * var button1 = new OO.ui.PopupButtonWidget( {
3965 * label: 'Select a category',
3968 * $content: $( '<p>List of categories…</p>' ),
3973 * button2 = new OO.ui.ButtonWidget( {
3976 * buttonGroup = new OO.ui.ButtonGroupWidget( {
3977 * items: [ button1, button2 ]
3979 * $( document.body ).append( buttonGroup.$element );
3982 * @extends OO.ui.Widget
3983 * @mixins OO.ui.mixin.GroupElement
3984 * @mixins OO.ui.mixin.TitledElement
3987 * @param {Object} [config] Configuration options
3988 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
3990 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
3991 // Configuration initialization
3992 config
= config
|| {};
3994 // Parent constructor
3995 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
3997 // Mixin constructors
3998 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {
3999 $group
: this.$element
4001 OO
.ui
.mixin
.TitledElement
.call( this, config
);
4004 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
4005 if ( Array
.isArray( config
.items
) ) {
4006 this.addItems( config
.items
);
4012 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
4013 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
4014 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.TitledElement
);
4016 /* Static Properties */
4022 OO
.ui
.ButtonGroupWidget
.static.tagName
= 'span';
4030 * @return {OO.ui.Widget} The widget, for chaining
4032 OO
.ui
.ButtonGroupWidget
.prototype.focus = function () {
4033 if ( !this.isDisabled() ) {
4034 if ( this.items
[ 0 ] ) {
4035 this.items
[ 0 ].focus();
4044 OO
.ui
.ButtonGroupWidget
.prototype.simulateLabelClick = function () {
4049 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}.
4050 * In general, IconWidgets should be used with OO.ui.LabelWidget, which creates a label that
4051 * identifies the icon’s function. See the [OOUI documentation on MediaWiki] [1]
4052 * for a list of icons included in the library.
4055 * // An IconWidget with a label via LabelWidget.
4056 * var myIcon = new OO.ui.IconWidget( {
4060 * // Create a label.
4061 * iconLabel = new OO.ui.LabelWidget( {
4064 * $( document.body ).append( myIcon.$element, iconLabel.$element );
4066 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
4069 * @extends OO.ui.Widget
4070 * @mixins OO.ui.mixin.IconElement
4071 * @mixins OO.ui.mixin.TitledElement
4072 * @mixins OO.ui.mixin.LabelElement
4073 * @mixins OO.ui.mixin.FlaggedElement
4076 * @param {Object} [config] Configuration options
4078 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
4079 // Configuration initialization
4080 config
= config
|| {};
4082 // Parent constructor
4083 OO
.ui
.IconWidget
.parent
.call( this, config
);
4085 // Mixin constructors
4086 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {
4087 $icon
: this.$element
4089 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {
4090 $titled
: this.$element
4092 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {
4093 $label
: this.$element
,
4094 invisibleLabel
: true
4096 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {
4097 $flagged
: this.$element
4101 this.$element
.addClass( 'oo-ui-iconWidget' );
4102 // Remove class added by LabelElement initialization. It causes unexpected CSS to apply when
4103 // nested in other widgets, because this widget used to not mix in LabelElement.
4104 this.$element
.removeClass( 'oo-ui-labelElement-label' );
4109 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
4110 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
4111 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
4112 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.LabelElement
);
4113 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
4115 /* Static Properties */
4121 OO
.ui
.IconWidget
.static.tagName
= 'span';
4124 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
4125 * attention to the status of an item or to clarify the function within a control. For a list of
4126 * indicators included in the library, please see the [OOUI documentation on MediaWiki][1].
4129 * // An indicator widget.
4130 * var indicator1 = new OO.ui.IndicatorWidget( {
4131 * indicator: 'required'
4133 * // Create a fieldset layout to add a label.
4134 * fieldset = new OO.ui.FieldsetLayout();
4135 * fieldset.addItems( [
4136 * new OO.ui.FieldLayout( indicator1, {
4137 * label: 'A required indicator:'
4140 * $( document.body ).append( fieldset.$element );
4142 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
4145 * @extends OO.ui.Widget
4146 * @mixins OO.ui.mixin.IndicatorElement
4147 * @mixins OO.ui.mixin.TitledElement
4148 * @mixins OO.ui.mixin.LabelElement
4151 * @param {Object} [config] Configuration options
4153 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
4154 // Configuration initialization
4155 config
= config
|| {};
4157 // Parent constructor
4158 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
4160 // Mixin constructors
4161 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {
4162 $indicator
: this.$element
4164 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {
4165 $titled
: this.$element
4167 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {
4168 $label
: this.$element
,
4169 invisibleLabel
: true
4173 this.$element
.addClass( 'oo-ui-indicatorWidget' );
4174 // Remove class added by LabelElement initialization. It causes unexpected CSS to apply when
4175 // nested in other widgets, because this widget used to not mix in LabelElement.
4176 this.$element
.removeClass( 'oo-ui-labelElement-label' );
4181 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
4182 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
4183 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
4184 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.LabelElement
);
4186 /* Static Properties */
4192 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
4195 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
4196 * be configured with a `label` option that is set to a string, a label node, or a function:
4198 * - String: a plaintext string
4199 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
4200 * label that includes a link or special styling, such as a gray color or additional
4201 * graphical elements.
4202 * - Function: a function that will produce a string in the future. Functions are used
4203 * in cases where the value of the label is not currently defined.
4205 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget},
4206 * which will come into focus when the label is clicked.
4209 * // Two LabelWidgets.
4210 * var label1 = new OO.ui.LabelWidget( {
4211 * label: 'plaintext label'
4213 * label2 = new OO.ui.LabelWidget( {
4214 * label: $( '<a>' ).attr( 'href', 'default.html' ).text( 'jQuery label' )
4216 * // Create a fieldset layout with fields for each example.
4217 * fieldset = new OO.ui.FieldsetLayout();
4218 * fieldset.addItems( [
4219 * new OO.ui.FieldLayout( label1 ),
4220 * new OO.ui.FieldLayout( label2 )
4222 * $( document.body ).append( fieldset.$element );
4225 * @extends OO.ui.Widget
4226 * @mixins OO.ui.mixin.LabelElement
4227 * @mixins OO.ui.mixin.TitledElement
4230 * @param {Object} [config] Configuration options
4231 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
4232 * Clicking the label will focus the specified input field.
4234 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
4235 // Configuration initialization
4236 config
= config
|| {};
4238 // Parent constructor
4239 OO
.ui
.LabelWidget
.parent
.call( this, config
);
4241 // Mixin constructors
4242 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {
4243 $label
: this.$element
4245 OO
.ui
.mixin
.TitledElement
.call( this, config
);
4248 this.input
= config
.input
;
4252 if ( this.input
.getInputId() ) {
4253 this.$element
.attr( 'for', this.input
.getInputId() );
4255 this.$label
.on( 'click', function () {
4256 this.input
.simulateLabelClick();
4260 this.$element
.addClass( 'oo-ui-labelWidget' );
4265 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
4266 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
4267 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
4269 /* Static Properties */
4275 OO
.ui
.LabelWidget
.static.tagName
= 'label';
4278 * PendingElement is a mixin that is used to create elements that notify users that something is
4279 * happening and that they should wait before proceeding. The pending state is visually represented
4280 * with a pending texture that appears in the head of a pending
4281 * {@link OO.ui.ProcessDialog process dialog} or in the input field of a
4282 * {@link OO.ui.TextInputWidget text input widget}.
4284 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked
4285 * as pending, but only when used in {@link OO.ui.MessageDialog message dialogs}. The behavior is
4286 * not currently supported for action widgets used in process dialogs.
4289 * function MessageDialog( config ) {
4290 * MessageDialog.parent.call( this, config );
4292 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
4294 * MessageDialog.static.name = 'myMessageDialog';
4295 * MessageDialog.static.actions = [
4296 * { action: 'save', label: 'Done', flags: 'primary' },
4297 * { label: 'Cancel', flags: 'safe' }
4300 * MessageDialog.prototype.initialize = function () {
4301 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
4302 * this.content = new OO.ui.PanelLayout( { padded: true } );
4303 * this.content.$element.append( '<p>Click the \'Done\' action widget to see its pending ' +
4304 * 'state. Note that action widgets can be marked pending in message dialogs but not ' +
4305 * 'process dialogs.</p>' );
4306 * this.$body.append( this.content.$element );
4308 * MessageDialog.prototype.getBodyHeight = function () {
4311 * MessageDialog.prototype.getActionProcess = function ( action ) {
4312 * var dialog = this;
4313 * if ( action === 'save' ) {
4314 * dialog.getActions().get({actions: 'save'})[0].pushPending();
4315 * return new OO.ui.Process()
4317 * .next( function () {
4318 * dialog.getActions().get({actions: 'save'})[0].popPending();
4321 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
4324 * var windowManager = new OO.ui.WindowManager();
4325 * $( document.body ).append( windowManager.$element );
4327 * var dialog = new MessageDialog();
4328 * windowManager.addWindows( [ dialog ] );
4329 * windowManager.openWindow( dialog );
4335 * @param {Object} [config] Configuration options
4336 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
4338 OO
.ui
.mixin
.PendingElement
= function OoUiMixinPendingElement( config
) {
4339 // Configuration initialization
4340 config
= config
|| {};
4344 this.$pending
= null;
4347 this.setPendingElement( config
.$pending
|| this.$element
);
4352 OO
.initClass( OO
.ui
.mixin
.PendingElement
);
4357 * Set the pending element (and clean up any existing one).
4359 * @param {jQuery} $pending The element to set to pending.
4361 OO
.ui
.mixin
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
4362 if ( this.$pending
) {
4363 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
4366 this.$pending
= $pending
;
4367 if ( this.pending
> 0 ) {
4368 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
4373 * Check if an element is pending.
4375 * @return {boolean} Element is pending
4377 OO
.ui
.mixin
.PendingElement
.prototype.isPending = function () {
4378 return !!this.pending
;
4382 * Increase the pending counter. The pending state will remain active until the counter is zero
4383 * (i.e., the number of calls to #pushPending and #popPending is the same).
4386 * @return {OO.ui.Element} The element, for chaining
4388 OO
.ui
.mixin
.PendingElement
.prototype.pushPending = function () {
4389 if ( this.pending
=== 0 ) {
4390 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
4391 this.updateThemeClasses();
4399 * Decrease the pending counter. The pending state will remain active until the counter is zero
4400 * (i.e., the number of calls to #pushPending and #popPending is the same).
4403 * @return {OO.ui.Element} The element, for chaining
4405 OO
.ui
.mixin
.PendingElement
.prototype.popPending = function () {
4406 if ( this.pending
=== 1 ) {
4407 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
4408 this.updateThemeClasses();
4410 this.pending
= Math
.max( 0, this.pending
- 1 );
4416 * Element that will stick adjacent to a specified container, even when it is inserted elsewhere
4417 * in the document (for example, in an OO.ui.Window's $overlay).
4419 * The elements's position is automatically calculated and maintained when window is resized or the
4420 * page is scrolled. If you reposition the container manually, you have to call #position to make
4421 * sure the element is still placed correctly.
4423 * As positioning is only possible when both the element and the container are attached to the DOM
4424 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
4425 * the #toggle method to display a floating popup, for example.
4431 * @param {Object} [config] Configuration options
4432 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
4433 * @cfg {jQuery} [$floatableContainer] Node to position adjacent to
4434 * @cfg {string} [verticalPosition='below'] Where to position $floatable vertically:
4435 * 'below': Directly below $floatableContainer, aligning f's top edge with fC's bottom edge
4436 * 'above': Directly above $floatableContainer, aligning f's bottom edge with fC's top edge
4437 * 'top': Align the top edge with $floatableContainer's top edge
4438 * 'bottom': Align the bottom edge with $floatableContainer's bottom edge
4439 * 'center': Vertically align the center with $floatableContainer's center
4440 * @cfg {string} [horizontalPosition='start'] Where to position $floatable horizontally:
4441 * 'before': Directly before $floatableContainer, aligning f's end edge with fC's start edge
4442 * 'after': Directly after $floatableContainer, aligning f's start edge with fC's end edge
4443 * 'start': Align the start (left in LTR, right in RTL) edge with $floatableContainer's start edge
4444 * 'end': Align the end (right in LTR, left in RTL) edge with $floatableContainer's end edge
4445 * 'center': Horizontally align the center with $floatableContainer's center
4446 * @cfg {boolean} [hideWhenOutOfView=true] Whether to hide the floatable element if the container
4449 OO
.ui
.mixin
.FloatableElement
= function OoUiMixinFloatableElement( config
) {
4450 // Configuration initialization
4451 config
= config
|| {};
4454 this.$floatable
= null;
4455 this.$floatableContainer
= null;
4456 this.$floatableWindow
= null;
4457 this.$floatableClosestScrollable
= null;
4458 this.floatableOutOfView
= false;
4459 this.onFloatableScrollHandler
= this.position
.bind( this );
4460 this.onFloatableWindowResizeHandler
= this.position
.bind( this );
4463 this.setFloatableContainer( config
.$floatableContainer
);
4464 this.setFloatableElement( config
.$floatable
|| this.$element
);
4465 this.setVerticalPosition( config
.verticalPosition
|| 'below' );
4466 this.setHorizontalPosition( config
.horizontalPosition
|| 'start' );
4467 this.hideWhenOutOfView
= config
.hideWhenOutOfView
=== undefined ?
4468 true : !!config
.hideWhenOutOfView
;
4474 * Set floatable element.
4476 * If an element is already set, it will be cleaned up before setting up the new element.
4478 * @param {jQuery} $floatable Element to make floatable
4480 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableElement = function ( $floatable
) {
4481 if ( this.$floatable
) {
4482 this.$floatable
.removeClass( 'oo-ui-floatableElement-floatable' );
4483 this.$floatable
.css( { left
: '', top
: '' } );
4486 this.$floatable
= $floatable
.addClass( 'oo-ui-floatableElement-floatable' );
4491 * Set floatable container.
4493 * The element will be positioned relative to the specified container.
4495 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
4497 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableContainer = function ( $floatableContainer
) {
4498 this.$floatableContainer
= $floatableContainer
;
4499 if ( this.$floatable
) {
4505 * Change how the element is positioned vertically.
4507 * @param {string} position 'below', 'above', 'top', 'bottom' or 'center'
4509 OO
.ui
.mixin
.FloatableElement
.prototype.setVerticalPosition = function ( position
) {
4510 if ( [ 'below', 'above', 'top', 'bottom', 'center' ].indexOf( position
) === -1 ) {
4511 throw new Error( 'Invalid value for vertical position: ' + position
);
4513 if ( this.verticalPosition
!== position
) {
4514 this.verticalPosition
= position
;
4515 if ( this.$floatable
) {
4522 * Change how the element is positioned horizontally.
4524 * @param {string} position 'before', 'after', 'start', 'end' or 'center'
4526 OO
.ui
.mixin
.FloatableElement
.prototype.setHorizontalPosition = function ( position
) {
4527 if ( [ 'before', 'after', 'start', 'end', 'center' ].indexOf( position
) === -1 ) {
4528 throw new Error( 'Invalid value for horizontal position: ' + position
);
4530 if ( this.horizontalPosition
!== position
) {
4531 this.horizontalPosition
= position
;
4532 if ( this.$floatable
) {
4539 * Toggle positioning.
4541 * Do not turn positioning on until after the element is attached to the DOM and visible.
4543 * @param {boolean} [positioning] Enable positioning, omit to toggle
4545 * @return {OO.ui.Element} The element, for chaining
4547 OO
.ui
.mixin
.FloatableElement
.prototype.togglePositioning = function ( positioning
) {
4548 var closestScrollableOfContainer
;
4550 if ( !this.$floatable
|| !this.$floatableContainer
) {
4554 positioning
= positioning
=== undefined ? !this.positioning
: !!positioning
;
4556 if ( positioning
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4557 OO
.ui
.warnDeprecation( 'FloatableElement#togglePositioning: Before calling this method, the element must be attached to the DOM.' );
4558 this.warnedUnattached
= true;
4561 if ( this.positioning
!== positioning
) {
4562 this.positioning
= positioning
;
4564 closestScrollableOfContainer
= OO
.ui
.Element
.static.getClosestScrollableContainer(
4565 this.$floatableContainer
[ 0 ]
4567 // If the scrollable is the root, we have to listen to scroll events
4568 // on the window because of browser inconsistencies.
4569 if ( $( closestScrollableOfContainer
).is( 'html, body' ) ) {
4570 closestScrollableOfContainer
= OO
.ui
.Element
.static.getWindow(
4571 closestScrollableOfContainer
4575 if ( positioning
) {
4576 this.$floatableWindow
= $( this.getElementWindow() );
4577 this.$floatableWindow
.on( 'resize', this.onFloatableWindowResizeHandler
);
4579 this.$floatableClosestScrollable
= $( closestScrollableOfContainer
);
4580 this.$floatableClosestScrollable
.on( 'scroll', this.onFloatableScrollHandler
);
4582 // Initial position after visible
4585 if ( this.$floatableWindow
) {
4586 this.$floatableWindow
.off( 'resize', this.onFloatableWindowResizeHandler
);
4587 this.$floatableWindow
= null;
4590 if ( this.$floatableClosestScrollable
) {
4591 this.$floatableClosestScrollable
.off( 'scroll', this.onFloatableScrollHandler
);
4592 this.$floatableClosestScrollable
= null;
4595 this.$floatable
.css( { left
: '', right
: '', top
: '' } );
4603 * Check whether the bottom edge of the given element is within the viewport of the given
4607 * @param {jQuery} $element
4608 * @param {jQuery} $container
4611 OO
.ui
.mixin
.FloatableElement
.prototype.isElementInViewport = function ( $element
, $container
) {
4612 var elemRect
, contRect
, topEdgeInBounds
, bottomEdgeInBounds
, leftEdgeInBounds
,
4613 rightEdgeInBounds
, startEdgeInBounds
, endEdgeInBounds
, viewportSpacing
,
4614 direction
= $element
.css( 'direction' );
4616 elemRect
= $element
[ 0 ].getBoundingClientRect();
4617 if ( $container
[ 0 ] === window
) {
4618 viewportSpacing
= OO
.ui
.getViewportSpacing();
4622 right
: document
.documentElement
.clientWidth
,
4623 bottom
: document
.documentElement
.clientHeight
4625 contRect
.top
+= viewportSpacing
.top
;
4626 contRect
.left
+= viewportSpacing
.left
;
4627 contRect
.right
-= viewportSpacing
.right
;
4628 contRect
.bottom
-= viewportSpacing
.bottom
;
4630 contRect
= $container
[ 0 ].getBoundingClientRect();
4633 topEdgeInBounds
= elemRect
.top
>= contRect
.top
&& elemRect
.top
<= contRect
.bottom
;
4634 bottomEdgeInBounds
= elemRect
.bottom
>= contRect
.top
&& elemRect
.bottom
<= contRect
.bottom
;
4635 leftEdgeInBounds
= elemRect
.left
>= contRect
.left
&& elemRect
.left
<= contRect
.right
;
4636 rightEdgeInBounds
= elemRect
.right
>= contRect
.left
&& elemRect
.right
<= contRect
.right
;
4637 if ( direction
=== 'rtl' ) {
4638 startEdgeInBounds
= rightEdgeInBounds
;
4639 endEdgeInBounds
= leftEdgeInBounds
;
4641 startEdgeInBounds
= leftEdgeInBounds
;
4642 endEdgeInBounds
= rightEdgeInBounds
;
4645 if ( this.verticalPosition
=== 'below' && !bottomEdgeInBounds
) {
4648 if ( this.verticalPosition
=== 'above' && !topEdgeInBounds
) {
4651 if ( this.horizontalPosition
=== 'before' && !startEdgeInBounds
) {
4654 if ( this.horizontalPosition
=== 'after' && !endEdgeInBounds
) {
4658 // The other positioning values are all about being inside the container,
4659 // so in those cases all we care about is that any part of the container is visible.
4660 return elemRect
.top
<= contRect
.bottom
&& elemRect
.bottom
>= contRect
.top
&&
4661 elemRect
.left
<= contRect
.right
&& elemRect
.right
>= contRect
.left
;
4665 * Check if the floatable is hidden to the user because it was offscreen.
4667 * @return {boolean} Floatable is out of view
4669 OO
.ui
.mixin
.FloatableElement
.prototype.isFloatableOutOfView = function () {
4670 return this.floatableOutOfView
;
4674 * Position the floatable below its container.
4676 * This should only be done when both of them are attached to the DOM and visible.
4679 * @return {OO.ui.Element} The element, for chaining
4681 OO
.ui
.mixin
.FloatableElement
.prototype.position = function () {
4682 if ( !this.positioning
) {
4687 // To continue, some things need to be true:
4688 // The element must actually be in the DOM
4689 this.isElementAttached() && (
4690 // The closest scrollable is the current window
4691 this.$floatableClosestScrollable
[ 0 ] === this.getElementWindow() ||
4692 // OR is an element in the element's DOM
4693 $.contains( this.getElementDocument(), this.$floatableClosestScrollable
[ 0 ] )
4696 // Abort early if important parts of the widget are no longer attached to the DOM
4700 this.floatableOutOfView
= this.hideWhenOutOfView
&&
4701 !this.isElementInViewport( this.$floatableContainer
, this.$floatableClosestScrollable
);
4702 if ( this.floatableOutOfView
) {
4703 this.$floatable
.addClass( 'oo-ui-element-hidden' );
4706 this.$floatable
.removeClass( 'oo-ui-element-hidden' );
4709 this.$floatable
.css( this.computePosition() );
4711 // We updated the position, so re-evaluate the clipping state.
4712 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
4713 // will not notice the need to update itself.)
4714 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here.
4715 // Why does it not listen to the right events in the right places?
4724 * Compute how #$floatable should be positioned based on the position of #$floatableContainer
4725 * and the positioning settings. This is a helper for #position that shouldn't be called directly,
4726 * but may be overridden by subclasses if they want to change or add to the positioning logic.
4728 * @return {Object} New position to apply with .css(). Keys are 'top', 'left', 'bottom' and 'right'.
4730 OO
.ui
.mixin
.FloatableElement
.prototype.computePosition = function () {
4731 var isBody
, scrollableX
, scrollableY
, containerPos
,
4732 horizScrollbarHeight
, vertScrollbarWidth
, scrollTop
, scrollLeft
,
4733 newPos
= { top
: '', left
: '', bottom
: '', right
: '' },
4734 direction
= this.$floatableContainer
.css( 'direction' ),
4735 $offsetParent
= this.$floatable
.offsetParent();
4737 if ( $offsetParent
.is( 'html' ) ) {
4738 // The innerHeight/Width and clientHeight/Width calculations don't work well on the
4739 // <html> element, but they do work on the <body>
4740 $offsetParent
= $( $offsetParent
[ 0 ].ownerDocument
.body
);
4742 isBody
= $offsetParent
.is( 'body' );
4743 scrollableX
= $offsetParent
.css( 'overflow-x' ) === 'scroll' ||
4744 $offsetParent
.css( 'overflow-x' ) === 'auto';
4745 scrollableY
= $offsetParent
.css( 'overflow-y' ) === 'scroll' ||
4746 $offsetParent
.css( 'overflow-y' ) === 'auto';
4748 vertScrollbarWidth
= $offsetParent
.innerWidth() - $offsetParent
.prop( 'clientWidth' );
4749 horizScrollbarHeight
= $offsetParent
.innerHeight() - $offsetParent
.prop( 'clientHeight' );
4750 // We don't need to compute and add scrollTop and scrollLeft if the scrollable container
4751 // is the body, or if it isn't scrollable
4752 scrollTop
= scrollableY
&& !isBody
?
4753 $offsetParent
.scrollTop() : 0;
4754 scrollLeft
= scrollableX
&& !isBody
?
4755 OO
.ui
.Element
.static.getScrollLeft( $offsetParent
[ 0 ] ) : 0;
4757 // Avoid passing the <body> to getRelativePosition(), because it won't return what we expect
4758 // if the <body> has a margin
4759 containerPos
= isBody
?
4760 this.$floatableContainer
.offset() :
4761 OO
.ui
.Element
.static.getRelativePosition( this.$floatableContainer
, $offsetParent
);
4762 containerPos
.bottom
= containerPos
.top
+ this.$floatableContainer
.outerHeight();
4763 containerPos
.right
= containerPos
.left
+ this.$floatableContainer
.outerWidth();
4764 containerPos
.start
= direction
=== 'rtl' ? containerPos
.right
: containerPos
.left
;
4765 containerPos
.end
= direction
=== 'rtl' ? containerPos
.left
: containerPos
.right
;
4767 if ( this.verticalPosition
=== 'below' ) {
4768 newPos
.top
= containerPos
.bottom
;
4769 } else if ( this.verticalPosition
=== 'above' ) {
4770 newPos
.bottom
= $offsetParent
.outerHeight() - containerPos
.top
;
4771 } else if ( this.verticalPosition
=== 'top' ) {
4772 newPos
.top
= containerPos
.top
;
4773 } else if ( this.verticalPosition
=== 'bottom' ) {
4774 newPos
.bottom
= $offsetParent
.outerHeight() - containerPos
.bottom
;
4775 } else if ( this.verticalPosition
=== 'center' ) {
4776 newPos
.top
= containerPos
.top
+
4777 ( this.$floatableContainer
.height() - this.$floatable
.height() ) / 2;
4780 if ( this.horizontalPosition
=== 'before' ) {
4781 newPos
.end
= containerPos
.start
;
4782 } else if ( this.horizontalPosition
=== 'after' ) {
4783 newPos
.start
= containerPos
.end
;
4784 } else if ( this.horizontalPosition
=== 'start' ) {
4785 newPos
.start
= containerPos
.start
;
4786 } else if ( this.horizontalPosition
=== 'end' ) {
4787 newPos
.end
= containerPos
.end
;
4788 } else if ( this.horizontalPosition
=== 'center' ) {
4789 newPos
.left
= containerPos
.left
+
4790 ( this.$floatableContainer
.width() - this.$floatable
.width() ) / 2;
4793 if ( newPos
.start
!== undefined ) {
4794 if ( direction
=== 'rtl' ) {
4795 newPos
.right
= ( isBody
? $( $offsetParent
[ 0 ].ownerDocument
.documentElement
) :
4796 $offsetParent
).outerWidth() - newPos
.start
;
4798 newPos
.left
= newPos
.start
;
4800 delete newPos
.start
;
4802 if ( newPos
.end
!== undefined ) {
4803 if ( direction
=== 'rtl' ) {
4804 newPos
.left
= newPos
.end
;
4806 newPos
.right
= ( isBody
? $( $offsetParent
[ 0 ].ownerDocument
.documentElement
) :
4807 $offsetParent
).outerWidth() - newPos
.end
;
4812 // Account for scroll position
4813 if ( newPos
.top
!== '' ) {
4814 newPos
.top
+= scrollTop
;
4816 if ( newPos
.bottom
!== '' ) {
4817 newPos
.bottom
-= scrollTop
;
4819 if ( newPos
.left
!== '' ) {
4820 newPos
.left
+= scrollLeft
;
4822 if ( newPos
.right
!== '' ) {
4823 newPos
.right
-= scrollLeft
;
4826 // Account for scrollbar gutter
4827 if ( newPos
.bottom
!== '' ) {
4828 newPos
.bottom
-= horizScrollbarHeight
;
4830 if ( direction
=== 'rtl' ) {
4831 if ( newPos
.left
!== '' ) {
4832 newPos
.left
-= vertScrollbarWidth
;
4835 if ( newPos
.right
!== '' ) {
4836 newPos
.right
-= vertScrollbarWidth
;
4844 * Element that can be automatically clipped to visible boundaries.
4846 * Whenever the element's natural height changes, you have to call
4847 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
4848 * clipping correctly.
4850 * The dimensions of #$clippableContainer will be compared to the boundaries of the
4851 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
4852 * then #$clippable will be given a fixed reduced height and/or width and will be made
4853 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
4854 * but you can build a static footer by setting #$clippableContainer to an element that contains
4855 * #$clippable and the footer.
4861 * @param {Object} [config] Configuration options
4862 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
4863 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
4864 * omit to use #$clippable
4866 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
4867 // Configuration initialization
4868 config
= config
|| {};
4871 this.$clippable
= null;
4872 this.$clippableContainer
= null;
4873 this.clipping
= false;
4874 this.clippedHorizontally
= false;
4875 this.clippedVertically
= false;
4876 this.$clippableScrollableContainer
= null;
4877 this.$clippableScroller
= null;
4878 this.$clippableWindow
= null;
4879 this.idealWidth
= null;
4880 this.idealHeight
= null;
4881 this.onClippableScrollHandler
= this.clip
.bind( this );
4882 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
4885 if ( config
.$clippableContainer
) {
4886 this.setClippableContainer( config
.$clippableContainer
);
4888 this.setClippableElement( config
.$clippable
|| this.$element
);
4894 * Set clippable element.
4896 * If an element is already set, it will be cleaned up before setting up the new element.
4898 * @param {jQuery} $clippable Element to make clippable
4900 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
4901 if ( this.$clippable
) {
4902 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
4903 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
4904 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4907 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
4912 * Set clippable container.
4914 * This is the container that will be measured when deciding whether to clip. When clipping,
4915 * #$clippable will be resized in order to keep the clippable container fully visible.
4917 * If the clippable container is unset, #$clippable will be used.
4919 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
4921 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableContainer = function ( $clippableContainer
) {
4922 this.$clippableContainer
= $clippableContainer
;
4923 if ( this.$clippable
) {
4931 * Do not turn clipping on until after the element is attached to the DOM and visible.
4933 * @param {boolean} [clipping] Enable clipping, omit to toggle
4935 * @return {OO.ui.Element} The element, for chaining
4937 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
4938 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
4940 if ( clipping
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4941 OO
.ui
.warnDeprecation( 'ClippableElement#toggleClipping: Before calling this method, the element must be attached to the DOM.' );
4942 this.warnedUnattached
= true;
4945 if ( this.clipping
!== clipping
) {
4946 this.clipping
= clipping
;
4948 this.$clippableScrollableContainer
= $( this.getClosestScrollableElementContainer() );
4949 // If the clippable container is the root, we have to listen to scroll events and check
4950 // jQuery.scrollTop on the window because of browser inconsistencies
4951 this.$clippableScroller
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
4952 $( OO
.ui
.Element
.static.getWindow( this.$clippableScrollableContainer
) ) :
4953 this.$clippableScrollableContainer
;
4954 this.$clippableScroller
.on( 'scroll', this.onClippableScrollHandler
);
4955 this.$clippableWindow
= $( this.getElementWindow() )
4956 .on( 'resize', this.onClippableWindowResizeHandler
);
4957 // Initial clip after visible
4960 this.$clippable
.css( {
4968 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4970 this.$clippableScrollableContainer
= null;
4971 this.$clippableScroller
.off( 'scroll', this.onClippableScrollHandler
);
4972 this.$clippableScroller
= null;
4973 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
4974 this.$clippableWindow
= null;
4982 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4984 * @return {boolean} Element will be clipped to the visible area
4986 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
4987 return this.clipping
;
4991 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
4993 * @return {boolean} Part of the element is being clipped
4995 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
4996 return this.clippedHorizontally
|| this.clippedVertically
;
5000 * Check if the right of the element is being clipped by the nearest scrollable container.
5002 * @return {boolean} Part of the element is being clipped
5004 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
5005 return this.clippedHorizontally
;
5009 * Check if the bottom of the element is being clipped by the nearest scrollable container.
5011 * @return {boolean} Part of the element is being clipped
5013 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
5014 return this.clippedVertically
;
5018 * Set the ideal size. These are the dimensions #$clippable will have when it's not being clipped.
5020 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
5021 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
5023 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
5024 this.idealWidth
= width
;
5025 this.idealHeight
= height
;
5027 if ( !this.clipping
) {
5028 // Update dimensions
5029 this.$clippable
.css( { width
: width
, height
: height
} );
5031 // While clipping, idealWidth and idealHeight are not considered
5035 * Return the side of the clippable on which it is "anchored" (aligned to something else).
5036 * ClippableElement will clip the opposite side when reducing element's width.
5038 * Classes that mix in ClippableElement should override this to return 'right' if their
5039 * clippable is absolutely positioned and using 'right: Npx' (and not using 'left').
5040 * If your class also mixes in FloatableElement, this is handled automatically.
5042 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
5043 * always in pixels, even if they were unset or set to 'auto'.)
5045 * When in doubt, 'left' (or 'right' in RTL) is a sane fallback.
5047 * @return {string} 'left' or 'right'
5049 OO
.ui
.mixin
.ClippableElement
.prototype.getHorizontalAnchorEdge = function () {
5050 if ( this.computePosition
&& this.positioning
&& this.computePosition().right
!== '' ) {
5057 * Return the side of the clippable on which it is "anchored" (aligned to something else).
5058 * ClippableElement will clip the opposite side when reducing element's width.
5060 * Classes that mix in ClippableElement should override this to return 'bottom' if their
5061 * clippable is absolutely positioned and using 'bottom: Npx' (and not using 'top').
5062 * If your class also mixes in FloatableElement, this is handled automatically.
5064 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
5065 * always in pixels, even if they were unset or set to 'auto'.)
5067 * When in doubt, 'top' is a sane fallback.
5069 * @return {string} 'top' or 'bottom'
5071 OO
.ui
.mixin
.ClippableElement
.prototype.getVerticalAnchorEdge = function () {
5072 if ( this.computePosition
&& this.positioning
&& this.computePosition().bottom
!== '' ) {
5079 * Clip element to visible boundaries and allow scrolling when needed. You should call this method
5080 * when the element's natural height changes.
5082 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
5083 * overlapped by, the visible area of the nearest scrollable container.
5085 * Because calling clip() when the natural height changes isn't always possible, we also set
5086 * max-height when the element isn't being clipped. This means that if the element tries to grow
5087 * beyond the edge, something reasonable will happen before clip() is called.
5090 * @return {OO.ui.Element} The element, for chaining
5092 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
5093 var extraHeight
, extraWidth
, viewportSpacing
,
5094 desiredWidth
, desiredHeight
, allotedWidth
, allotedHeight
,
5095 naturalWidth
, naturalHeight
, clipWidth
, clipHeight
,
5096 $item
, itemRect
, $viewport
, viewportRect
, availableRect
,
5097 direction
, vertScrollbarWidth
, horizScrollbarHeight
,
5098 // Extra tolerance so that the sloppy code below doesn't result in results that are off
5099 // by one or two pixels. (And also so that we have space to display drop shadows.)
5100 // Chosen by fair dice roll.
5103 if ( !this.clipping
) {
5104 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below
5109 function rectIntersection( a
, b
) {
5111 out
.top
= Math
.max( a
.top
, b
.top
);
5112 out
.left
= Math
.max( a
.left
, b
.left
);
5113 out
.bottom
= Math
.min( a
.bottom
, b
.bottom
);
5114 out
.right
= Math
.min( a
.right
, b
.right
);
5118 viewportSpacing
= OO
.ui
.getViewportSpacing();
5120 if ( this.$clippableScrollableContainer
.is( 'html, body' ) ) {
5121 $viewport
= $( this.$clippableScrollableContainer
[ 0 ].ownerDocument
.body
);
5122 // Dimensions of the browser window, rather than the element!
5126 right
: document
.documentElement
.clientWidth
,
5127 bottom
: document
.documentElement
.clientHeight
5129 viewportRect
.top
+= viewportSpacing
.top
;
5130 viewportRect
.left
+= viewportSpacing
.left
;
5131 viewportRect
.right
-= viewportSpacing
.right
;
5132 viewportRect
.bottom
-= viewportSpacing
.bottom
;
5134 $viewport
= this.$clippableScrollableContainer
;
5135 viewportRect
= $viewport
[ 0 ].getBoundingClientRect();
5136 // Convert into a plain object
5137 viewportRect
= $.extend( {}, viewportRect
);
5140 // Account for scrollbar gutter
5141 direction
= $viewport
.css( 'direction' );
5142 vertScrollbarWidth
= $viewport
.innerWidth() - $viewport
.prop( 'clientWidth' );
5143 horizScrollbarHeight
= $viewport
.innerHeight() - $viewport
.prop( 'clientHeight' );
5144 viewportRect
.bottom
-= horizScrollbarHeight
;
5145 if ( direction
=== 'rtl' ) {
5146 viewportRect
.left
+= vertScrollbarWidth
;
5148 viewportRect
.right
-= vertScrollbarWidth
;
5151 // Add arbitrary tolerance
5152 viewportRect
.top
+= buffer
;
5153 viewportRect
.left
+= buffer
;
5154 viewportRect
.right
-= buffer
;
5155 viewportRect
.bottom
-= buffer
;
5157 $item
= this.$clippableContainer
|| this.$clippable
;
5159 extraHeight
= $item
.outerHeight() - this.$clippable
.outerHeight();
5160 extraWidth
= $item
.outerWidth() - this.$clippable
.outerWidth();
5162 itemRect
= $item
[ 0 ].getBoundingClientRect();
5163 // Convert into a plain object
5164 itemRect
= $.extend( {}, itemRect
);
5166 // Item might already be clipped, so we can't just use its dimensions (in case we might need to
5167 // make it larger than before). Extend the rectangle to the maximum size we are allowed to take.
5168 if ( this.getHorizontalAnchorEdge() === 'right' ) {
5169 itemRect
.left
= viewportRect
.left
;
5171 itemRect
.right
= viewportRect
.right
;
5173 if ( this.getVerticalAnchorEdge() === 'bottom' ) {
5174 itemRect
.top
= viewportRect
.top
;
5176 itemRect
.bottom
= viewportRect
.bottom
;
5179 availableRect
= rectIntersection( viewportRect
, itemRect
);
5181 desiredWidth
= Math
.max( 0, availableRect
.right
- availableRect
.left
);
5182 desiredHeight
= Math
.max( 0, availableRect
.bottom
- availableRect
.top
);
5183 // It should never be desirable to exceed the dimensions of the browser viewport... right?
5184 desiredWidth
= Math
.min( desiredWidth
,
5185 document
.documentElement
.clientWidth
- viewportSpacing
.left
- viewportSpacing
.right
);
5186 desiredHeight
= Math
.min( desiredHeight
,
5187 document
.documentElement
.clientHeight
- viewportSpacing
.top
- viewportSpacing
.right
);
5188 allotedWidth
= Math
.ceil( desiredWidth
- extraWidth
);
5189 allotedHeight
= Math
.ceil( desiredHeight
- extraHeight
);
5190 naturalWidth
= this.$clippable
.prop( 'scrollWidth' );
5191 naturalHeight
= this.$clippable
.prop( 'scrollHeight' );
5192 clipWidth
= allotedWidth
< naturalWidth
;
5193 clipHeight
= allotedHeight
< naturalHeight
;
5196 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars.
5198 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for
5200 this.$clippable
.css( 'overflowX', 'scroll' );
5201 // eslint-disable-next-line no-void
5202 void this.$clippable
[ 0 ].offsetHeight
; // Force reflow
5203 this.$clippable
.css( {
5204 width
: Math
.max( 0, allotedWidth
),
5208 this.$clippable
.css( {
5210 width
: this.idealWidth
|| '',
5211 maxWidth
: Math
.max( 0, allotedWidth
)
5215 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars.
5217 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for
5219 this.$clippable
.css( 'overflowY', 'scroll' );
5220 // eslint-disable-next-line no-void
5221 void this.$clippable
[ 0 ].offsetHeight
; // Force reflow
5222 this.$clippable
.css( {
5223 height
: Math
.max( 0, allotedHeight
),
5227 this.$clippable
.css( {
5229 height
: this.idealHeight
|| '',
5230 maxHeight
: Math
.max( 0, allotedHeight
)
5234 // If we stopped clipping in at least one of the dimensions
5235 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
5236 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
5239 this.clippedHorizontally
= clipWidth
;
5240 this.clippedVertically
= clipHeight
;
5246 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
5247 * By default, each popup has an anchor that points toward its origin.
5248 * Please see the [OOUI documentation on MediaWiki.org] [1] for more information and examples.
5250 * Unlike most widgets, PopupWidget is initially hidden and must be shown by calling #toggle.
5254 * var popup = new OO.ui.PopupWidget( {
5255 * $content: $( '<p>Hi there!</p>' ),
5260 * $( document.body ).append( popup.$element );
5261 * // To display the popup, toggle the visibility to 'true'.
5262 * popup.toggle( true );
5264 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups
5267 * @extends OO.ui.Widget
5268 * @mixins OO.ui.mixin.LabelElement
5269 * @mixins OO.ui.mixin.ClippableElement
5270 * @mixins OO.ui.mixin.FloatableElement
5273 * @param {Object} [config] Configuration options
5274 * @cfg {number|null} [width=320] Width of popup in pixels. Pass `null` to use automatic width.
5275 * @cfg {number|null} [height=null] Height of popup in pixels. Pass `null` to use automatic height.
5276 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
5277 * @cfg {string} [position='below'] Where to position the popup relative to $floatableContainer
5278 * 'above': Put popup above $floatableContainer; anchor points down to the horizontal center
5279 * of $floatableContainer
5280 * 'below': Put popup below $floatableContainer; anchor points up to the horizontal center
5281 * of $floatableContainer
5282 * 'before': Put popup to the left (LTR) / right (RTL) of $floatableContainer; anchor points
5283 * endwards (right/left) to the vertical center of $floatableContainer
5284 * 'after': Put popup to the right (LTR) / left (RTL) of $floatableContainer; anchor points
5285 * startwards (left/right) to the vertical center of $floatableContainer
5286 * @cfg {string} [align='center'] How to align the popup to $floatableContainer
5287 * 'forwards': If position is above/below, move the popup as far endwards (right in LTR, left in
5288 * RTL) as possible while still keeping the anchor within the popup; if position is before/after,
5289 * move the popup as far downwards as possible.
5290 * 'backwards': If position is above/below, move the popup as far startwards (left in LTR, right in
5291 * RTL) as possible while still keeping the anchor within the popup; if position is before/after,
5292 * move the popup as far upwards as possible.
5293 * 'center': Horizontally (if position is above/below) or vertically (before/after) align the
5294 * center of the popup with the center of $floatableContainer.
5295 * 'force-left': Alias for 'forwards' in LTR and 'backwards' in RTL
5296 * 'force-right': Alias for 'backwards' in RTL and 'forwards' in LTR
5297 * @cfg {boolean} [autoFlip=true] Whether to automatically switch the popup's position between
5298 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5299 * desired direction to display the popup without clipping
5300 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
5301 * See the [OOUI docs on MediaWiki][3] for an example.
5302 * [3]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#containerExample
5303 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a
5305 * @cfg {jQuery} [$content] Content to append to the popup's body
5306 * @cfg {jQuery} [$footer] Content to append to the popup's footer
5307 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
5308 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
5309 * This config option is only relevant if #autoClose is set to `true`. See the
5310 * [OOUI documentation on MediaWiki][2] for an example.
5311 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#autocloseExample
5312 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
5314 * @cfg {boolean} [padded=false] Add padding to the popup's body
5316 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
5317 // Configuration initialization
5318 config
= config
|| {};
5320 // Parent constructor
5321 OO
.ui
.PopupWidget
.parent
.call( this, config
);
5323 // Properties (must be set before ClippableElement constructor call)
5324 this.$body
= $( '<div>' );
5325 this.$popup
= $( '<div>' );
5327 // Mixin constructors
5328 OO
.ui
.mixin
.LabelElement
.call( this, config
);
5329 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {
5330 $clippable
: this.$body
,
5331 $clippableContainer
: this.$popup
5333 OO
.ui
.mixin
.FloatableElement
.call( this, config
);
5336 this.$anchor
= $( '<div>' );
5337 // If undefined, will be computed lazily in computePosition()
5338 this.$container
= config
.$container
;
5339 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
5340 this.autoClose
= !!config
.autoClose
;
5341 this.transitionTimeout
= null;
5342 this.anchored
= false;
5343 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
5344 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
5347 this.setSize( config
.width
, config
.height
);
5348 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
5349 this.setAlignment( config
.align
|| 'center' );
5350 this.setPosition( config
.position
|| 'below' );
5351 this.setAutoFlip( config
.autoFlip
=== undefined || config
.autoFlip
);
5352 this.setAutoCloseIgnore( config
.$autoCloseIgnore
);
5353 this.$body
.addClass( 'oo-ui-popupWidget-body' );
5354 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
5356 .addClass( 'oo-ui-popupWidget-popup' )
5357 .append( this.$body
);
5359 .addClass( 'oo-ui-popupWidget' )
5360 .append( this.$popup
, this.$anchor
);
5361 // Move content, which was added to #$element by OO.ui.Widget, to the body
5362 // FIXME This is gross, we should use '$body' or something for the config
5363 if ( config
.$content
instanceof $ ) {
5364 this.$body
.append( config
.$content
);
5367 if ( config
.padded
) {
5368 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
5371 if ( config
.head
) {
5372 this.closeButton
= new OO
.ui
.ButtonWidget( {
5376 this.closeButton
.connect( this, {
5377 click
: 'onCloseButtonClick'
5379 this.$head
= $( '<div>' )
5380 .addClass( 'oo-ui-popupWidget-head' )
5381 .append( this.$label
, this.closeButton
.$element
);
5382 this.$popup
.prepend( this.$head
);
5385 if ( config
.$footer
) {
5386 this.$footer
= $( '<div>' )
5387 .addClass( 'oo-ui-popupWidget-footer' )
5388 .append( config
.$footer
);
5389 this.$popup
.append( this.$footer
);
5392 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
5393 // that reference properties not initialized at that time of parent class construction
5394 // TODO: Find a better way to handle post-constructor setup
5395 this.visible
= false;
5396 this.$element
.addClass( 'oo-ui-element-hidden' );
5401 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
5402 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
5403 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
5404 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.FloatableElement
);
5411 * The popup is ready: it is visible and has been positioned and clipped.
5417 * Handles document mouse down events.
5420 * @param {MouseEvent} e Mouse down event
5422 OO
.ui
.PopupWidget
.prototype.onDocumentMouseDown = function ( e
) {
5425 !OO
.ui
.contains( this.$element
.add( this.$autoCloseIgnore
).get(), e
.target
, true )
5427 this.toggle( false );
5432 * Bind document mouse down listener.
5436 OO
.ui
.PopupWidget
.prototype.bindDocumentMouseDownListener = function () {
5437 // Capture clicks outside popup
5438 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
5439 // We add 'click' event because iOS safari needs to respond to this event.
5440 // We can't use 'touchstart' (as is usually the equivalent to 'mousedown') because
5441 // then it will trigger when scrolling. While iOS Safari has some reported behavior
5442 // of occasionally not emitting 'click' properly, that event seems to be the standard
5443 // that it should be emitting, so we add it to this and will operate the event handler
5444 // on whichever of these events was triggered first
5445 this.getElementDocument().addEventListener( 'click', this.onDocumentMouseDownHandler
, true );
5449 * Handles close button click events.
5453 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
5454 if ( this.isVisible() ) {
5455 this.toggle( false );
5460 * Unbind document mouse down listener.
5464 OO
.ui
.PopupWidget
.prototype.unbindDocumentMouseDownListener = function () {
5465 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
5466 this.getElementDocument().removeEventListener( 'click', this.onDocumentMouseDownHandler
, true );
5470 * Handles document key down events.
5473 * @param {KeyboardEvent} e Key down event
5475 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
5477 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
5480 this.toggle( false );
5482 e
.stopPropagation();
5487 * Bind document key down listener.
5491 OO
.ui
.PopupWidget
.prototype.bindDocumentKeyDownListener = function () {
5492 this.getElementDocument().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
5496 * Unbind document key down listener.
5500 OO
.ui
.PopupWidget
.prototype.unbindDocumentKeyDownListener = function () {
5501 this.getElementDocument().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
5505 * Show, hide, or toggle the visibility of the anchor.
5507 * @param {boolean} [show] Show anchor, omit to toggle
5509 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
5510 show
= show
=== undefined ? !this.anchored
: !!show
;
5512 if ( this.anchored
!== show
) {
5514 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
5515 this.$element
.addClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5517 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
5518 this.$element
.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5520 this.anchored
= show
;
5525 * Change which edge the anchor appears on.
5527 * @param {string} edge 'top', 'bottom', 'start' or 'end'
5529 OO
.ui
.PopupWidget
.prototype.setAnchorEdge = function ( edge
) {
5530 if ( [ 'top', 'bottom', 'start', 'end' ].indexOf( edge
) === -1 ) {
5531 throw new Error( 'Invalid value for edge: ' + edge
);
5533 if ( this.anchorEdge
!== null ) {
5534 this.$element
.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5536 this.anchorEdge
= edge
;
5537 if ( this.anchored
) {
5538 this.$element
.addClass( 'oo-ui-popupWidget-anchored-' + edge
);
5543 * Check if the anchor is visible.
5545 * @return {boolean} Anchor is visible
5547 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
5548 return this.anchored
;
5552 * Toggle visibility of the popup. The popup is initially hidden and must be shown by calling
5553 * `.toggle( true )` after its #$element is attached to the DOM.
5555 * Do not show the popup while it is not attached to the DOM. The calculations required to display
5556 * it in the right place and with the right dimensions only work correctly while it is attached.
5557 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
5558 * strictly enforced, so currently it only generates a warning in the browser console.
5563 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
5564 var change
, normalHeight
, oppositeHeight
, normalWidth
, oppositeWidth
;
5565 show
= show
=== undefined ? !this.isVisible() : !!show
;
5567 change
= show
!== this.isVisible();
5569 if ( show
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
5570 OO
.ui
.warnDeprecation( 'PopupWidget#toggle: Before calling this method, the popup must be attached to the DOM.' );
5571 this.warnedUnattached
= true;
5573 if ( show
&& !this.$floatableContainer
&& this.isElementAttached() ) {
5574 // Fall back to the parent node if the floatableContainer is not set
5575 this.setFloatableContainer( this.$element
.parent() );
5578 if ( change
&& show
&& this.autoFlip
) {
5579 // Reset auto-flipping before showing the popup again. It's possible we no longer need to
5580 // flip (e.g. if the user scrolled).
5581 this.isAutoFlipped
= false;
5585 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
5588 this.togglePositioning( show
&& !!this.$floatableContainer
);
5591 if ( this.autoClose
) {
5592 this.bindDocumentMouseDownListener();
5593 this.bindDocumentKeyDownListener();
5595 this.updateDimensions();
5596 this.toggleClipping( true );
5598 if ( this.autoFlip
) {
5599 if ( this.popupPosition
=== 'above' || this.popupPosition
=== 'below' ) {
5600 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5601 // If opening the popup in the normal direction causes it to be clipped,
5602 // open in the opposite one instead
5603 normalHeight
= this.$element
.height();
5604 this.isAutoFlipped
= !this.isAutoFlipped
;
5606 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5607 // If that also causes it to be clipped, open in whichever direction
5608 // we have more space
5609 oppositeHeight
= this.$element
.height();
5610 if ( oppositeHeight
< normalHeight
) {
5611 this.isAutoFlipped
= !this.isAutoFlipped
;
5617 if ( this.popupPosition
=== 'before' || this.popupPosition
=== 'after' ) {
5618 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5619 // If opening the popup in the normal direction causes it to be clipped,
5620 // open in the opposite one instead
5621 normalWidth
= this.$element
.width();
5622 this.isAutoFlipped
= !this.isAutoFlipped
;
5623 // Due to T180173 horizontally clipped PopupWidgets have messed up
5624 // dimensions, which causes positioning to be off. Toggle clipping back and
5625 // forth to work around.
5626 this.toggleClipping( false );
5628 this.toggleClipping( true );
5629 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5630 // If that also causes it to be clipped, open in whichever direction
5631 // we have more space
5632 oppositeWidth
= this.$element
.width();
5633 if ( oppositeWidth
< normalWidth
) {
5634 this.isAutoFlipped
= !this.isAutoFlipped
;
5635 // Due to T180173, horizontally clipped PopupWidgets have messed up
5636 // dimensions, which causes positioning to be off. Toggle clipping
5637 // back and forth to work around.
5638 this.toggleClipping( false );
5640 this.toggleClipping( true );
5647 this.emit( 'ready' );
5649 this.toggleClipping( false );
5650 if ( this.autoClose
) {
5651 this.unbindDocumentMouseDownListener();
5652 this.unbindDocumentKeyDownListener();
5661 * Set the size of the popup.
5663 * Changing the size may also change the popup's position depending on the alignment.
5665 * @param {number|null} [width=320] Width in pixels. Pass `null` to use automatic width.
5666 * @param {number|null} [height=null] Height in pixels. Pass `null` to use automatic height.
5667 * @param {boolean} [transition=false] Use a smooth transition
5670 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
5671 this.width
= width
!== undefined ? width
: 320;
5672 this.height
= height
!== undefined ? height
: null;
5673 if ( this.isVisible() ) {
5674 this.updateDimensions( transition
);
5679 * Update the size and position.
5681 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
5682 * be called automatically.
5684 * @param {boolean} [transition=false] Use a smooth transition
5687 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
5690 // Prevent transition from being interrupted
5691 clearTimeout( this.transitionTimeout
);
5693 // Enable transition
5694 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
5700 // Prevent transitioning after transition is complete
5701 this.transitionTimeout
= setTimeout( function () {
5702 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
5705 // Prevent transitioning immediately
5706 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
5713 OO
.ui
.PopupWidget
.prototype.computePosition = function () {
5714 var direction
, align
, vertical
, start
, end
, near
, far
, sizeProp
, popupSize
, anchorSize
,
5715 anchorPos
, anchorOffset
, anchorMargin
, parentPosition
, positionProp
, positionAdjustment
,
5716 floatablePos
, offsetParentPos
, containerPos
, popupPosition
, viewportSpacing
,
5718 anchorCss
= { left
: '', right
: '', top
: '', bottom
: '' },
5719 popupPositionOppositeMap
= {
5727 'force-left': 'backwards',
5728 'force-right': 'forwards'
5731 'force-left': 'forwards',
5732 'force-right': 'backwards'
5744 backwards
: this.anchored
? 'before' : 'end'
5752 if ( !this.$container
) {
5753 // Lazy-initialize $container if not specified in constructor
5754 this.$container
= $( this.getClosestScrollableElementContainer() );
5756 direction
= this.$container
.css( 'direction' );
5758 // Set height and width before we do anything else, since it might cause our measurements
5759 // to change (e.g. due to scrollbars appearing or disappearing), and it also affects centering
5761 width
: this.width
!== null ? this.width
: 'auto',
5762 height
: this.height
!== null ? this.height
: 'auto'
5765 align
= alignMap
[ direction
][ this.align
] || this.align
;
5766 popupPosition
= this.popupPosition
;
5767 if ( this.isAutoFlipped
) {
5768 popupPosition
= popupPositionOppositeMap
[ popupPosition
];
5771 // If the popup is positioned before or after, then the anchor positioning is vertical,
5772 // otherwise horizontal
5773 vertical
= popupPosition
=== 'before' || popupPosition
=== 'after';
5774 start
= vertical
? 'top' : ( direction
=== 'rtl' ? 'right' : 'left' );
5775 end
= vertical
? 'bottom' : ( direction
=== 'rtl' ? 'left' : 'right' );
5776 near
= vertical
? 'top' : 'left';
5777 far
= vertical
? 'bottom' : 'right';
5778 sizeProp
= vertical
? 'Height' : 'Width';
5779 popupSize
= vertical
?
5780 ( this.height
|| this.$popup
.height() ) :
5781 ( this.width
|| this.$popup
.width() );
5783 this.setAnchorEdge( anchorEdgeMap
[ popupPosition
] );
5784 this.horizontalPosition
= vertical
? popupPosition
: hPosMap
[ align
];
5785 this.verticalPosition
= vertical
? vPosMap
[ align
] : popupPosition
;
5788 parentPosition
= OO
.ui
.mixin
.FloatableElement
.prototype.computePosition
.call( this );
5789 // Find out which property FloatableElement used for positioning, and adjust that value
5790 positionProp
= vertical
?
5791 ( parentPosition
.top
!== '' ? 'top' : 'bottom' ) :
5792 ( parentPosition
.left
!== '' ? 'left' : 'right' );
5794 // Figure out where the near and far edges of the popup and $floatableContainer are
5795 floatablePos
= this.$floatableContainer
.offset();
5796 floatablePos
[ far
] = floatablePos
[ near
] + this.$floatableContainer
[ 'outer' + sizeProp
]();
5797 // Measure where the offsetParent is and compute our position based on that and parentPosition
5798 offsetParentPos
= this.$element
.offsetParent()[ 0 ] === document
.documentElement
?
5799 { top
: 0, left
: 0 } :
5800 this.$element
.offsetParent().offset();
5802 if ( positionProp
=== near
) {
5803 popupPos
[ near
] = offsetParentPos
[ near
] + parentPosition
[ near
];
5804 popupPos
[ far
] = popupPos
[ near
] + popupSize
;
5806 popupPos
[ far
] = offsetParentPos
[ near
] +
5807 this.$element
.offsetParent()[ 'inner' + sizeProp
]() - parentPosition
[ far
];
5808 popupPos
[ near
] = popupPos
[ far
] - popupSize
;
5811 if ( this.anchored
) {
5812 // Position the anchor (which is positioned relative to the popup) to point to
5813 // $floatableContainer
5814 anchorPos
= ( floatablePos
[ start
] + floatablePos
[ end
] ) / 2;
5815 anchorOffset
= ( start
=== far
? -1 : 1 ) * ( anchorPos
- popupPos
[ start
] );
5817 // If the anchor is less than 2*anchorSize from either edge, move the popup to make more
5818 // space this.$anchor.width()/height() returns 0 because of the CSS trickery we use, so use
5819 // scrollWidth/Height
5820 anchorSize
= this.$anchor
[ 0 ][ 'scroll' + sizeProp
];
5821 anchorMargin
= parseFloat( this.$anchor
.css( 'margin-' + start
) );
5822 if ( anchorOffset
+ anchorMargin
< 2 * anchorSize
) {
5823 // Not enough space for the anchor on the start side; pull the popup startwards
5824 positionAdjustment
= ( positionProp
=== start
? -1 : 1 ) *
5825 ( 2 * anchorSize
- ( anchorOffset
+ anchorMargin
) );
5826 } else if ( anchorOffset
+ anchorMargin
> popupSize
- 2 * anchorSize
) {
5827 // Not enough space for the anchor on the end side; pull the popup endwards
5828 positionAdjustment
= ( positionProp
=== end
? -1 : 1 ) *
5829 ( anchorOffset
+ anchorMargin
- ( popupSize
- 2 * anchorSize
) );
5831 positionAdjustment
= 0;
5834 positionAdjustment
= 0;
5837 // Check if the popup will go beyond the edge of this.$container
5838 containerPos
= this.$container
[ 0 ] === document
.documentElement
?
5839 { top
: 0, left
: 0 } :
5840 this.$container
.offset();
5841 containerPos
[ far
] = containerPos
[ near
] + this.$container
[ 'inner' + sizeProp
]();
5842 if ( this.$container
[ 0 ] === document
.documentElement
) {
5843 viewportSpacing
= OO
.ui
.getViewportSpacing();
5844 containerPos
[ near
] += viewportSpacing
[ near
];
5845 containerPos
[ far
] -= viewportSpacing
[ far
];
5847 // Take into account how much the popup will move because of the adjustments we're going to make
5848 popupPos
[ near
] += ( positionProp
=== near
? 1 : -1 ) * positionAdjustment
;
5849 popupPos
[ far
] += ( positionProp
=== near
? 1 : -1 ) * positionAdjustment
;
5850 if ( containerPos
[ near
] + this.containerPadding
> popupPos
[ near
] ) {
5851 // Popup goes beyond the near (left/top) edge, move it to the right/bottom
5852 positionAdjustment
+= ( positionProp
=== near
? 1 : -1 ) *
5853 ( containerPos
[ near
] + this.containerPadding
- popupPos
[ near
] );
5854 } else if ( containerPos
[ far
] - this.containerPadding
< popupPos
[ far
] ) {
5855 // Popup goes beyond the far (right/bottom) edge, move it to the left/top
5856 positionAdjustment
+= ( positionProp
=== far
? 1 : -1 ) *
5857 ( popupPos
[ far
] - ( containerPos
[ far
] - this.containerPadding
) );
5860 if ( this.anchored
) {
5861 // Adjust anchorOffset for positionAdjustment
5862 anchorOffset
+= ( positionProp
=== start
? -1 : 1 ) * positionAdjustment
;
5864 // Position the anchor
5865 anchorCss
[ start
] = anchorOffset
;
5866 this.$anchor
.css( anchorCss
);
5869 // Move the popup if needed
5870 parentPosition
[ positionProp
] += positionAdjustment
;
5872 return parentPosition
;
5876 * Set popup alignment
5878 * @param {string} [align=center] Alignment of the popup, `center`, `force-left`, `force-right`,
5879 * `backwards` or `forwards`.
5881 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
5882 // Validate alignment
5883 if ( [ 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
5886 this.align
= 'center';
5892 * Get popup alignment
5894 * @return {string} Alignment of the popup, `center`, `force-left`, `force-right`,
5895 * `backwards` or `forwards`.
5897 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
5902 * Change the positioning of the popup.
5904 * @param {string} position 'above', 'below', 'before' or 'after'
5906 OO
.ui
.PopupWidget
.prototype.setPosition = function ( position
) {
5907 if ( [ 'above', 'below', 'before', 'after' ].indexOf( position
) === -1 ) {
5910 this.popupPosition
= position
;
5915 * Get popup positioning.
5917 * @return {string} 'above', 'below', 'before' or 'after'
5919 OO
.ui
.PopupWidget
.prototype.getPosition = function () {
5920 return this.popupPosition
;
5924 * Set popup auto-flipping.
5926 * @param {boolean} autoFlip Whether to automatically switch the popup's position between
5927 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5928 * desired direction to display the popup without clipping
5930 OO
.ui
.PopupWidget
.prototype.setAutoFlip = function ( autoFlip
) {
5931 autoFlip
= !!autoFlip
;
5933 if ( this.autoFlip
!== autoFlip
) {
5934 this.autoFlip
= autoFlip
;
5939 * Set which elements will not close the popup when clicked.
5941 * For auto-closing popups, clicks on these elements will not cause the popup to auto-close.
5943 * @param {jQuery} $autoCloseIgnore Elements to ignore for auto-closing
5945 OO
.ui
.PopupWidget
.prototype.setAutoCloseIgnore = function ( $autoCloseIgnore
) {
5946 this.$autoCloseIgnore
= $autoCloseIgnore
;
5950 * Get an ID of the body element, this can be used as the
5951 * `aria-describedby` attribute for an input field.
5953 * @return {string} The ID of the body element
5955 OO
.ui
.PopupWidget
.prototype.getBodyId = function () {
5956 var id
= this.$body
.attr( 'id' );
5957 if ( id
=== undefined ) {
5958 id
= OO
.ui
.generateElementId();
5959 this.$body
.attr( 'id', id
);
5965 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5966 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5967 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5968 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5974 * @param {Object} [config] Configuration options
5975 * @cfg {Object} [popup] Configuration to pass to popup
5976 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5978 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
5979 // Configuration initialization
5980 config
= config
|| {};
5983 this.popup
= new OO
.ui
.PopupWidget( $.extend(
5986 $floatableContainer
: this.$element
5990 $autoCloseIgnore
: this.$element
.add( config
.popup
&& config
.popup
.$autoCloseIgnore
)
6000 * @return {OO.ui.PopupWidget} Popup widget
6002 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
6007 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
6008 * which is used to display additional information or options.
6011 * // A PopupButtonWidget.
6012 * var popupButton = new OO.ui.PopupButtonWidget( {
6013 * label: 'Popup button with options',
6016 * $content: $( '<p>Additional options here.</p>' ),
6018 * align: 'force-left'
6021 * // Append the button to the DOM.
6022 * $( document.body ).append( popupButton.$element );
6025 * @extends OO.ui.ButtonWidget
6026 * @mixins OO.ui.mixin.PopupElement
6029 * @param {Object} [config] Configuration options
6030 * @cfg {jQuery} [$overlay] Render the popup into a separate layer. This configuration is useful
6031 * in cases where the expanded popup is larger than its containing `<div>`. The specified overlay
6032 * layer is usually on top of the containing `<div>` and has a larger area. By default, the popup
6033 * uses relative positioning.
6034 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
6036 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
6037 // Configuration initialization
6038 config
= config
|| {};
6040 // Parent constructor
6041 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
6043 // Mixin constructors
6044 OO
.ui
.mixin
.PopupElement
.call( this, config
);
6047 this.$overlay
= ( config
.$overlay
=== true ?
6048 OO
.ui
.getDefaultOverlay() : config
.$overlay
) || this.$element
;
6051 this.connect( this, {
6056 this.$element
.addClass( 'oo-ui-popupButtonWidget' );
6058 .addClass( 'oo-ui-popupButtonWidget-popup' )
6059 .toggleClass( 'oo-ui-popupButtonWidget-framed-popup', this.isFramed() )
6060 .toggleClass( 'oo-ui-popupButtonWidget-frameless-popup', !this.isFramed() );
6061 this.$overlay
.append( this.popup
.$element
);
6066 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
6067 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
6072 * Handle the button action being triggered.
6076 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
6077 this.popup
.toggle();
6081 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
6083 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
6088 * @mixins OO.ui.mixin.GroupElement
6091 * @param {Object} [config] Configuration options
6093 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
6094 // Mixin constructors
6095 OO
.ui
.mixin
.GroupElement
.call( this, config
);
6100 OO
.mixinClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
6105 * Set the disabled state of the widget.
6107 * This will also update the disabled state of child widgets.
6109 * @param {boolean} disabled Disable widget
6111 * @return {OO.ui.Widget} The widget, for chaining
6113 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
6117 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
6118 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
6120 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
6122 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6123 this.items
[ i
].updateDisabled();
6131 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
6133 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group.
6134 * This allows bidirectional communication.
6136 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
6144 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
6151 * Check if widget is disabled.
6153 * Checks parent if present, making disabled state inheritable.
6155 * @return {boolean} Widget is disabled
6157 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
6158 return this.disabled
||
6159 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
6163 * Set group element is in.
6165 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
6167 * @return {OO.ui.Widget} The widget, for chaining
6169 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
6171 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
6172 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
6174 // Initialize item disabled states
6175 this.updateDisabled();
6181 * OptionWidgets are special elements that can be selected and configured with data. The
6182 * data is often unique for each option, but it does not have to be. OptionWidgets are used
6183 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
6184 * and examples, please see the [OOUI documentation on MediaWiki][1].
6186 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6189 * @extends OO.ui.Widget
6190 * @mixins OO.ui.mixin.ItemWidget
6191 * @mixins OO.ui.mixin.LabelElement
6192 * @mixins OO.ui.mixin.FlaggedElement
6193 * @mixins OO.ui.mixin.AccessKeyedElement
6194 * @mixins OO.ui.mixin.TitledElement
6197 * @param {Object} [config] Configuration options
6199 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
6200 // Configuration initialization
6201 config
= config
|| {};
6203 // Parent constructor
6204 OO
.ui
.OptionWidget
.parent
.call( this, config
);
6206 // Mixin constructors
6207 OO
.ui
.mixin
.ItemWidget
.call( this );
6208 OO
.ui
.mixin
.LabelElement
.call( this, config
);
6209 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
6210 OO
.ui
.mixin
.AccessKeyedElement
.call( this, config
);
6211 OO
.ui
.mixin
.TitledElement
.call( this, config
);
6214 this.highlighted
= false;
6215 this.pressed
= false;
6216 this.setSelected( !!config
.selected
);
6220 .data( 'oo-ui-optionWidget', this )
6221 // Allow programmatic focussing (and by access key), but not tabbing
6222 .attr( 'tabindex', '-1' )
6223 .attr( 'role', 'option' )
6224 .addClass( 'oo-ui-optionWidget' )
6225 .append( this.$label
);
6230 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
6231 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
6232 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
6233 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
6234 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
6235 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.TitledElement
);
6237 /* Static Properties */
6240 * Whether this option can be selected. See #setSelected.
6244 * @property {boolean}
6246 OO
.ui
.OptionWidget
.static.selectable
= true;
6249 * Whether this option can be highlighted. See #setHighlighted.
6253 * @property {boolean}
6255 OO
.ui
.OptionWidget
.static.highlightable
= true;
6258 * Whether this option can be pressed. See #setPressed.
6262 * @property {boolean}
6264 OO
.ui
.OptionWidget
.static.pressable
= true;
6267 * Whether this option will be scrolled into view when it is selected.
6271 * @property {boolean}
6273 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
6278 * Check if the option can be selected.
6280 * @return {boolean} Item is selectable
6282 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
6283 return this.constructor.static.selectable
&& !this.disabled
&& this.isVisible();
6287 * Check if the option can be highlighted. A highlight indicates that the option
6288 * may be selected when a user presses Enter key or clicks. Disabled items cannot
6291 * @return {boolean} Item is highlightable
6293 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
6294 return this.constructor.static.highlightable
&& !this.disabled
&& this.isVisible();
6298 * Check if the option can be pressed. The pressed state occurs when a user mouses
6299 * down on an item, but has not yet let go of the mouse.
6301 * @return {boolean} Item is pressable
6303 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
6304 return this.constructor.static.pressable
&& !this.disabled
&& this.isVisible();
6308 * Check if the option is selected.
6310 * @return {boolean} Item is selected
6312 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
6313 return this.selected
;
6317 * Check if the option is highlighted. A highlight indicates that the
6318 * item may be selected when a user presses Enter key or clicks.
6320 * @return {boolean} Item is highlighted
6322 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
6323 return this.highlighted
;
6327 * Check if the option is pressed. The pressed state occurs when a user mouses
6328 * down on an item, but has not yet let go of the mouse. The item may appear
6329 * selected, but it will not be selected until the user releases the mouse.
6331 * @return {boolean} Item is pressed
6333 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
6334 return this.pressed
;
6338 * Set the option’s selected state. In general, all modifications to the selection
6339 * should be handled by the SelectWidget’s
6340 * {@link OO.ui.SelectWidget#selectItem selectItem( [item] )} method instead of this method.
6342 * @param {boolean} [state=false] Select option
6344 * @return {OO.ui.Widget} The widget, for chaining
6346 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
6347 if ( this.constructor.static.selectable
) {
6348 this.selected
= !!state
;
6350 .toggleClass( 'oo-ui-optionWidget-selected', state
)
6351 .attr( 'aria-selected', state
.toString() );
6352 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
6353 this.scrollElementIntoView();
6355 this.updateThemeClasses();
6361 * Set the option’s highlighted state. In general, all programmatic
6362 * modifications to the highlight should be handled by the
6363 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
6364 * method instead of this method.
6366 * @param {boolean} [state=false] Highlight option
6368 * @return {OO.ui.Widget} The widget, for chaining
6370 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
6371 if ( this.constructor.static.highlightable
) {
6372 this.highlighted
= !!state
;
6373 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
6374 this.updateThemeClasses();
6380 * Set the option’s pressed state. In general, all
6381 * programmatic modifications to the pressed state should be handled by the
6382 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
6383 * method instead of this method.
6385 * @param {boolean} [state=false] Press option
6387 * @return {OO.ui.Widget} The widget, for chaining
6389 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
6390 if ( this.constructor.static.pressable
) {
6391 this.pressed
= !!state
;
6392 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
6393 this.updateThemeClasses();
6399 * Get text to match search strings against.
6401 * The default implementation returns the label text, but subclasses
6402 * can override this to provide more complex behavior.
6404 * @return {string|boolean} String to match search string against
6406 OO
.ui
.OptionWidget
.prototype.getMatchText = function () {
6407 var label
= this.getLabel();
6408 return typeof label
=== 'string' ? label
: this.$label
.text();
6412 * A SelectWidget is of a generic selection of options. The OOUI library contains several types of
6413 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
6414 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
6417 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For
6418 * more information, please see the [OOUI documentation on MediaWiki][1].
6421 * // A select widget with three options.
6422 * var select = new OO.ui.SelectWidget( {
6424 * new OO.ui.OptionWidget( {
6426 * label: 'Option One',
6428 * new OO.ui.OptionWidget( {
6430 * label: 'Option Two',
6432 * new OO.ui.OptionWidget( {
6434 * label: 'Option Three',
6438 * $( document.body ).append( select.$element );
6440 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6444 * @extends OO.ui.Widget
6445 * @mixins OO.ui.mixin.GroupWidget
6448 * @param {Object} [config] Configuration options
6449 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
6450 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
6451 * the [OOUI documentation on MediaWiki] [2] for examples.
6452 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6453 * @cfg {boolean} [multiselect] Allow for multiple selections
6455 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
6456 // Configuration initialization
6457 config
= config
|| {};
6459 // Parent constructor
6460 OO
.ui
.SelectWidget
.parent
.call( this, config
);
6462 // Mixin constructors
6463 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {
6464 $group
: this.$element
6468 this.pressed
= false;
6469 this.selecting
= null;
6470 this.multiselect
= !!config
.multiselect
;
6471 this.onDocumentMouseUpHandler
= this.onDocumentMouseUp
.bind( this );
6472 this.onDocumentMouseMoveHandler
= this.onDocumentMouseMove
.bind( this );
6473 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
6474 this.onDocumentKeyPressHandler
= this.onDocumentKeyPress
.bind( this );
6475 this.keyPressBuffer
= '';
6476 this.keyPressBufferTimer
= null;
6477 this.blockMouseOverEvents
= 0;
6480 this.connect( this, {
6484 focusin
: this.onFocus
.bind( this ),
6485 mousedown
: this.onMouseDown
.bind( this ),
6486 mouseover
: this.onMouseOver
.bind( this ),
6487 mouseleave
: this.onMouseLeave
.bind( this )
6492 // -depressed is a deprecated alias of -unpressed
6493 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-unpressed oo-ui-selectWidget-depressed' )
6494 .attr( 'role', 'listbox' );
6495 this.setFocusOwner( this.$element
);
6496 if ( Array
.isArray( config
.items
) ) {
6497 this.addItems( config
.items
);
6503 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
6504 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
6511 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
6513 * @param {OO.ui.OptionWidget|null} item Highlighted item
6519 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
6520 * pressed state of an option.
6522 * @param {OO.ui.OptionWidget|null} item Pressed item
6528 * A `select` event is emitted when the selection is modified programmatically with the #selectItem
6531 * @param {OO.ui.OptionWidget[]|OO.ui.OptionWidget|null} items Currently selected items
6537 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
6539 * @param {OO.ui.OptionWidget} item Chosen item
6540 * @param {boolean} selected Item is selected
6546 * An `add` event is emitted when options are added to the select with the #addItems method.
6548 * @param {OO.ui.OptionWidget[]} items Added items
6549 * @param {number} index Index of insertion point
6555 * A `remove` event is emitted when options are removed from the select with the #clearItems
6556 * or #removeItems methods.
6558 * @param {OO.ui.OptionWidget[]} items Removed items
6561 /* Static methods */
6564 * Normalize text for filter matching
6566 * @param {string} text Text
6567 * @return {string} Normalized text
6569 OO
.ui
.SelectWidget
.static.normalizeForMatching = function ( text
) {
6570 // Replace trailing whitespace, normalize multiple spaces and make case insensitive
6571 var normalized
= text
.trim().replace( /\s+/, ' ' ).toLowerCase();
6573 // Normalize Unicode
6574 // eslint-disable-next-line no-restricted-properties
6575 if ( normalized
.normalize
) {
6576 // eslint-disable-next-line no-restricted-properties
6577 normalized
= normalized
.normalize();
6585 * Handle focus events
6588 * @param {jQuery.Event} event
6590 OO
.ui
.SelectWidget
.prototype.onFocus = function ( event
) {
6592 if ( event
.target
=== this.$element
[ 0 ] ) {
6593 // This widget was focussed, e.g. by the user tabbing to it.
6594 // The styles for focus state depend on one of the items being selected.
6595 if ( !this.findSelectedItem() ) {
6596 item
= this.findFirstSelectableItem();
6599 if ( event
.target
.tabIndex
=== -1 ) {
6600 // One of the options got focussed (and the event bubbled up here).
6601 // They can't be tabbed to, but they can be activated using access keys.
6602 // OptionWidgets and focusable UI elements inside them have tabindex="-1" set.
6603 item
= this.findTargetItem( event
);
6605 // There is something actually user-focusable in one of the labels of the options, and
6606 // the user focussed it (e.g. by tabbing to it). Do nothing (especially, don't change
6613 if ( item
.constructor.static.highlightable
) {
6614 this.highlightItem( item
);
6616 this.selectItem( item
);
6620 if ( event
.target
!== this.$element
[ 0 ] ) {
6621 this.$focusOwner
.trigger( 'focus' );
6626 * Handle mouse down events.
6629 * @param {jQuery.Event} e Mouse down event
6630 * @return {undefined|boolean} False to prevent default if event is handled
6632 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
6635 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
6636 this.togglePressed( true );
6637 item
= this.findTargetItem( e
);
6638 if ( item
&& item
.isSelectable() ) {
6639 this.pressItem( item
);
6640 this.selecting
= item
;
6641 this.getElementDocument().addEventListener( 'mouseup', this.onDocumentMouseUpHandler
, true );
6642 this.getElementDocument().addEventListener( 'mousemove', this.onDocumentMouseMoveHandler
, true );
6649 * Handle document mouse up events.
6652 * @param {MouseEvent} e Mouse up event
6653 * @return {undefined|boolean} False to prevent default if event is handled
6655 OO
.ui
.SelectWidget
.prototype.onDocumentMouseUp = function ( e
) {
6658 this.togglePressed( false );
6659 if ( !this.selecting
) {
6660 item
= this.findTargetItem( e
);
6661 if ( item
&& item
.isSelectable() ) {
6662 this.selecting
= item
;
6665 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
&& this.selecting
) {
6666 this.pressItem( null );
6667 this.chooseItem( this.selecting
);
6668 this.selecting
= null;
6671 this.getElementDocument().removeEventListener( 'mouseup', this.onDocumentMouseUpHandler
, true );
6672 this.getElementDocument().removeEventListener( 'mousemove', this.onDocumentMouseMoveHandler
, true );
6678 * Handle document mouse move events.
6681 * @param {MouseEvent} e Mouse move event
6683 OO
.ui
.SelectWidget
.prototype.onDocumentMouseMove = function ( e
) {
6686 if ( !this.isDisabled() && this.pressed
) {
6687 item
= this.findTargetItem( e
);
6688 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
6689 this.pressItem( item
);
6690 this.selecting
= item
;
6696 * Handle mouse over events.
6699 * @param {jQuery.Event} e Mouse over event
6700 * @return {undefined|boolean} False to prevent default if event is handled
6702 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
6704 if ( this.blockMouseOverEvents
) {
6707 if ( !this.isDisabled() ) {
6708 item
= this.findTargetItem( e
);
6709 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
6715 * Handle mouse leave events.
6718 * @param {jQuery.Event} e Mouse over event
6719 * @return {undefined|boolean} False to prevent default if event is handled
6721 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
6722 if ( !this.isDisabled() ) {
6723 this.highlightItem( null );
6729 * Handle document key down events.
6732 * @param {KeyboardEvent} e Key down event
6734 OO
.ui
.SelectWidget
.prototype.onDocumentKeyDown = function ( e
) {
6737 currentItem
= this.findHighlightedItem(),
6738 firstItem
= this.getItems()[ 0 ];
6740 if ( !this.isDisabled() && this.isVisible() ) {
6741 switch ( e
.keyCode
) {
6742 case OO
.ui
.Keys
.ENTER
:
6743 if ( currentItem
) {
6744 // Was only highlighted, now let's select it. No-op if already selected.
6745 this.chooseItem( currentItem
);
6750 case OO
.ui
.Keys
.LEFT
:
6751 this.clearKeyPressBuffer();
6752 nextItem
= currentItem
?
6753 this.findRelativeSelectableItem( currentItem
, -1 ) : firstItem
;
6756 case OO
.ui
.Keys
.DOWN
:
6757 case OO
.ui
.Keys
.RIGHT
:
6758 this.clearKeyPressBuffer();
6759 nextItem
= currentItem
?
6760 this.findRelativeSelectableItem( currentItem
, 1 ) : firstItem
;
6763 case OO
.ui
.Keys
.ESCAPE
:
6764 case OO
.ui
.Keys
.TAB
:
6765 if ( currentItem
) {
6766 currentItem
.setHighlighted( false );
6768 this.unbindDocumentKeyDownListener();
6769 this.unbindDocumentKeyPressListener();
6770 // Don't prevent tabbing away / defocusing
6776 if ( nextItem
.constructor.static.highlightable
) {
6777 this.highlightItem( nextItem
);
6779 this.chooseItem( nextItem
);
6781 this.scrollItemIntoView( nextItem
);
6786 e
.stopPropagation();
6792 * Bind document key down listener.
6796 OO
.ui
.SelectWidget
.prototype.bindDocumentKeyDownListener = function () {
6797 this.getElementDocument().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
6801 * Unbind document key down listener.
6805 OO
.ui
.SelectWidget
.prototype.unbindDocumentKeyDownListener = function () {
6806 this.getElementDocument().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
6810 * Scroll item into view, preventing spurious mouse highlight actions from happening.
6812 * @param {OO.ui.OptionWidget} item Item to scroll into view
6814 OO
.ui
.SelectWidget
.prototype.scrollItemIntoView = function ( item
) {
6816 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic
6817 // scrolling and around 100-150 ms after it is finished.
6818 this.blockMouseOverEvents
++;
6819 item
.scrollElementIntoView().done( function () {
6820 setTimeout( function () {
6821 widget
.blockMouseOverEvents
--;
6827 * Clear the key-press buffer
6831 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
6832 if ( this.keyPressBufferTimer
) {
6833 clearTimeout( this.keyPressBufferTimer
);
6834 this.keyPressBufferTimer
= null;
6836 this.keyPressBuffer
= '';
6840 * Handle key press events.
6843 * @param {KeyboardEvent} e Key press event
6844 * @return {undefined|boolean} False to prevent default if event is handled
6846 OO
.ui
.SelectWidget
.prototype.onDocumentKeyPress = function ( e
) {
6847 var c
, filter
, item
;
6849 if ( !e
.charCode
) {
6850 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
6851 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
6856 // eslint-disable-next-line no-restricted-properties
6857 if ( String
.fromCodePoint
) {
6858 // eslint-disable-next-line no-restricted-properties
6859 c
= String
.fromCodePoint( e
.charCode
);
6861 c
= String
.fromCharCode( e
.charCode
);
6864 if ( this.keyPressBufferTimer
) {
6865 clearTimeout( this.keyPressBufferTimer
);
6867 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
6869 item
= this.findHighlightedItem() || this.findSelectedItem();
6871 if ( this.keyPressBuffer
=== c
) {
6872 // Common (if weird) special case: typing "xxxx" will cycle through all
6873 // the items beginning with "x".
6875 item
= this.findRelativeSelectableItem( item
, 1 );
6878 this.keyPressBuffer
+= c
;
6881 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
6882 if ( !item
|| !filter( item
) ) {
6883 item
= this.findRelativeSelectableItem( item
, 1, filter
);
6886 if ( this.isVisible() && item
.constructor.static.highlightable
) {
6887 this.highlightItem( item
);
6889 this.chooseItem( item
);
6891 this.scrollItemIntoView( item
);
6895 e
.stopPropagation();
6899 * Get a matcher for the specific string
6902 * @param {string} query String to match against items
6903 * @param {string} [mode='prefix'] Matching mode: 'substring', 'prefix', or 'exact'
6904 * @return {Function} function ( OO.ui.OptionWidget ) => boolean
6906 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( query
, mode
) {
6907 var normalizeForMatching
= this.constructor.static.normalizeForMatching
,
6908 normalizedQuery
= normalizeForMatching( query
);
6910 // Support deprecated exact=true argument
6911 if ( mode
=== true ) {
6915 return function ( item
) {
6916 var matchText
= normalizeForMatching( item
.getMatchText() );
6918 if ( normalizedQuery
=== '' ) {
6919 // Empty string matches all, except if we are in 'exact'
6920 // mode, where it doesn't match at all
6921 return mode
!== 'exact';
6926 return matchText
=== normalizedQuery
;
6928 return matchText
.indexOf( normalizedQuery
) !== -1;
6931 return matchText
.indexOf( normalizedQuery
) === 0;
6937 * Bind document key press listener.
6941 OO
.ui
.SelectWidget
.prototype.bindDocumentKeyPressListener = function () {
6942 this.getElementDocument().addEventListener( 'keypress', this.onDocumentKeyPressHandler
, true );
6946 * Unbind document key down listener.
6948 * If you override this, be sure to call this.clearKeyPressBuffer() from your
6953 OO
.ui
.SelectWidget
.prototype.unbindDocumentKeyPressListener = function () {
6954 this.getElementDocument().removeEventListener( 'keypress', this.onDocumentKeyPressHandler
, true );
6955 this.clearKeyPressBuffer();
6959 * Visibility change handler
6962 * @param {boolean} visible
6964 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
6966 this.clearKeyPressBuffer();
6971 * Get the closest item to a jQuery.Event.
6974 * @param {jQuery.Event} e
6975 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
6977 OO
.ui
.SelectWidget
.prototype.findTargetItem = function ( e
) {
6978 var $option
= $( e
.target
).closest( '.oo-ui-optionWidget' );
6979 if ( !$option
.closest( '.oo-ui-selectWidget' ).is( this.$element
) ) {
6982 return $option
.data( 'oo-ui-optionWidget' ) || null;
6986 * Find all selected items, if there are any. If the widget allows for multiselect
6987 * it will return an array of selected options. If the widget doesn't allow for
6988 * multiselect, it will return the selected option or null if no item is selected.
6990 * @return {OO.ui.OptionWidget[]|OO.ui.OptionWidget|null} If the widget is multiselect
6991 * then return an array of selected items (or empty array),
6992 * if the widget is not multiselect, return a single selected item, or `null`
6993 * if no item is selected
6995 OO
.ui
.SelectWidget
.prototype.findSelectedItems = function () {
6996 var selected
= this.items
.filter( function ( item
) {
6997 return item
.isSelected();
7000 return this.multiselect
?
7002 selected
[ 0 ] || null;
7006 * Find selected item.
7008 * @return {OO.ui.OptionWidget[]|OO.ui.OptionWidget|null} If the widget is multiselect
7009 * then return an array of selected items (or empty array),
7010 * if the widget is not multiselect, return a single selected item, or `null`
7011 * if no item is selected
7013 OO
.ui
.SelectWidget
.prototype.findSelectedItem = function () {
7014 return this.findSelectedItems();
7018 * Find highlighted item.
7020 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
7022 OO
.ui
.SelectWidget
.prototype.findHighlightedItem = function () {
7025 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
7026 if ( this.items
[ i
].isHighlighted() ) {
7027 return this.items
[ i
];
7034 * Toggle pressed state.
7036 * Press is a state that occurs when a user mouses down on an item, but
7037 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
7038 * until the user releases the mouse.
7040 * @param {boolean} pressed An option is being pressed
7042 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
7043 if ( pressed
=== undefined ) {
7044 pressed
= !this.pressed
;
7046 if ( pressed
!== this.pressed
) {
7048 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
7049 // -depressed is a deprecated alias of -unpressed
7050 .toggleClass( 'oo-ui-selectWidget-unpressed oo-ui-selectWidget-depressed', !pressed
);
7051 this.pressed
= pressed
;
7056 * Highlight an option. If the `item` param is omitted, no options will be highlighted
7057 * and any existing highlight will be removed. The highlight is mutually exclusive.
7059 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
7062 * @return {OO.ui.Widget} The widget, for chaining
7064 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
7065 var i
, len
, highlighted
,
7068 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
7069 highlighted
= this.items
[ i
] === item
;
7070 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
7071 this.items
[ i
].setHighlighted( highlighted
);
7077 this.$focusOwner
.attr( 'aria-activedescendant', item
.getElementId() );
7079 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
7081 this.emit( 'highlight', item
);
7088 * Fetch an item by its label.
7090 * @param {string} label Label of the item to select.
7091 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
7092 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
7094 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
7096 len
= this.items
.length
,
7097 filter
= this.getItemMatcher( label
, 'exact' );
7099 for ( i
= 0; i
< len
; i
++ ) {
7100 item
= this.items
[ i
];
7101 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
7108 filter
= this.getItemMatcher( label
, 'prefix' );
7109 for ( i
= 0; i
< len
; i
++ ) {
7110 item
= this.items
[ i
];
7111 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
7127 * Programmatically select an option by its label. If the item does not exist,
7128 * all options will be deselected.
7130 * @param {string} [label] Label of the item to select.
7131 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
7134 * @return {OO.ui.Widget} The widget, for chaining
7136 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
7137 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
7138 if ( label
=== undefined || !itemFromLabel
) {
7139 return this.selectItem();
7141 return this.selectItem( itemFromLabel
);
7145 * Programmatically select an option by its data. If the `data` parameter is omitted,
7146 * or if the item does not exist, all options will be deselected.
7148 * @param {Object|string} [data] Value of the item to select, omit to deselect all
7151 * @return {OO.ui.Widget} The widget, for chaining
7153 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
7154 var itemFromData
= this.findItemFromData( data
);
7155 if ( data
=== undefined || !itemFromData
) {
7156 return this.selectItem();
7158 return this.selectItem( itemFromData
);
7162 * Programmatically unselect an option by its reference. If the widget
7163 * allows for multiple selections, there may be other items still selected;
7164 * otherwise, no items will be selected.
7165 * If no item is given, all selected items will be unselected.
7167 * @param {OO.ui.OptionWidget} [item] Item to unselect
7170 * @return {OO.ui.Widget} The widget, for chaining
7172 OO
.ui
.SelectWidget
.prototype.unselectItem = function ( item
) {
7174 item
.setSelected( false );
7176 this.items
.forEach( function ( item
) {
7177 item
.setSelected( false );
7181 this.emit( 'select', this.findSelectedItems() );
7186 * Programmatically select an option by its reference. If the `item` parameter is omitted,
7187 * all options will be deselected.
7189 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
7192 * @return {OO.ui.Widget} The widget, for chaining
7194 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
7195 var i
, len
, selected
,
7198 if ( this.multiselect
&& item
) {
7199 // Select the item directly
7200 item
.setSelected( true );
7202 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
7203 selected
= this.items
[ i
] === item
;
7204 if ( this.items
[ i
].isSelected() !== selected
) {
7205 this.items
[ i
].setSelected( selected
);
7211 // TODO: When should a non-highlightable element be selected?
7212 if ( item
&& !item
.constructor.static.highlightable
) {
7214 this.$focusOwner
.attr( 'aria-activedescendant', item
.getElementId() );
7216 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
7219 this.emit( 'select', this.findSelectedItems() );
7228 * Press is a state that occurs when a user mouses down on an item, but has not
7229 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
7230 * releases the mouse.
7232 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
7235 * @return {OO.ui.Widget} The widget, for chaining
7237 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
7238 var i
, len
, pressed
,
7241 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
7242 pressed
= this.items
[ i
] === item
;
7243 if ( this.items
[ i
].isPressed() !== pressed
) {
7244 this.items
[ i
].setPressed( pressed
);
7249 this.emit( 'press', item
);
7258 * Note that ‘choose’ should never be modified programmatically. A user can choose
7259 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
7260 * use the #selectItem method.
7262 * This method is identical to #selectItem, but may vary in subclasses that take additional action
7263 * when users choose an item with the keyboard or mouse.
7265 * @param {OO.ui.OptionWidget} item Item to choose
7268 * @return {OO.ui.Widget} The widget, for chaining
7270 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
7272 if ( this.multiselect
&& item
.isSelected() ) {
7273 this.unselectItem( item
);
7275 this.selectItem( item
);
7278 this.emit( 'choose', item
, item
.isSelected() );
7285 * Find an option by its position relative to the specified item (or to the start of the option
7286 * array, if item is `null`). The direction in which to search through the option array is specified
7287 * with a number: -1 for reverse (the default) or 1 for forward. The method will return an option,
7288 * or `null` if there are no options in the array.
7290 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at
7291 * the beginning of the array.
7292 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
7293 * @param {Function} [filter] Only consider items for which this function returns
7294 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
7295 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
7297 OO
.ui
.SelectWidget
.prototype.findRelativeSelectableItem = function ( item
, direction
, filter
) {
7298 var currentIndex
, nextIndex
, i
,
7299 increase
= direction
> 0 ? 1 : -1,
7300 len
= this.items
.length
;
7302 if ( item
instanceof OO
.ui
.OptionWidget
) {
7303 currentIndex
= this.items
.indexOf( item
);
7304 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
7306 // If no item is selected and moving forward, start at the beginning.
7307 // If moving backward, start at the end.
7308 nextIndex
= direction
> 0 ? 0 : len
- 1;
7311 for ( i
= 0; i
< len
; i
++ ) {
7312 item
= this.items
[ nextIndex
];
7314 item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() &&
7315 ( !filter
|| filter( item
) )
7319 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
7325 * Find the next selectable item or `null` if there are no selectable items.
7326 * Disabled options and menu-section markers and breaks are not selectable.
7328 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
7330 OO
.ui
.SelectWidget
.prototype.findFirstSelectableItem = function () {
7331 return this.findRelativeSelectableItem( null, 1 );
7335 * Add an array of options to the select. Optionally, an index number can be used to
7336 * specify an insertion point.
7338 * @param {OO.ui.OptionWidget[]} items Items to add
7339 * @param {number} [index] Index to insert items after
7342 * @return {OO.ui.Widget} The widget, for chaining
7344 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
7346 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
7348 // Always provide an index, even if it was omitted
7349 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
7355 * Remove the specified array of options from the select. Options will be detached
7356 * from the DOM, not removed, so they can be reused later. To remove all options from
7357 * the select, you may wish to use the #clearItems method instead.
7359 * @param {OO.ui.OptionWidget[]} items Items to remove
7362 * @return {OO.ui.Widget} The widget, for chaining
7364 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
7367 // Deselect items being removed
7368 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
7370 if ( item
.isSelected() ) {
7371 this.selectItem( null );
7376 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
7378 this.emit( 'remove', items
);
7384 * Clear all options from the select. Options will be detached from the DOM, not removed,
7385 * so that they can be reused later. To remove a subset of options from the select, use
7386 * the #removeItems method.
7390 * @return {OO.ui.Widget} The widget, for chaining
7392 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
7393 var items
= this.items
.slice();
7396 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
7399 this.selectItem( null );
7401 this.emit( 'remove', items
);
7407 * Set the DOM element which has focus while the user is interacting with this SelectWidget.
7409 * This is used to set `aria-activedescendant` and `aria-expanded` on it.
7412 * @param {jQuery} $focusOwner
7414 OO
.ui
.SelectWidget
.prototype.setFocusOwner = function ( $focusOwner
) {
7415 this.$focusOwner
= $focusOwner
;
7419 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
7420 * with an {@link OO.ui.mixin.IconElement icon} and/or
7421 * {@link OO.ui.mixin.IndicatorElement indicator}.
7422 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
7423 * options. For more information about options and selects, please see the
7424 * [OOUI documentation on MediaWiki][1].
7427 * // Decorated options in a select widget.
7428 * var select = new OO.ui.SelectWidget( {
7430 * new OO.ui.DecoratedOptionWidget( {
7432 * label: 'Option with icon',
7435 * new OO.ui.DecoratedOptionWidget( {
7437 * label: 'Option with indicator',
7442 * $( document.body ).append( select.$element );
7444 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7447 * @extends OO.ui.OptionWidget
7448 * @mixins OO.ui.mixin.IconElement
7449 * @mixins OO.ui.mixin.IndicatorElement
7452 * @param {Object} [config] Configuration options
7454 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
7455 // Parent constructor
7456 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
7458 // Mixin constructors
7459 OO
.ui
.mixin
.IconElement
.call( this, config
);
7460 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
7464 .addClass( 'oo-ui-decoratedOptionWidget' )
7465 .prepend( this.$icon
)
7466 .append( this.$indicator
);
7471 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
7472 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
7473 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
7476 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
7477 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
7478 * the [OOUI documentation on MediaWiki] [1] for more information.
7480 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
7483 * @extends OO.ui.DecoratedOptionWidget
7486 * @param {Object} [config] Configuration options
7488 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
7489 // Parent constructor
7490 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
7493 this.checkIcon
= new OO
.ui
.IconWidget( {
7495 classes
: [ 'oo-ui-menuOptionWidget-checkIcon' ]
7500 .prepend( this.checkIcon
.$element
)
7501 .addClass( 'oo-ui-menuOptionWidget' );
7506 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
7508 /* Static Properties */
7514 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
7517 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to
7518 * group one or more related {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets
7519 * cannot be highlighted or selected.
7522 * var dropdown = new OO.ui.DropdownWidget( {
7525 * new OO.ui.MenuSectionOptionWidget( {
7528 * new OO.ui.MenuOptionWidget( {
7530 * label: 'Welsh Corgi'
7532 * new OO.ui.MenuOptionWidget( {
7534 * label: 'Standard Poodle'
7536 * new OO.ui.MenuSectionOptionWidget( {
7539 * new OO.ui.MenuOptionWidget( {
7546 * $( document.body ).append( dropdown.$element );
7549 * @extends OO.ui.DecoratedOptionWidget
7552 * @param {Object} [config] Configuration options
7554 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
7555 // Parent constructor
7556 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
7560 .addClass( 'oo-ui-menuSectionOptionWidget' )
7561 .removeAttr( 'role aria-selected' );
7562 this.selected
= false;
7567 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
7569 /* Static Properties */
7575 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
7581 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
7584 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
7585 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
7586 * See {@link OO.ui.DropdownWidget DropdownWidget},
7587 * {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}, and
7588 * {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
7589 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
7590 * and customized to be opened, closed, and displayed as needed.
7592 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
7593 * mouse outside the menu.
7595 * Menus also have support for keyboard interaction:
7597 * - Enter/Return key: choose and select a menu option
7598 * - Up-arrow key: highlight the previous menu option
7599 * - Down-arrow key: highlight the next menu option
7600 * - Escape key: hide the menu
7602 * Unlike most widgets, MenuSelectWidget is initially hidden and must be shown by calling #toggle.
7604 * Please see the [OOUI documentation on MediaWiki][1] for more information.
7605 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7608 * @extends OO.ui.SelectWidget
7609 * @mixins OO.ui.mixin.ClippableElement
7610 * @mixins OO.ui.mixin.FloatableElement
7613 * @param {Object} [config] Configuration options
7614 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu
7615 * items that match the text the user types. This config is used by
7616 * {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget} and
7617 * {@link OO.ui.mixin.LookupElement LookupElement}
7618 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
7619 * the text the user types. This config is used by
7620 * {@link OO.ui.TagMultiselectWidget TagMultiselectWidget}
7621 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks
7622 * the mouse anywhere on the page outside of this widget, the menu is hidden. For example, if
7623 * there is a button that toggles the menu's visibility on click, the menu will be hidden then
7624 * re-shown when the user clicks that button, unless the button (or its parent widget) is passed
7626 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
7627 * @cfg {jQuery} [$autoCloseIgnore] If these elements are clicked, don't auto-hide the menu.
7628 * @cfg {boolean} [hideOnChoose=true] Hide the menu when the user chooses an option.
7629 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
7630 * @cfg {boolean} [highlightOnFilter] Highlight the first result when filtering
7631 * @cfg {string} [filterMode='prefix'] The mode by which the menu filters the results.
7632 * Options are 'exact', 'prefix' or 'substring'. See `OO.ui.SelectWidget#getItemMatcher`
7633 * @param {number|string} [width] Width of the menu as a number of pixels or CSS string with unit
7634 * suffix, used by {@link OO.ui.mixin.ClippableElement ClippableElement}
7636 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
7637 // Configuration initialization
7638 config
= config
|| {};
7640 // Parent constructor
7641 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
7643 // Mixin constructors
7644 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( { $clippable
: this.$group
}, config
) );
7645 OO
.ui
.mixin
.FloatableElement
.call( this, config
);
7647 // Initial vertical positions other than 'center' will result in
7648 // the menu being flipped if there is not enough space in the container.
7649 // Store the original position so we know what to reset to.
7650 this.originalVerticalPosition
= this.verticalPosition
;
7653 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
7654 this.hideOnChoose
= config
.hideOnChoose
=== undefined || !!config
.hideOnChoose
;
7655 this.filterFromInput
= !!config
.filterFromInput
;
7656 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
7657 this.$widget
= config
.widget
? config
.widget
.$element
: null;
7658 this.$autoCloseIgnore
= config
.$autoCloseIgnore
|| $( [] );
7659 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
7660 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
7661 this.highlightOnFilter
= !!config
.highlightOnFilter
;
7662 this.lastHighlightedItem
= null;
7663 this.width
= config
.width
;
7664 this.filterMode
= config
.filterMode
;
7667 this.$element
.addClass( 'oo-ui-menuSelectWidget' );
7668 if ( config
.widget
) {
7669 this.setFocusOwner( config
.widget
.$tabIndexed
);
7672 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
7673 // that reference properties not initialized at that time of parent class construction
7674 // TODO: Find a better way to handle post-constructor setup
7675 this.visible
= false;
7676 this.$element
.addClass( 'oo-ui-element-hidden' );
7677 this.$focusOwner
.attr( 'aria-expanded', 'false' );
7682 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
7683 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
7684 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.FloatableElement
);
7691 * The menu is ready: it is visible and has been positioned and clipped.
7694 /* Static properties */
7697 * Positions to flip to if there isn't room in the container for the
7698 * menu in a specific direction.
7700 * @property {Object.<string,string>}
7702 OO
.ui
.MenuSelectWidget
.static.flippedPositions
= {
7712 * Handles document mouse down events.
7715 * @param {MouseEvent} e Mouse down event
7717 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
7721 this.$element
.add( this.$widget
).add( this.$autoCloseIgnore
).get(),
7726 this.toggle( false );
7733 OO
.ui
.MenuSelectWidget
.prototype.onDocumentKeyDown = function ( e
) {
7734 var currentItem
= this.findHighlightedItem() || this.findSelectedItem();
7736 if ( !this.isDisabled() && this.isVisible() ) {
7737 switch ( e
.keyCode
) {
7738 case OO
.ui
.Keys
.LEFT
:
7739 case OO
.ui
.Keys
.RIGHT
:
7740 // Do nothing if a text field is associated, arrow keys will be handled natively
7741 if ( !this.$input
) {
7742 OO
.ui
.MenuSelectWidget
.parent
.prototype.onDocumentKeyDown
.call( this, e
);
7745 case OO
.ui
.Keys
.ESCAPE
:
7746 case OO
.ui
.Keys
.TAB
:
7747 if ( currentItem
&& !this.multiselect
) {
7748 currentItem
.setHighlighted( false );
7750 this.toggle( false );
7751 // Don't prevent tabbing away, prevent defocusing
7752 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
7754 e
.stopPropagation();
7758 OO
.ui
.MenuSelectWidget
.parent
.prototype.onDocumentKeyDown
.call( this, e
);
7765 * Update menu item visibility and clipping after input changes (if filterFromInput is enabled)
7766 * or after items were added/removed (always).
7770 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
7771 var i
, item
, items
, visible
, section
, sectionEmpty
, filter
, exactFilter
,
7773 len
= this.items
.length
,
7774 showAll
= !this.isVisible(),
7777 if ( this.$input
&& this.filterFromInput
) {
7778 filter
= showAll
? null : this.getItemMatcher( this.$input
.val(), this.filterMode
);
7779 exactFilter
= this.getItemMatcher( this.$input
.val(), 'exact' );
7780 // Hide non-matching options, and also hide section headers if all options
7781 // in their section are hidden.
7782 for ( i
= 0; i
< len
; i
++ ) {
7783 item
= this.items
[ i
];
7784 if ( item
instanceof OO
.ui
.MenuSectionOptionWidget
) {
7786 // If the previous section was empty, hide its header
7787 section
.toggle( showAll
|| !sectionEmpty
);
7790 sectionEmpty
= true;
7791 } else if ( item
instanceof OO
.ui
.OptionWidget
) {
7792 visible
= showAll
|| filter( item
);
7793 exactMatch
= exactMatch
|| exactFilter( item
);
7794 anyVisible
= anyVisible
|| visible
;
7795 sectionEmpty
= sectionEmpty
&& !visible
;
7796 item
.toggle( visible
);
7799 // Process the final section
7801 section
.toggle( showAll
|| !sectionEmpty
);
7804 if ( !anyVisible
) {
7805 this.highlightItem( null );
7808 this.$element
.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible
);
7811 this.highlightOnFilter
&&
7812 !( this.lastHighlightedItem
&& this.lastHighlightedItem
.isVisible() )
7814 // Highlight the first item on the list
7816 items
= this.getItems();
7817 for ( i
= 0; i
< items
.length
; i
++ ) {
7818 if ( items
[ i
].isVisible() ) {
7823 this.highlightItem( item
);
7824 this.lastHighlightedItem
= item
;
7829 // Reevaluate clipping
7836 OO
.ui
.MenuSelectWidget
.prototype.bindDocumentKeyDownListener = function () {
7837 if ( this.$input
) {
7838 this.$input
.on( 'keydown', this.onDocumentKeyDownHandler
);
7840 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindDocumentKeyDownListener
.call( this );
7847 OO
.ui
.MenuSelectWidget
.prototype.unbindDocumentKeyDownListener = function () {
7848 if ( this.$input
) {
7849 this.$input
.off( 'keydown', this.onDocumentKeyDownHandler
);
7851 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindDocumentKeyDownListener
.call( this );
7858 OO
.ui
.MenuSelectWidget
.prototype.bindDocumentKeyPressListener = function () {
7859 if ( this.$input
) {
7860 if ( this.filterFromInput
) {
7862 'keydown mouseup cut paste change input select',
7863 this.onInputEditHandler
7865 this.updateItemVisibility();
7868 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindDocumentKeyPressListener
.call( this );
7875 OO
.ui
.MenuSelectWidget
.prototype.unbindDocumentKeyPressListener = function () {
7876 if ( this.$input
) {
7877 if ( this.filterFromInput
) {
7879 'keydown mouseup cut paste change input select',
7880 this.onInputEditHandler
7882 this.updateItemVisibility();
7885 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindDocumentKeyPressListener
.call( this );
7892 * When a user chooses an item, the menu is closed, unless the hideOnChoose config option is
7895 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with
7896 * the keyboard or mouse and it becomes selected. To select an item programmatically,
7897 * use the #selectItem method.
7899 * @param {OO.ui.OptionWidget} item Item to choose
7901 * @return {OO.ui.Widget} The widget, for chaining
7903 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
7904 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
7905 if ( this.hideOnChoose
) {
7906 this.toggle( false );
7914 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
7916 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
7918 this.updateItemVisibility();
7926 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
7928 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
7930 this.updateItemVisibility();
7938 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
7940 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
7942 this.updateItemVisibility();
7948 * Toggle visibility of the menu. The menu is initially hidden and must be shown by calling
7949 * `.toggle( true )` after its #$element is attached to the DOM.
7951 * Do not show the menu while it is not attached to the DOM. The calculations required to display
7952 * it in the right place and with the right dimensions only work correctly while it is attached.
7953 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
7954 * strictly enforced, so currently it only generates a warning in the browser console.
7959 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
7960 var change
, originalHeight
, flippedHeight
, selectedItem
;
7962 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
7963 change
= visible
!== this.isVisible();
7965 if ( visible
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
7966 OO
.ui
.warnDeprecation( 'MenuSelectWidget#toggle: Before calling this method, the menu must be attached to the DOM.' );
7967 this.warnedUnattached
= true;
7970 if ( change
&& visible
) {
7971 // Reset position before showing the popup again. It's possible we no longer need to flip
7972 // (e.g. if the user scrolled).
7973 this.setVerticalPosition( this.originalVerticalPosition
);
7977 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
7983 this.setIdealSize( this.width
);
7984 } else if ( this.$floatableContainer
) {
7985 this.$clippable
.css( 'width', 'auto' );
7987 this.$floatableContainer
[ 0 ].offsetWidth
> this.$clippable
[ 0 ].offsetWidth
?
7988 // Dropdown is smaller than handle so expand to width
7989 this.$floatableContainer
[ 0 ].offsetWidth
:
7990 // Dropdown is larger than handle so auto size
7993 this.$clippable
.css( 'width', '' );
7996 this.togglePositioning( !!this.$floatableContainer
);
7997 this.toggleClipping( true );
7999 this.bindDocumentKeyDownListener();
8000 this.bindDocumentKeyPressListener();
8003 ( this.isClippedVertically() || this.isFloatableOutOfView() ) &&
8004 this.originalVerticalPosition
!== 'center'
8006 // If opening the menu in one direction causes it to be clipped, flip it
8007 originalHeight
= this.$element
.height();
8008 this.setVerticalPosition(
8009 this.constructor.static.flippedPositions
[ this.originalVerticalPosition
]
8011 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
8012 // If flipping also causes it to be clipped, open in whichever direction
8013 // we have more space
8014 flippedHeight
= this.$element
.height();
8015 if ( originalHeight
> flippedHeight
) {
8016 this.setVerticalPosition( this.originalVerticalPosition
);
8020 // Note that we do not flip the menu's opening direction if the clipping changes
8021 // later (e.g. after the user scrolls), that seems like it would be annoying
8023 this.$focusOwner
.attr( 'aria-expanded', 'true' );
8025 selectedItem
= this.findSelectedItem();
8026 if ( !this.multiselect
&& selectedItem
) {
8027 // TODO: Verify if this is even needed; This is already done on highlight changes
8028 // in SelectWidget#highlightItem, so we should just need to highlight the item
8029 // we need to highlight here and not bother with attr or checking selections.
8030 this.$focusOwner
.attr( 'aria-activedescendant', selectedItem
.getElementId() );
8031 selectedItem
.scrollElementIntoView( { duration
: 0 } );
8035 if ( this.autoHide
) {
8036 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
8039 this.emit( 'ready' );
8041 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
8042 this.unbindDocumentKeyDownListener();
8043 this.unbindDocumentKeyPressListener();
8044 this.$focusOwner
.attr( 'aria-expanded', 'false' );
8045 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
8046 this.togglePositioning( false );
8047 this.toggleClipping( false );
8048 this.lastHighlightedItem
= null;
8056 * Scroll to the top of the menu
8058 OO
.ui
.MenuSelectWidget
.prototype.scrollToTop = function () {
8059 this.$element
.scrollTop( 0 );
8063 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
8064 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
8065 * users can interact with it.
8067 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8068 * OO.ui.DropdownInputWidget instead.
8071 * // A DropdownWidget with a menu that contains three options.
8072 * var dropDown = new OO.ui.DropdownWidget( {
8073 * label: 'Dropdown menu: Select a menu option',
8076 * new OO.ui.MenuOptionWidget( {
8080 * new OO.ui.MenuOptionWidget( {
8084 * new OO.ui.MenuOptionWidget( {
8092 * $( document.body ).append( dropDown.$element );
8094 * dropDown.getMenu().selectItemByData( 'b' );
8096 * dropDown.getMenu().findSelectedItem().getData(); // Returns 'b'.
8098 * For more information, please see the [OOUI documentation on MediaWiki] [1].
8100 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
8103 * @extends OO.ui.Widget
8104 * @mixins OO.ui.mixin.IconElement
8105 * @mixins OO.ui.mixin.IndicatorElement
8106 * @mixins OO.ui.mixin.LabelElement
8107 * @mixins OO.ui.mixin.TitledElement
8108 * @mixins OO.ui.mixin.TabIndexedElement
8111 * @param {Object} [config] Configuration options
8112 * @cfg {Object} [menu] Configuration options to pass to
8113 * {@link OO.ui.MenuSelectWidget menu select widget}.
8114 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful
8115 * in cases where the expanded menu is larger than its containing `<div>`. The specified overlay
8116 * layer is usually on top of the containing `<div>` and has a larger area. By default, the menu
8117 * uses relative positioning.
8118 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
8120 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
8121 // Configuration initialization
8122 config
= $.extend( { indicator
: 'down' }, config
);
8124 // Parent constructor
8125 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
8127 // Properties (must be set before TabIndexedElement constructor call)
8128 this.$handle
= $( '<button>' );
8129 this.$overlay
= ( config
.$overlay
=== true ?
8130 OO
.ui
.getDefaultOverlay() : config
.$overlay
) || this.$element
;
8132 // Mixin constructors
8133 OO
.ui
.mixin
.IconElement
.call( this, config
);
8134 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
8135 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8136 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {
8137 $titled
: this.$label
8139 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {
8140 $tabIndexed
: this.$handle
8144 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend( {
8146 $floatableContainer
: this.$element
8151 click
: this.onClick
.bind( this ),
8152 keydown
: this.onKeyDown
.bind( this ),
8153 // Hack? Handle type-to-search when menu is not expanded and not handling its own events.
8154 keypress
: this.menu
.onDocumentKeyPressHandler
,
8155 blur
: this.menu
.clearKeyPressBuffer
.bind( this.menu
)
8157 this.menu
.connect( this, {
8158 select
: 'onMenuSelect',
8159 toggle
: 'onMenuToggle'
8164 .addClass( 'oo-ui-dropdownWidget-handle' )
8167 'aria-owns': this.menu
.getElementId(),
8168 'aria-haspopup': 'listbox'
8170 .append( this.$icon
, this.$label
, this.$indicator
);
8172 .addClass( 'oo-ui-dropdownWidget' )
8173 .append( this.$handle
);
8174 this.$overlay
.append( this.menu
.$element
);
8179 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
8180 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
8181 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
8182 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
8183 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
8184 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
8191 * @return {OO.ui.MenuSelectWidget} Menu of widget
8193 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
8198 * Handles menu select events.
8201 * @param {OO.ui.MenuOptionWidget} item Selected menu item
8203 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
8207 this.setLabel( null );
8211 selectedLabel
= item
.getLabel();
8213 // If the label is a DOM element, clone it, because setLabel will append() it
8214 if ( selectedLabel
instanceof $ ) {
8215 selectedLabel
= selectedLabel
.clone();
8218 this.setLabel( selectedLabel
);
8222 * Handle menu toggle events.
8225 * @param {boolean} isVisible Open state of the menu
8227 OO
.ui
.DropdownWidget
.prototype.onMenuToggle = function ( isVisible
) {
8228 this.$element
.toggleClass( 'oo-ui-dropdownWidget-open', isVisible
);
8232 * Handle mouse click events.
8235 * @param {jQuery.Event} e Mouse click event
8236 * @return {undefined|boolean} False to prevent default if event is handled
8238 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
8239 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
8246 * Handle key down events.
8249 * @param {jQuery.Event} e Key down event
8250 * @return {undefined|boolean} False to prevent default if event is handled
8252 OO
.ui
.DropdownWidget
.prototype.onKeyDown = function ( e
) {
8254 !this.isDisabled() &&
8256 e
.which
=== OO
.ui
.Keys
.ENTER
||
8258 e
.which
=== OO
.ui
.Keys
.SPACE
&&
8259 // Avoid conflicts with type-to-search, see SelectWidget#onKeyPress.
8260 // Space only closes the menu is the user is not typing to search.
8261 this.menu
.keyPressBuffer
=== ''
8264 !this.menu
.isVisible() &&
8266 e
.which
=== OO
.ui
.Keys
.UP
||
8267 e
.which
=== OO
.ui
.Keys
.DOWN
8278 * RadioOptionWidget is an option widget that looks like a radio button.
8279 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
8280 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8282 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8285 * @extends OO.ui.OptionWidget
8288 * @param {Object} [config] Configuration options
8290 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
8291 // Configuration initialization
8292 config
= config
|| {};
8294 // Properties (must be done before parent constructor which calls #setDisabled)
8295 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
8297 // Parent constructor
8298 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
8301 // Remove implicit role, we're handling it ourselves
8302 this.radio
.$input
.attr( 'role', 'presentation' );
8304 .addClass( 'oo-ui-radioOptionWidget' )
8305 .attr( 'role', 'radio' )
8306 .attr( 'aria-checked', 'false' )
8307 .removeAttr( 'aria-selected' )
8308 .prepend( this.radio
.$element
);
8313 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
8315 /* Static Properties */
8321 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
8327 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
8333 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
8339 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
8346 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
8347 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
8349 this.radio
.setSelected( state
);
8351 .attr( 'aria-checked', state
.toString() )
8352 .removeAttr( 'aria-selected' );
8360 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
8361 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
8363 this.radio
.setDisabled( this.isDisabled() );
8369 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
8370 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
8371 * an interface for adding, removing and selecting options.
8372 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8374 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8375 * OO.ui.RadioSelectInputWidget instead.
8378 * // A RadioSelectWidget with RadioOptions.
8379 * var option1 = new OO.ui.RadioOptionWidget( {
8381 * label: 'Selected radio option'
8383 * option2 = new OO.ui.RadioOptionWidget( {
8385 * label: 'Unselected radio option'
8387 * radioSelect = new OO.ui.RadioSelectWidget( {
8388 * items: [ option1, option2 ]
8391 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
8392 * radioSelect.selectItem( option1 );
8394 * $( document.body ).append( radioSelect.$element );
8396 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8400 * @extends OO.ui.SelectWidget
8401 * @mixins OO.ui.mixin.TabIndexedElement
8404 * @param {Object} [config] Configuration options
8406 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
8407 // Parent constructor
8408 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
8410 // Mixin constructors
8411 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
8415 focus
: this.bindDocumentKeyDownListener
.bind( this ),
8416 blur
: this.unbindDocumentKeyDownListener
.bind( this )
8421 .addClass( 'oo-ui-radioSelectWidget' )
8422 .attr( 'role', 'radiogroup' );
8427 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
8428 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
8431 * MultioptionWidgets are special elements that can be selected and configured with data. The
8432 * data is often unique for each option, but it does not have to be. MultioptionWidgets are used
8433 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
8434 * and examples, please see the [OOUI documentation on MediaWiki][1].
8436 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8439 * @extends OO.ui.Widget
8440 * @mixins OO.ui.mixin.ItemWidget
8441 * @mixins OO.ui.mixin.LabelElement
8442 * @mixins OO.ui.mixin.TitledElement
8445 * @param {Object} [config] Configuration options
8446 * @cfg {boolean} [selected=false] Whether the option is initially selected
8448 OO
.ui
.MultioptionWidget
= function OoUiMultioptionWidget( config
) {
8449 // Configuration initialization
8450 config
= config
|| {};
8452 // Parent constructor
8453 OO
.ui
.MultioptionWidget
.parent
.call( this, config
);
8455 // Mixin constructors
8456 OO
.ui
.mixin
.ItemWidget
.call( this );
8457 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8458 OO
.ui
.mixin
.TitledElement
.call( this, config
);
8461 this.selected
= null;
8465 .addClass( 'oo-ui-multioptionWidget' )
8466 .append( this.$label
);
8467 this.setSelected( config
.selected
);
8472 OO
.inheritClass( OO
.ui
.MultioptionWidget
, OO
.ui
.Widget
);
8473 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.ItemWidget
);
8474 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.LabelElement
);
8475 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.TitledElement
);
8482 * A change event is emitted when the selected state of the option changes.
8484 * @param {boolean} selected Whether the option is now selected
8490 * Check if the option is selected.
8492 * @return {boolean} Item is selected
8494 OO
.ui
.MultioptionWidget
.prototype.isSelected = function () {
8495 return this.selected
;
8499 * Set the option’s selected state. In general, all modifications to the selection
8500 * should be handled by the SelectWidget’s
8501 * {@link OO.ui.SelectWidget#selectItem selectItem( [item] )} method instead of this method.
8503 * @param {boolean} [state=false] Select option
8505 * @return {OO.ui.Widget} The widget, for chaining
8507 OO
.ui
.MultioptionWidget
.prototype.setSelected = function ( state
) {
8509 if ( this.selected
!== state
) {
8510 this.selected
= state
;
8511 this.emit( 'change', state
);
8512 this.$element
.toggleClass( 'oo-ui-multioptionWidget-selected', state
);
8518 * MultiselectWidget allows selecting multiple options from a list.
8520 * For more information about menus and options, please see the [OOUI documentation
8523 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
8527 * @extends OO.ui.Widget
8528 * @mixins OO.ui.mixin.GroupWidget
8529 * @mixins OO.ui.mixin.TitledElement
8532 * @param {Object} [config] Configuration options
8533 * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
8535 OO
.ui
.MultiselectWidget
= function OoUiMultiselectWidget( config
) {
8536 // Parent constructor
8537 OO
.ui
.MultiselectWidget
.parent
.call( this, config
);
8539 // Configuration initialization
8540 config
= config
|| {};
8542 // Mixin constructors
8543 OO
.ui
.mixin
.GroupWidget
.call( this, config
);
8544 OO
.ui
.mixin
.TitledElement
.call( this, config
);
8550 // This is mostly for compatibility with TagMultiselectWidget... normally, 'change' is emitted
8551 // by GroupElement only when items are added/removed
8552 this.connect( this, {
8553 select
: [ 'emit', 'change' ]
8557 if ( config
.items
) {
8558 this.addItems( config
.items
);
8560 this.$group
.addClass( 'oo-ui-multiselectWidget-group' );
8561 this.$element
.addClass( 'oo-ui-multiselectWidget' )
8562 .append( this.$group
);
8567 OO
.inheritClass( OO
.ui
.MultiselectWidget
, OO
.ui
.Widget
);
8568 OO
.mixinClass( OO
.ui
.MultiselectWidget
, OO
.ui
.mixin
.GroupWidget
);
8569 OO
.mixinClass( OO
.ui
.MultiselectWidget
, OO
.ui
.mixin
.TitledElement
);
8576 * A change event is emitted when the set of items changes, or an item is selected or deselected.
8582 * A select event is emitted when an item is selected or deselected.
8588 * Find options that are selected.
8590 * @return {OO.ui.MultioptionWidget[]} Selected options
8592 OO
.ui
.MultiselectWidget
.prototype.findSelectedItems = function () {
8593 return this.items
.filter( function ( item
) {
8594 return item
.isSelected();
8599 * Find the data of options that are selected.
8601 * @return {Object[]|string[]} Values of selected options
8603 OO
.ui
.MultiselectWidget
.prototype.findSelectedItemsData = function () {
8604 return this.findSelectedItems().map( function ( item
) {
8610 * Select options by reference. Options not mentioned in the `items` array will be deselected.
8612 * @param {OO.ui.MultioptionWidget[]} items Items to select
8614 * @return {OO.ui.Widget} The widget, for chaining
8616 OO
.ui
.MultiselectWidget
.prototype.selectItems = function ( items
) {
8617 this.items
.forEach( function ( item
) {
8618 var selected
= items
.indexOf( item
) !== -1;
8619 item
.setSelected( selected
);
8625 * Select items by their data. Options not mentioned in the `datas` array will be deselected.
8627 * @param {Object[]|string[]} datas Values of items to select
8629 * @return {OO.ui.Widget} The widget, for chaining
8631 OO
.ui
.MultiselectWidget
.prototype.selectItemsByData = function ( datas
) {
8634 items
= datas
.map( function ( data
) {
8635 return widget
.findItemFromData( data
);
8637 this.selectItems( items
);
8642 * CheckboxMultioptionWidget is an option widget that looks like a checkbox.
8643 * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
8644 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8646 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8649 * @extends OO.ui.MultioptionWidget
8652 * @param {Object} [config] Configuration options
8654 OO
.ui
.CheckboxMultioptionWidget
= function OoUiCheckboxMultioptionWidget( config
) {
8655 // Configuration initialization
8656 config
= config
|| {};
8658 // Properties (must be done before parent constructor which calls #setDisabled)
8659 this.checkbox
= new OO
.ui
.CheckboxInputWidget();
8661 // Parent constructor
8662 OO
.ui
.CheckboxMultioptionWidget
.parent
.call( this, config
);
8665 this.checkbox
.on( 'change', this.onCheckboxChange
.bind( this ) );
8666 this.$element
.on( 'keydown', this.onKeyDown
.bind( this ) );
8670 .addClass( 'oo-ui-checkboxMultioptionWidget' )
8671 .prepend( this.checkbox
.$element
);
8676 OO
.inheritClass( OO
.ui
.CheckboxMultioptionWidget
, OO
.ui
.MultioptionWidget
);
8678 /* Static Properties */
8684 OO
.ui
.CheckboxMultioptionWidget
.static.tagName
= 'label';
8689 * Handle checkbox selected state change.
8693 OO
.ui
.CheckboxMultioptionWidget
.prototype.onCheckboxChange = function () {
8694 this.setSelected( this.checkbox
.isSelected() );
8700 OO
.ui
.CheckboxMultioptionWidget
.prototype.setSelected = function ( state
) {
8701 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setSelected
.call( this, state
);
8702 this.checkbox
.setSelected( state
);
8709 OO
.ui
.CheckboxMultioptionWidget
.prototype.setDisabled = function ( disabled
) {
8710 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
8711 this.checkbox
.setDisabled( this.isDisabled() );
8718 OO
.ui
.CheckboxMultioptionWidget
.prototype.focus = function () {
8719 this.checkbox
.focus();
8723 * Handle key down events.
8726 * @param {jQuery.Event} e
8728 OO
.ui
.CheckboxMultioptionWidget
.prototype.onKeyDown = function ( e
) {
8730 element
= this.getElementGroup(),
8733 if ( e
.keyCode
=== OO
.ui
.Keys
.LEFT
|| e
.keyCode
=== OO
.ui
.Keys
.UP
) {
8734 nextItem
= element
.getRelativeFocusableItem( this, -1 );
8735 } else if ( e
.keyCode
=== OO
.ui
.Keys
.RIGHT
|| e
.keyCode
=== OO
.ui
.Keys
.DOWN
) {
8736 nextItem
= element
.getRelativeFocusableItem( this, 1 );
8746 * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
8747 * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
8748 * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
8749 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8751 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8752 * OO.ui.CheckboxMultiselectInputWidget instead.
8755 * // A CheckboxMultiselectWidget with CheckboxMultioptions.
8756 * var option1 = new OO.ui.CheckboxMultioptionWidget( {
8759 * label: 'Selected checkbox'
8761 * option2 = new OO.ui.CheckboxMultioptionWidget( {
8763 * label: 'Unselected checkbox'
8765 * multiselect = new OO.ui.CheckboxMultiselectWidget( {
8766 * items: [ option1, option2 ]
8768 * $( document.body ).append( multiselect.$element );
8770 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8773 * @extends OO.ui.MultiselectWidget
8776 * @param {Object} [config] Configuration options
8778 OO
.ui
.CheckboxMultiselectWidget
= function OoUiCheckboxMultiselectWidget( config
) {
8779 // Parent constructor
8780 OO
.ui
.CheckboxMultiselectWidget
.parent
.call( this, config
);
8783 this.$lastClicked
= null;
8786 this.$group
.on( 'click', this.onClick
.bind( this ) );
8789 this.$element
.addClass( 'oo-ui-checkboxMultiselectWidget' );
8794 OO
.inheritClass( OO
.ui
.CheckboxMultiselectWidget
, OO
.ui
.MultiselectWidget
);
8799 * Get an option by its position relative to the specified item (or to the start of the
8800 * option array, if item is `null`). The direction in which to search through the option array
8801 * is specified with a number: -1 for reverse (the default) or 1 for forward. The method will
8802 * return an option, or `null` if there are no options in the array.
8804 * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or
8805 * `null` to start at the beginning of the array.
8806 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
8807 * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items
8810 OO
.ui
.CheckboxMultiselectWidget
.prototype.getRelativeFocusableItem = function ( item
, direction
) {
8811 var currentIndex
, nextIndex
, i
,
8812 increase
= direction
> 0 ? 1 : -1,
8813 len
= this.items
.length
;
8816 currentIndex
= this.items
.indexOf( item
);
8817 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
8819 // If no item is selected and moving forward, start at the beginning.
8820 // If moving backward, start at the end.
8821 nextIndex
= direction
> 0 ? 0 : len
- 1;
8824 for ( i
= 0; i
< len
; i
++ ) {
8825 item
= this.items
[ nextIndex
];
8826 if ( item
&& !item
.isDisabled() ) {
8829 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
8835 * Handle click events on checkboxes.
8837 * @param {jQuery.Event} e
8839 OO
.ui
.CheckboxMultiselectWidget
.prototype.onClick = function ( e
) {
8840 var $options
, lastClickedIndex
, nowClickedIndex
, i
, direction
, wasSelected
, items
,
8841 $lastClicked
= this.$lastClicked
,
8842 $nowClicked
= $( e
.target
).closest( '.oo-ui-checkboxMultioptionWidget' )
8843 .not( '.oo-ui-widget-disabled' );
8845 // Allow selecting multiple options at once by Shift-clicking them
8846 if ( $lastClicked
&& $nowClicked
.length
&& e
.shiftKey
) {
8847 $options
= this.$group
.find( '.oo-ui-checkboxMultioptionWidget' );
8848 lastClickedIndex
= $options
.index( $lastClicked
);
8849 nowClickedIndex
= $options
.index( $nowClicked
);
8850 // If it's the same item, either the user is being silly, or it's a fake event generated
8851 // by the browser. In either case we don't need custom handling.
8852 if ( nowClickedIndex
!== lastClickedIndex
) {
8854 wasSelected
= items
[ nowClickedIndex
].isSelected();
8855 direction
= nowClickedIndex
> lastClickedIndex
? 1 : -1;
8857 // This depends on the DOM order of the items and the order of the .items array being
8859 for ( i
= lastClickedIndex
; i
!== nowClickedIndex
; i
+= direction
) {
8860 if ( !items
[ i
].isDisabled() ) {
8861 items
[ i
].setSelected( !wasSelected
);
8864 // For the now-clicked element, use immediate timeout to allow the browser to do its own
8865 // handling first, then set our value. The order in which events happen is different for
8866 // clicks on the <input> and on the <label> and there are additional fake clicks fired
8867 // for non-click actions that change the checkboxes.
8869 setTimeout( function () {
8870 if ( !items
[ nowClickedIndex
].isDisabled() ) {
8871 items
[ nowClickedIndex
].setSelected( !wasSelected
);
8877 if ( $nowClicked
.length
) {
8878 this.$lastClicked
= $nowClicked
;
8886 * @return {OO.ui.Widget} The widget, for chaining
8888 OO
.ui
.CheckboxMultiselectWidget
.prototype.focus = function () {
8890 if ( !this.isDisabled() ) {
8891 item
= this.getRelativeFocusableItem( null, 1 );
8902 OO
.ui
.CheckboxMultiselectWidget
.prototype.simulateLabelClick = function () {
8907 * Progress bars visually display the status of an operation, such as a download,
8908 * and can be either determinate or indeterminate:
8910 * - **determinate** process bars show the percent of an operation that is complete.
8912 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
8913 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
8914 * not use percentages.
8916 * The value of the `progress` configuration determines whether the bar is determinate
8920 * // Examples of determinate and indeterminate progress bars.
8921 * var progressBar1 = new OO.ui.ProgressBarWidget( {
8924 * var progressBar2 = new OO.ui.ProgressBarWidget();
8926 * // Create a FieldsetLayout to layout progress bars.
8927 * var fieldset = new OO.ui.FieldsetLayout;
8928 * fieldset.addItems( [
8929 * new OO.ui.FieldLayout( progressBar1, {
8930 * label: 'Determinate',
8933 * new OO.ui.FieldLayout( progressBar2, {
8934 * label: 'Indeterminate',
8938 * $( document.body ).append( fieldset.$element );
8941 * @extends OO.ui.Widget
8944 * @param {Object} [config] Configuration options
8945 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
8946 * To create a determinate progress bar, specify a number that reflects the initial
8948 * By default, the progress bar is indeterminate.
8950 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
8951 // Configuration initialization
8952 config
= config
|| {};
8954 // Parent constructor
8955 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
8958 this.$bar
= $( '<div>' );
8959 this.progress
= null;
8962 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
8963 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
8966 role
: 'progressbar',
8968 'aria-valuemax': 100
8970 .addClass( 'oo-ui-progressBarWidget' )
8971 .append( this.$bar
);
8976 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
8978 /* Static Properties */
8984 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
8989 * Get the percent of the progress that has been completed. Indeterminate progresses will
8992 * @return {number|boolean} Progress percent
8994 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
8995 return this.progress
;
8999 * Set the percent of the process completed or `false` for an indeterminate process.
9001 * @param {number|boolean} progress Progress percent or `false` for indeterminate
9003 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
9004 this.progress
= progress
;
9006 if ( progress
!== false ) {
9007 this.$bar
.css( 'width', this.progress
+ '%' );
9008 this.$element
.attr( 'aria-valuenow', this.progress
);
9010 this.$bar
.css( 'width', '' );
9011 this.$element
.removeAttr( 'aria-valuenow' );
9013 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress
=== false );
9017 * InputWidget is the base class for all input widgets, which
9018 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox
9019 * inputs}, {@link OO.ui.RadioInputWidget radio inputs}, and
9020 * {@link OO.ui.ButtonInputWidget button inputs}.
9021 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
9023 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9027 * @extends OO.ui.Widget
9028 * @mixins OO.ui.mixin.TabIndexedElement
9029 * @mixins OO.ui.mixin.TitledElement
9030 * @mixins OO.ui.mixin.AccessKeyedElement
9033 * @param {Object} [config] Configuration options
9034 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
9035 * @cfg {string} [value=''] The value of the input.
9036 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
9037 * @cfg {string} [inputId] The value of the input’s HTML `id` attribute.
9038 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the
9039 * value of an input before it is accepted.
9041 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
9042 // Configuration initialization
9043 config
= config
|| {};
9045 // Parent constructor
9046 OO
.ui
.InputWidget
.parent
.call( this, config
);
9049 // See #reusePreInfuseDOM about config.$input
9050 this.$input
= config
.$input
|| this.getInputElement( config
);
9052 this.inputFilter
= config
.inputFilter
;
9054 // Mixin constructors
9055 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {
9056 $tabIndexed
: this.$input
9058 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {
9059 $titled
: this.$input
9061 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {
9062 $accessKeyed
: this.$input
9066 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
9070 .addClass( 'oo-ui-inputWidget-input' )
9071 .attr( 'name', config
.name
)
9072 .prop( 'disabled', this.isDisabled() );
9074 .addClass( 'oo-ui-inputWidget' )
9075 .append( this.$input
);
9076 this.setValue( config
.value
);
9078 this.setDir( config
.dir
);
9080 if ( config
.inputId
!== undefined ) {
9081 this.setInputId( config
.inputId
);
9087 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
9088 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
9089 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
9090 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
9092 /* Static Methods */
9097 OO
.ui
.InputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
9098 config
= OO
.ui
.InputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
9099 // Reusing `$input` lets browsers preserve inputted values across page reloads, see T114134.
9100 config
.$input
= $( node
).find( '.oo-ui-inputWidget-input' );
9107 OO
.ui
.InputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9108 var state
= OO
.ui
.InputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9109 if ( config
.$input
&& config
.$input
.length
) {
9110 state
.value
= config
.$input
.val();
9111 // Might be better in TabIndexedElement, but it's awkward to do there because
9112 // mixins are awkward
9113 state
.focus
= config
.$input
.is( ':focus' );
9123 * A change event is emitted when the value of the input changes.
9125 * @param {string} value
9131 * Get input element.
9133 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
9134 * different circumstances. The element must have a `value` property (like form elements).
9137 * @param {Object} config Configuration options
9138 * @return {jQuery} Input element
9140 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
9141 return $( '<input>' );
9145 * Handle potentially value-changing events.
9148 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
9150 OO
.ui
.InputWidget
.prototype.onEdit = function () {
9152 if ( !this.isDisabled() ) {
9153 // Allow the stack to clear so the value will be updated
9154 setTimeout( function () {
9155 widget
.setValue( widget
.$input
.val() );
9161 * Get the value of the input.
9163 * @return {string} Input value
9165 OO
.ui
.InputWidget
.prototype.getValue = function () {
9166 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
9167 // it, and we won't know unless they're kind enough to trigger a 'change' event.
9168 var value
= this.$input
.val();
9169 if ( this.value
!== value
) {
9170 this.setValue( value
);
9176 * Set the directionality of the input.
9178 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
9180 * @return {OO.ui.Widget} The widget, for chaining
9182 OO
.ui
.InputWidget
.prototype.setDir = function ( dir
) {
9183 this.$input
.prop( 'dir', dir
);
9188 * Set the value of the input.
9190 * @param {string} value New value
9193 * @return {OO.ui.Widget} The widget, for chaining
9195 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
9196 value
= this.cleanUpValue( value
);
9197 // Update the DOM if it has changed. Note that with cleanUpValue, it
9198 // is possible for the DOM value to change without this.value changing.
9199 if ( this.$input
.val() !== value
) {
9200 this.$input
.val( value
);
9202 if ( this.value
!== value
) {
9204 this.emit( 'change', this.value
);
9206 // The first time that the value is set (probably while constructing the widget),
9207 // remember it in defaultValue. This property can be later used to check whether
9208 // the value of the input has been changed since it was created.
9209 if ( this.defaultValue
=== undefined ) {
9210 this.defaultValue
= this.value
;
9211 this.$input
[ 0 ].defaultValue
= this.defaultValue
;
9217 * Clean up incoming value.
9219 * Ensures value is a string, and converts undefined and null to empty string.
9222 * @param {string} value Original value
9223 * @return {string} Cleaned up value
9225 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
9226 if ( value
=== undefined || value
=== null ) {
9228 } else if ( this.inputFilter
) {
9229 return this.inputFilter( String( value
) );
9231 return String( value
);
9238 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
9239 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9240 if ( this.$input
) {
9241 this.$input
.prop( 'disabled', this.isDisabled() );
9247 * Set the 'id' attribute of the `<input>` element.
9249 * @param {string} id
9251 * @return {OO.ui.Widget} The widget, for chaining
9253 OO
.ui
.InputWidget
.prototype.setInputId = function ( id
) {
9254 this.$input
.attr( 'id', id
);
9261 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
9262 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
9263 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
9264 this.setValue( state
.value
);
9266 if ( state
.focus
) {
9272 * Data widget intended for creating `<input type="hidden">` inputs.
9275 * @extends OO.ui.Widget
9278 * @param {Object} [config] Configuration options
9279 * @cfg {string} [value=''] The value of the input.
9280 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
9282 OO
.ui
.HiddenInputWidget
= function OoUiHiddenInputWidget( config
) {
9283 // Configuration initialization
9284 config
= $.extend( { value
: '', name
: '' }, config
);
9286 // Parent constructor
9287 OO
.ui
.HiddenInputWidget
.parent
.call( this, config
);
9290 this.$element
.attr( {
9292 value
: config
.value
,
9295 this.$element
.removeAttr( 'aria-disabled' );
9300 OO
.inheritClass( OO
.ui
.HiddenInputWidget
, OO
.ui
.Widget
);
9302 /* Static Properties */
9308 OO
.ui
.HiddenInputWidget
.static.tagName
= 'input';
9311 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
9312 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
9313 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
9314 * HTML `<button>` (the default) or an HTML `<input>` tags. See the
9315 * [OOUI documentation on MediaWiki] [1] for more information.
9318 * // A ButtonInputWidget rendered as an HTML button, the default.
9319 * var button = new OO.ui.ButtonInputWidget( {
9320 * label: 'Input button',
9324 * $( document.body ).append( button.$element );
9326 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#Button_inputs
9329 * @extends OO.ui.InputWidget
9330 * @mixins OO.ui.mixin.ButtonElement
9331 * @mixins OO.ui.mixin.IconElement
9332 * @mixins OO.ui.mixin.IndicatorElement
9333 * @mixins OO.ui.mixin.LabelElement
9334 * @mixins OO.ui.mixin.FlaggedElement
9337 * @param {Object} [config] Configuration options
9338 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute:
9339 * 'button', 'submit' or 'reset'.
9340 * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
9341 * Widgets configured to be an `<input>` do not support {@link #icon icons} and
9342 * {@link #indicator indicators},
9343 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should
9344 * only be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
9346 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
9347 // Configuration initialization
9348 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
9350 // See InputWidget#reusePreInfuseDOM about config.$input
9351 if ( config
.$input
) {
9352 config
.$input
.empty();
9355 // Properties (must be set before parent constructor, which calls #setValue)
9356 this.useInputTag
= config
.useInputTag
;
9358 // Parent constructor
9359 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
9361 // Mixin constructors
9362 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {
9363 $button
: this.$input
9365 OO
.ui
.mixin
.IconElement
.call( this, config
);
9366 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
9367 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9368 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
9371 if ( !config
.useInputTag
) {
9372 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
9374 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
9379 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
9380 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
9381 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
9382 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
9383 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
9384 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.FlaggedElement
);
9386 /* Static Properties */
9392 OO
.ui
.ButtonInputWidget
.static.tagName
= 'span';
9400 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
9402 type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ? config
.type
: 'button';
9403 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
9409 * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
9411 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
9412 * text, or `null` for no label
9414 * @return {OO.ui.Widget} The widget, for chaining
9416 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
9417 if ( typeof label
=== 'function' ) {
9418 label
= OO
.ui
.resolveMsg( label
);
9421 if ( this.useInputTag
) {
9422 // Discard non-plaintext labels
9423 if ( typeof label
!== 'string' ) {
9427 this.$input
.val( label
);
9430 return OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
9434 * Set the value of the input.
9436 * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
9437 * they do not support {@link #value values}.
9439 * @param {string} value New value
9441 * @return {OO.ui.Widget} The widget, for chaining
9443 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
9444 if ( !this.useInputTag
) {
9445 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
9453 OO
.ui
.ButtonInputWidget
.prototype.getInputId = function () {
9454 // Disable generating `<label>` elements for buttons. One would very rarely need additional
9455 // label for a button, and it's already a big clickable target, and it causes
9456 // unexpected rendering.
9461 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
9462 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
9463 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
9464 * alignment. For more information, please see the [OOUI documentation on MediaWiki][1].
9466 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9469 * // An example of selected, unselected, and disabled checkbox inputs.
9470 * var checkbox1 = new OO.ui.CheckboxInputWidget( {
9474 * checkbox2 = new OO.ui.CheckboxInputWidget( {
9477 * checkbox3 = new OO.ui.CheckboxInputWidget( {
9481 * // Create a fieldset layout with fields for each checkbox.
9482 * fieldset = new OO.ui.FieldsetLayout( {
9483 * label: 'Checkboxes'
9485 * fieldset.addItems( [
9486 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
9487 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
9488 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
9490 * $( document.body ).append( fieldset.$element );
9492 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9495 * @extends OO.ui.InputWidget
9498 * @param {Object} [config] Configuration options
9499 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is
9501 * @cfg {boolean} [indeterminate=false] Whether the checkbox is in the indeterminate state.
9503 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
9504 // Configuration initialization
9505 config
= config
|| {};
9507 // Parent constructor
9508 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
9511 this.checkIcon
= new OO
.ui
.IconWidget( {
9513 classes
: [ 'oo-ui-checkboxInputWidget-checkIcon' ]
9518 .addClass( 'oo-ui-checkboxInputWidget' )
9519 // Required for pretty styling in WikimediaUI theme
9520 .append( this.checkIcon
.$element
);
9521 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
9522 this.setIndeterminate( config
.indeterminate
!== undefined ? config
.indeterminate
: false );
9527 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
9534 * A change event is emitted when the state of the input changes.
9536 * @param {boolean} selected
9537 * @param {boolean} indeterminate
9540 /* Static Properties */
9546 OO
.ui
.CheckboxInputWidget
.static.tagName
= 'span';
9548 /* Static Methods */
9553 OO
.ui
.CheckboxInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9554 var state
= OO
.ui
.CheckboxInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9555 state
.checked
= config
.$input
.prop( 'checked' );
9565 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
9566 return $( '<input>' ).attr( 'type', 'checkbox' );
9572 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
9574 if ( !this.isDisabled() ) {
9575 // Allow the stack to clear so the value will be updated
9576 setTimeout( function () {
9577 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
9578 widget
.setIndeterminate( widget
.$input
.prop( 'indeterminate' ) );
9584 * Set selection state of this checkbox.
9586 * @param {boolean} state Selected state
9587 * @param {boolean} internal Used for internal calls to suppress events
9589 * @return {OO.ui.CheckboxInputWidget} The widget, for chaining
9591 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
, internal ) {
9593 if ( this.selected
!== state
) {
9594 this.selected
= state
;
9595 this.$input
.prop( 'checked', this.selected
);
9597 this.setIndeterminate( false, true );
9598 this.emit( 'change', this.selected
, this.indeterminate
);
9601 // The first time that the selection state is set (probably while constructing the widget),
9602 // remember it in defaultSelected. This property can be later used to check whether
9603 // the selection state of the input has been changed since it was created.
9604 if ( this.defaultSelected
=== undefined ) {
9605 this.defaultSelected
= this.selected
;
9606 this.$input
[ 0 ].defaultChecked
= this.defaultSelected
;
9612 * Check if this checkbox is selected.
9614 * @return {boolean} Checkbox is selected
9616 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
9617 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
9618 // it, and we won't know unless they're kind enough to trigger a 'change' event.
9619 var selected
= this.$input
.prop( 'checked' );
9620 if ( this.selected
!== selected
) {
9621 this.setSelected( selected
);
9623 return this.selected
;
9627 * Set indeterminate state of this checkbox.
9629 * @param {boolean} state Indeterminate state
9630 * @param {boolean} internal Used for internal calls to suppress events
9632 * @return {OO.ui.CheckboxInputWidget} The widget, for chaining
9634 OO
.ui
.CheckboxInputWidget
.prototype.setIndeterminate = function ( state
, internal ) {
9636 if ( this.indeterminate
!== state
) {
9637 this.indeterminate
= state
;
9638 this.$input
.prop( 'indeterminate', this.indeterminate
);
9640 this.setSelected( false, true );
9641 this.emit( 'change', this.selected
, this.indeterminate
);
9648 * Check if this checkbox is selected.
9650 * @return {boolean} Checkbox is selected
9652 OO
.ui
.CheckboxInputWidget
.prototype.isIndeterminate = function () {
9653 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
9654 // it, and we won't know unless they're kind enough to trigger a 'change' event.
9655 var indeterminate
= this.$input
.prop( 'indeterminate' );
9656 if ( this.indeterminate
!== indeterminate
) {
9657 this.setIndeterminate( indeterminate
);
9659 return this.indeterminate
;
9665 OO
.ui
.CheckboxInputWidget
.prototype.simulateLabelClick = function () {
9666 if ( !this.isDisabled() ) {
9667 this.$handle
.trigger( 'click' );
9675 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
9676 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
9677 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
9678 this.setSelected( state
.checked
);
9683 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
9684 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the
9685 * value of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9686 * more information about input widgets.
9688 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
9689 * are no options. If no `value` configuration option is provided, the first option is selected.
9690 * If you need a state representing no value (no option being selected), use a DropdownWidget.
9692 * This and OO.ui.RadioSelectInputWidget support similar configuration options.
9695 * // A DropdownInputWidget with three options.
9696 * var dropdownInput = new OO.ui.DropdownInputWidget( {
9698 * { data: 'a', label: 'First' },
9699 * { data: 'b', label: 'Second', disabled: true },
9700 * { optgroup: 'Group label' },
9701 * { data: 'c', label: 'First sub-item)' }
9704 * $( document.body ).append( dropdownInput.$element );
9706 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9709 * @extends OO.ui.InputWidget
9712 * @param {Object} [config] Configuration options
9713 * @cfg {Object[]} [options=[]] Array of menu options in the format described above.
9714 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
9715 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful
9716 * in cases where the expanded menu is larger than its containing `<div>`. The specified overlay
9717 * layer is usually on top of the containing `<div>` and has a larger area. By default, the menu
9718 * uses relative positioning.
9719 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
9721 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
9722 // Configuration initialization
9723 config
= config
|| {};
9725 // Properties (must be done before parent constructor which calls #setDisabled)
9726 this.dropdownWidget
= new OO
.ui
.DropdownWidget( $.extend(
9728 $overlay
: config
.$overlay
9732 // Set up the options before parent constructor, which uses them to validate config.value.
9733 // Use this instead of setOptions() because this.$input is not set up yet.
9734 this.setOptionsData( config
.options
|| [] );
9736 // Parent constructor
9737 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
9740 this.dropdownWidget
.getMenu().connect( this, {
9741 select
: 'onMenuSelect'
9746 .addClass( 'oo-ui-dropdownInputWidget' )
9747 .append( this.dropdownWidget
.$element
);
9748 this.setTabIndexedElement( this.dropdownWidget
.$tabIndexed
);
9749 this.setTitledElement( this.dropdownWidget
.$handle
);
9754 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
9762 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
9763 return $( '<select>' );
9767 * Handles menu select events.
9770 * @param {OO.ui.MenuOptionWidget|null} item Selected menu item
9772 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
9773 this.setValue( item
? item
.getData() : '' );
9779 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
9781 value
= this.cleanUpValue( value
);
9782 // Only allow setting values that are actually present in the dropdown
9783 selected
= this.dropdownWidget
.getMenu().findItemFromData( value
) ||
9784 this.dropdownWidget
.getMenu().findFirstSelectableItem();
9785 this.dropdownWidget
.getMenu().selectItem( selected
);
9786 value
= selected
? selected
.getData() : '';
9787 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
9788 if ( this.optionsDirty
) {
9789 // We reached this from the constructor or from #setOptions.
9790 // We have to update the <select> element.
9791 this.updateOptionsInterface();
9799 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
9800 this.dropdownWidget
.setDisabled( state
);
9801 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9806 * Set the options available for this input.
9808 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9810 * @return {OO.ui.Widget} The widget, for chaining
9812 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
9813 var value
= this.getValue();
9815 this.setOptionsData( options
);
9817 // Re-set the value to update the visible interface (DropdownWidget and <select>).
9818 // In case the previous value is no longer an available option, select the first valid one.
9819 this.setValue( value
);
9825 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
9827 * This method may be called before the parent constructor, so various properties may not be
9830 * @param {Object[]} options Array of menu options (see #constructor for details).
9833 OO
.ui
.DropdownInputWidget
.prototype.setOptionsData = function ( options
) {
9834 var optionWidgets
, optIndex
, opt
, previousOptgroup
, optionWidget
, optValue
,
9837 this.optionsDirty
= true;
9839 // Go through all the supplied option configs and create either
9840 // MenuSectionOption or MenuOption widgets from each.
9842 for ( optIndex
= 0; optIndex
< options
.length
; optIndex
++ ) {
9843 opt
= options
[ optIndex
];
9845 if ( opt
.optgroup
!== undefined ) {
9846 // Create a <optgroup> menu item.
9847 optionWidget
= widget
.createMenuSectionOptionWidget( opt
.optgroup
);
9848 previousOptgroup
= optionWidget
;
9851 // Create a normal <option> menu item.
9852 optValue
= widget
.cleanUpValue( opt
.data
);
9853 optionWidget
= widget
.createMenuOptionWidget(
9855 opt
.label
!== undefined ? opt
.label
: optValue
9859 // Disable the menu option if it is itself disabled or if its parent optgroup is disabled.
9861 opt
.disabled
!== undefined ||
9862 previousOptgroup
instanceof OO
.ui
.MenuSectionOptionWidget
&&
9863 previousOptgroup
.isDisabled()
9865 optionWidget
.setDisabled( true );
9868 optionWidgets
.push( optionWidget
);
9871 this.dropdownWidget
.getMenu().clearItems().addItems( optionWidgets
);
9875 * Create a menu option widget.
9878 * @param {string} data Item data
9879 * @param {string} label Item label
9880 * @return {OO.ui.MenuOptionWidget} Option widget
9882 OO
.ui
.DropdownInputWidget
.prototype.createMenuOptionWidget = function ( data
, label
) {
9883 return new OO
.ui
.MenuOptionWidget( {
9890 * Create a menu section option widget.
9893 * @param {string} label Section item label
9894 * @return {OO.ui.MenuSectionOptionWidget} Menu section option widget
9896 OO
.ui
.DropdownInputWidget
.prototype.createMenuSectionOptionWidget = function ( label
) {
9897 return new OO
.ui
.MenuSectionOptionWidget( {
9903 * Update the user-visible interface to match the internal list of options and value.
9905 * This method must only be called after the parent constructor.
9909 OO
.ui
.DropdownInputWidget
.prototype.updateOptionsInterface = function () {
9911 $optionsContainer
= this.$input
,
9912 defaultValue
= this.defaultValue
,
9915 this.$input
.empty();
9917 this.dropdownWidget
.getMenu().getItems().forEach( function ( optionWidget
) {
9920 if ( !( optionWidget
instanceof OO
.ui
.MenuSectionOptionWidget
) ) {
9921 $optionNode
= $( '<option>' )
9922 .attr( 'value', optionWidget
.getData() )
9923 .text( optionWidget
.getLabel() );
9925 // Remember original selection state. This property can be later used to check whether
9926 // the selection state of the input has been changed since it was created.
9927 $optionNode
[ 0 ].defaultSelected
= ( optionWidget
.getData() === defaultValue
);
9929 $optionsContainer
.append( $optionNode
);
9931 $optionNode
= $( '<optgroup>' )
9932 .attr( 'label', optionWidget
.getLabel() );
9933 widget
.$input
.append( $optionNode
);
9934 $optionsContainer
= $optionNode
;
9937 // Disable the option or optgroup if required.
9938 if ( optionWidget
.isDisabled() ) {
9939 $optionNode
.prop( 'disabled', true );
9943 this.optionsDirty
= false;
9949 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
9950 this.dropdownWidget
.focus();
9957 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
9958 this.dropdownWidget
.blur();
9963 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
9964 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
9965 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
9966 * please see the [OOUI documentation on MediaWiki][1].
9968 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9971 * // An example of selected, unselected, and disabled radio inputs
9972 * var radio1 = new OO.ui.RadioInputWidget( {
9976 * var radio2 = new OO.ui.RadioInputWidget( {
9979 * var radio3 = new OO.ui.RadioInputWidget( {
9983 * // Create a fieldset layout with fields for each radio button.
9984 * var fieldset = new OO.ui.FieldsetLayout( {
9985 * label: 'Radio inputs'
9987 * fieldset.addItems( [
9988 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
9989 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
9990 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
9992 * $( document.body ).append( fieldset.$element );
9994 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9997 * @extends OO.ui.InputWidget
10000 * @param {Object} [config] Configuration options
10001 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button
10004 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
10005 // Configuration initialization
10006 config
= config
|| {};
10008 // Parent constructor
10009 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
10013 .addClass( 'oo-ui-radioInputWidget' )
10014 // Required for pretty styling in WikimediaUI theme
10015 .append( $( '<span>' ) );
10016 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
10021 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
10023 /* Static Properties */
10029 OO
.ui
.RadioInputWidget
.static.tagName
= 'span';
10031 /* Static Methods */
10036 OO
.ui
.RadioInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
10037 var state
= OO
.ui
.RadioInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
10038 state
.checked
= config
.$input
.prop( 'checked' );
10048 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
10049 return $( '<input>' ).attr( 'type', 'radio' );
10055 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
10056 // RadioInputWidget doesn't track its state.
10060 * Set selection state of this radio button.
10062 * @param {boolean} state `true` for selected
10064 * @return {OO.ui.Widget} The widget, for chaining
10066 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
10067 // RadioInputWidget doesn't track its state.
10068 this.$input
.prop( 'checked', state
);
10069 // The first time that the selection state is set (probably while constructing the widget),
10070 // remember it in defaultSelected. This property can be later used to check whether
10071 // the selection state of the input has been changed since it was created.
10072 if ( this.defaultSelected
=== undefined ) {
10073 this.defaultSelected
= state
;
10074 this.$input
[ 0 ].defaultChecked
= this.defaultSelected
;
10080 * Check if this radio button is selected.
10082 * @return {boolean} Radio is selected
10084 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
10085 return this.$input
.prop( 'checked' );
10091 OO
.ui
.RadioInputWidget
.prototype.simulateLabelClick = function () {
10092 if ( !this.isDisabled() ) {
10093 this.$input
.trigger( 'click' );
10101 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
10102 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
10103 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
10104 this.setSelected( state
.checked
);
10109 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be
10110 * used within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with
10111 * the value of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
10112 * more information about input widgets.
10114 * This and OO.ui.DropdownInputWidget support similar configuration options.
10117 * // A RadioSelectInputWidget with three options
10118 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
10120 * { data: 'a', label: 'First' },
10121 * { data: 'b', label: 'Second'},
10122 * { data: 'c', label: 'Third' }
10125 * $( document.body ).append( radioSelectInput.$element );
10127 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
10130 * @extends OO.ui.InputWidget
10133 * @param {Object} [config] Configuration options
10134 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
10136 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
10137 // Configuration initialization
10138 config
= config
|| {};
10140 // Properties (must be done before parent constructor which calls #setDisabled)
10141 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
10142 // Set up the options before parent constructor, which uses them to validate config.value.
10143 // Use this instead of setOptions() because this.$input is not set up yet
10144 this.setOptionsData( config
.options
|| [] );
10146 // Parent constructor
10147 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
10150 this.radioSelectWidget
.connect( this, {
10151 select
: 'onMenuSelect'
10156 .addClass( 'oo-ui-radioSelectInputWidget' )
10157 .append( this.radioSelectWidget
.$element
);
10158 this.setTabIndexedElement( this.radioSelectWidget
.$tabIndexed
);
10163 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
10165 /* Static Methods */
10170 OO
.ui
.RadioSelectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
10171 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
10172 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
10179 OO
.ui
.RadioSelectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
10180 config
= OO
.ui
.RadioSelectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
10181 // Cannot reuse the `<input type=radio>` set
10182 delete config
.$input
;
10192 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
10193 // Use this instead of <input type="hidden">, because hidden inputs do not have separate
10194 // 'value' and 'defaultValue' properties, and InputWidget wants to handle 'defaultValue'.
10195 return $( '<input>' ).addClass( 'oo-ui-element-hidden' );
10199 * Handles menu select events.
10202 * @param {OO.ui.RadioOptionWidget} item Selected menu item
10204 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
10205 this.setValue( item
.getData() );
10211 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
10213 value
= this.cleanUpValue( value
);
10214 // Only allow setting values that are actually present in the dropdown
10215 selected
= this.radioSelectWidget
.findItemFromData( value
) ||
10216 this.radioSelectWidget
.findFirstSelectableItem();
10217 this.radioSelectWidget
.selectItem( selected
);
10218 value
= selected
? selected
.getData() : '';
10219 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
10226 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
10227 this.radioSelectWidget
.setDisabled( state
);
10228 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
10233 * Set the options available for this input.
10235 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10237 * @return {OO.ui.Widget} The widget, for chaining
10239 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
10240 var value
= this.getValue();
10242 this.setOptionsData( options
);
10244 // Re-set the value to update the visible interface (RadioSelectWidget).
10245 // In case the previous value is no longer an available option, select the first valid one.
10246 this.setValue( value
);
10252 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
10254 * This method may be called before the parent constructor, so various properties may not be
10257 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10260 OO
.ui
.RadioSelectInputWidget
.prototype.setOptionsData = function ( options
) {
10263 this.radioSelectWidget
10265 .addItems( options
.map( function ( opt
) {
10266 var optValue
= widget
.cleanUpValue( opt
.data
);
10267 return new OO
.ui
.RadioOptionWidget( {
10269 label
: opt
.label
!== undefined ? opt
.label
: optValue
10277 OO
.ui
.RadioSelectInputWidget
.prototype.focus = function () {
10278 this.radioSelectWidget
.focus();
10285 OO
.ui
.RadioSelectInputWidget
.prototype.blur = function () {
10286 this.radioSelectWidget
.blur();
10291 * CheckboxMultiselectInputWidget is a
10292 * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
10293 * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
10294 * HTML `<input type=checkbox>` tags. Please see the [OOUI documentation on MediaWiki][1] for
10295 * more information about input widgets.
10298 * // A CheckboxMultiselectInputWidget with three options.
10299 * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
10301 * { data: 'a', label: 'First' },
10302 * { data: 'b', label: 'Second' },
10303 * { data: 'c', label: 'Third' }
10306 * $( document.body ).append( multiselectInput.$element );
10308 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
10311 * @extends OO.ui.InputWidget
10314 * @param {Object} [config] Configuration options
10315 * @cfg {Object[]} [options=[]] Array of menu options in the format
10316 * `{ data: …, label: …, disabled: … }`
10318 OO
.ui
.CheckboxMultiselectInputWidget
= function OoUiCheckboxMultiselectInputWidget( config
) {
10319 // Configuration initialization
10320 config
= config
|| {};
10322 // Properties (must be done before parent constructor which calls #setDisabled)
10323 this.checkboxMultiselectWidget
= new OO
.ui
.CheckboxMultiselectWidget();
10324 // Must be set before the #setOptionsData call below
10325 this.inputName
= config
.name
;
10326 // Set up the options before parent constructor, which uses them to validate config.value.
10327 // Use this instead of setOptions() because this.$input is not set up yet
10328 this.setOptionsData( config
.options
|| [] );
10330 // Parent constructor
10331 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.call( this, config
);
10334 this.checkboxMultiselectWidget
.connect( this, {
10335 select
: 'onCheckboxesSelect'
10340 .addClass( 'oo-ui-checkboxMultiselectInputWidget' )
10341 .append( this.checkboxMultiselectWidget
.$element
);
10342 // We don't use this.$input, but rather the CheckboxInputWidgets inside each option
10343 this.$input
.detach();
10348 OO
.inheritClass( OO
.ui
.CheckboxMultiselectInputWidget
, OO
.ui
.InputWidget
);
10350 /* Static Methods */
10355 OO
.ui
.CheckboxMultiselectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
10356 var state
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.gatherPreInfuseState(
10359 state
.value
= $( node
).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
10360 .toArray().map( function ( el
) { return el
.value
; } );
10367 OO
.ui
.CheckboxMultiselectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
10368 config
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
10369 // Cannot reuse the `<input type=checkbox>` set
10370 delete config
.$input
;
10380 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getInputElement = function () {
10382 return $( '<unused>' );
10386 * Handles CheckboxMultiselectWidget select events.
10390 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.onCheckboxesSelect = function () {
10391 this.setValue( this.checkboxMultiselectWidget
.findSelectedItemsData() );
10397 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getValue = function () {
10398 var value
= this.$element
.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
10399 .toArray().map( function ( el
) { return el
.value
; } );
10400 if ( this.value
!== value
) {
10401 this.setValue( value
);
10409 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setValue = function ( value
) {
10410 value
= this.cleanUpValue( value
);
10411 this.checkboxMultiselectWidget
.selectItemsByData( value
);
10412 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setValue
.call( this, value
);
10413 if ( this.optionsDirty
) {
10414 // We reached this from the constructor or from #setOptions.
10415 // We have to update the <select> element.
10416 this.updateOptionsInterface();
10422 * Clean up incoming value.
10424 * @param {string[]} value Original value
10425 * @return {string[]} Cleaned up value
10427 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.cleanUpValue = function ( value
) {
10428 var i
, singleValue
,
10430 if ( !Array
.isArray( value
) ) {
10433 for ( i
= 0; i
< value
.length
; i
++ ) {
10434 singleValue
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
10435 .call( this, value
[ i
] );
10436 // Remove options that we don't have here
10437 if ( !this.checkboxMultiselectWidget
.findItemFromData( singleValue
) ) {
10440 cleanValue
.push( singleValue
);
10448 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setDisabled = function ( state
) {
10449 this.checkboxMultiselectWidget
.setDisabled( state
);
10450 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
10455 * Set the options available for this input.
10457 * @param {Object[]} options Array of menu options in the format
10458 * `{ data: …, label: …, disabled: … }`
10460 * @return {OO.ui.Widget} The widget, for chaining
10462 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setOptions = function ( options
) {
10463 var value
= this.getValue();
10465 this.setOptionsData( options
);
10467 // Re-set the value to update the visible interface (CheckboxMultiselectWidget).
10468 // This will also get rid of any stale options that we just removed.
10469 this.setValue( value
);
10475 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
10477 * This method may be called before the parent constructor, so various properties may not be
10480 * @param {Object[]} options Array of menu options in the format
10481 * `{ data: …, label: … }`
10484 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setOptionsData = function ( options
) {
10487 this.optionsDirty
= true;
10489 this.checkboxMultiselectWidget
10491 .addItems( options
.map( function ( opt
) {
10492 var optValue
, item
, optDisabled
;
10493 optValue
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
10494 .call( widget
, opt
.data
);
10495 optDisabled
= opt
.disabled
!== undefined ? opt
.disabled
: false;
10496 item
= new OO
.ui
.CheckboxMultioptionWidget( {
10498 label
: opt
.label
!== undefined ? opt
.label
: optValue
,
10499 disabled
: optDisabled
10501 // Set the 'name' and 'value' for form submission
10502 item
.checkbox
.$input
.attr( 'name', widget
.inputName
);
10503 item
.checkbox
.setValue( optValue
);
10509 * Update the user-visible interface to match the internal list of options and value.
10511 * This method must only be called after the parent constructor.
10515 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.updateOptionsInterface = function () {
10516 var defaultValue
= this.defaultValue
;
10518 this.checkboxMultiselectWidget
.getItems().forEach( function ( item
) {
10519 // Remember original selection state. This property can be later used to check whether
10520 // the selection state of the input has been changed since it was created.
10521 var isDefault
= defaultValue
.indexOf( item
.getData() ) !== -1;
10522 item
.checkbox
.defaultSelected
= isDefault
;
10523 item
.checkbox
.$input
[ 0 ].defaultChecked
= isDefault
;
10526 this.optionsDirty
= false;
10532 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.focus = function () {
10533 this.checkboxMultiselectWidget
.focus();
10538 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
10539 * size of the field as well as its presentation. In addition, these widgets can be configured
10540 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an
10541 * optional validation-pattern (used to determine if an input value is valid or not) and an input
10542 * filter, which modifies incoming values rather than validating them.
10543 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
10545 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
10548 * // A TextInputWidget.
10549 * var textInput = new OO.ui.TextInputWidget( {
10550 * value: 'Text input'
10552 * $( document.body ).append( textInput.$element );
10554 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
10557 * @extends OO.ui.InputWidget
10558 * @mixins OO.ui.mixin.IconElement
10559 * @mixins OO.ui.mixin.IndicatorElement
10560 * @mixins OO.ui.mixin.PendingElement
10561 * @mixins OO.ui.mixin.LabelElement
10562 * @mixins OO.ui.mixin.FlaggedElement
10565 * @param {Object} [config] Configuration options
10566 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password'
10567 * 'email', 'url' or 'number'.
10568 * @cfg {string} [placeholder] Placeholder text
10569 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
10570 * instruct the browser to focus this widget.
10571 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
10572 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
10574 * For unfortunate historical reasons, this counts the number of UTF-16 code units rather than
10575 * Unicode codepoints, which means that codepoints outside the Basic Multilingual Plane (e.g.
10576 * many emojis) count as 2 characters each.
10577 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
10578 * the value or placeholder text: `'before'` or `'after'`
10579 * @cfg {boolean} [required=false] Mark the field as required with `true`. Implies `indicator:
10580 * 'required'`. Note that `false` & setting `indicator: 'required' will result in no indicator
10582 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
10583 * @cfg {boolean} [spellcheck] Should the browser support spellcheck for this field (`undefined`
10584 * means leaving it up to the browser).
10585 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
10586 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
10587 * (the value must contain only numbers); when RegExp, a regular expression that must match the
10588 * value for it to be considered valid; when Function, a function receiving the value as parameter
10589 * that must return true, or promise resolving to true, for it to be considered valid.
10591 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
10592 // Configuration initialization
10593 config
= $.extend( {
10595 labelPosition
: 'after'
10598 // Parent constructor
10599 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
10601 // Mixin constructors
10602 OO
.ui
.mixin
.IconElement
.call( this, config
);
10603 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
10604 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( { $pending
: this.$input
}, config
) );
10605 OO
.ui
.mixin
.LabelElement
.call( this, config
);
10606 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
10609 this.type
= this.getSaneType( config
);
10610 this.readOnly
= false;
10611 this.required
= false;
10612 this.validate
= null;
10613 this.scrollWidth
= null;
10615 this.setValidation( config
.validate
);
10616 this.setLabelPosition( config
.labelPosition
);
10620 keypress
: this.onKeyPress
.bind( this ),
10621 blur
: this.onBlur
.bind( this ),
10622 focus
: this.onFocus
.bind( this )
10624 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
10625 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
10626 this.on( 'labelChange', this.updatePosition
.bind( this ) );
10627 this.on( 'change', OO
.ui
.debounce( this.onDebouncedChange
.bind( this ), 250 ) );
10631 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
10632 .append( this.$icon
, this.$indicator
);
10633 this.setReadOnly( !!config
.readOnly
);
10634 this.setRequired( !!config
.required
);
10635 if ( config
.placeholder
!== undefined ) {
10636 this.$input
.attr( 'placeholder', config
.placeholder
);
10638 if ( config
.maxLength
!== undefined ) {
10639 this.$input
.attr( 'maxlength', config
.maxLength
);
10641 if ( config
.autofocus
) {
10642 this.$input
.attr( 'autofocus', 'autofocus' );
10644 if ( config
.autocomplete
=== false ) {
10645 this.$input
.attr( 'autocomplete', 'off' );
10646 // Turning off autocompletion also disables "form caching" when the user navigates to a
10647 // different page and then clicks "Back". Re-enable it when leaving.
10648 // Borrowed from jQuery UI.
10650 beforeunload: function () {
10651 this.$input
.removeAttr( 'autocomplete' );
10653 pageshow: function () {
10654 // Browsers don't seem to actually fire this event on "Back", they instead just
10655 // reload the whole page... it shouldn't hurt, though.
10656 this.$input
.attr( 'autocomplete', 'off' );
10660 if ( config
.spellcheck
!== undefined ) {
10661 this.$input
.attr( 'spellcheck', config
.spellcheck
? 'true' : 'false' );
10663 if ( this.label
) {
10664 this.isWaitingToBeAttached
= true;
10665 this.installParentChangeDetector();
10671 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
10672 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
10673 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
10674 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
10675 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
10676 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.FlaggedElement
);
10678 /* Static Properties */
10680 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
10688 * An `enter` event is emitted when the user presses Enter key inside the text box.
10696 * Handle icon mouse down events.
10699 * @param {jQuery.Event} e Mouse down event
10700 * @return {undefined|boolean} False to prevent default if event is handled
10702 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
10703 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
10710 * Handle indicator mouse down events.
10713 * @param {jQuery.Event} e Mouse down event
10714 * @return {undefined|boolean} False to prevent default if event is handled
10716 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
10717 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
10724 * Handle key press events.
10727 * @param {jQuery.Event} e Key press event
10728 * @fires enter If Enter key is pressed
10730 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
10731 if ( e
.which
=== OO
.ui
.Keys
.ENTER
) {
10732 this.emit( 'enter', e
);
10737 * Handle blur events.
10740 * @param {jQuery.Event} e Blur event
10742 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
10743 this.setValidityFlag();
10747 * Handle focus events.
10750 * @param {jQuery.Event} e Focus event
10752 OO
.ui
.TextInputWidget
.prototype.onFocus = function () {
10753 if ( this.isWaitingToBeAttached
) {
10754 // If we've received focus, then we must be attached to the document, and if
10755 // isWaitingToBeAttached is still true, that means the handler never fired. Fire it now.
10756 this.onElementAttach();
10758 this.setValidityFlag( true );
10762 * Handle element attach events.
10765 * @param {jQuery.Event} e Element attach event
10767 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
10768 this.isWaitingToBeAttached
= false;
10769 // Any previously calculated size is now probably invalid if we reattached elsewhere
10770 this.valCache
= null;
10771 this.positionLabel();
10775 * Handle debounced change events.
10777 * @param {string} value
10780 OO
.ui
.TextInputWidget
.prototype.onDebouncedChange = function () {
10781 this.setValidityFlag();
10785 * Check if the input is {@link #readOnly read-only}.
10787 * @return {boolean}
10789 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
10790 return this.readOnly
;
10794 * Set the {@link #readOnly read-only} state of the input.
10796 * @param {boolean} state Make input read-only
10798 * @return {OO.ui.Widget} The widget, for chaining
10800 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
10801 this.readOnly
= !!state
;
10802 this.$input
.prop( 'readOnly', this.readOnly
);
10807 * Check if the input is {@link #required required}.
10809 * @return {boolean}
10811 OO
.ui
.TextInputWidget
.prototype.isRequired = function () {
10812 return this.required
;
10816 * Set the {@link #required required} state of the input.
10818 * @param {boolean} state Make input required
10820 * @return {OO.ui.Widget} The widget, for chaining
10822 OO
.ui
.TextInputWidget
.prototype.setRequired = function ( state
) {
10823 this.required
= !!state
;
10824 if ( this.required
) {
10826 .prop( 'required', true )
10827 .attr( 'aria-required', 'true' );
10828 if ( this.getIndicator() === null ) {
10829 this.setIndicator( 'required' );
10833 .prop( 'required', false )
10834 .removeAttr( 'aria-required' );
10835 if ( this.getIndicator() === 'required' ) {
10836 this.setIndicator( null );
10843 * Support function for making #onElementAttach work across browsers.
10845 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
10846 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
10848 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
10849 * first time that the element gets attached to the documented.
10851 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
10852 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
10853 MutationObserver
= window
.MutationObserver
||
10854 window
.WebKitMutationObserver
||
10855 window
.MozMutationObserver
,
10858 if ( MutationObserver
) {
10859 // The new way. If only it wasn't so ugly.
10861 if ( this.isElementAttached() ) {
10862 // Widget is attached already, do nothing. This breaks the functionality of this
10863 // function when the widget is detached and reattached. Alas, doing this correctly with
10864 // MutationObserver would require observation of the whole document, which would hurt
10865 // performance of other, more important code.
10869 // Find topmost node in the tree
10870 topmostNode
= this.$element
[ 0 ];
10871 while ( topmostNode
.parentNode
) {
10872 topmostNode
= topmostNode
.parentNode
;
10875 // We have no way to detect the $element being attached somewhere without observing the
10876 // entire DOM with subtree modifications, which would hurt performance. So we cheat: we hook
10877 // to the parent node of $element, and instead detect when $element is removed from it (and
10878 // thus probably attached somewhere else). If there is no parent, we create a "fake" one. If
10879 // it doesn't get attached, we end up back here and create the parent.
10880 mutationObserver
= new MutationObserver( function ( mutations
) {
10881 var i
, j
, removedNodes
;
10882 for ( i
= 0; i
< mutations
.length
; i
++ ) {
10883 removedNodes
= mutations
[ i
].removedNodes
;
10884 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
10885 if ( removedNodes
[ j
] === topmostNode
) {
10886 setTimeout( onRemove
, 0 );
10893 onRemove = function () {
10894 // If the node was attached somewhere else, report it
10895 if ( widget
.isElementAttached() ) {
10896 widget
.onElementAttach();
10898 mutationObserver
.disconnect();
10899 widget
.installParentChangeDetector();
10902 // Create a fake parent and observe it
10903 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
10904 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
10906 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
10907 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
10908 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
10916 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
10917 if ( this.getSaneType( config
) === 'number' ) {
10918 return $( '<input>' )
10919 .attr( 'step', 'any' )
10920 .attr( 'type', 'number' );
10922 return $( '<input>' ).attr( 'type', this.getSaneType( config
) );
10927 * Get sanitized value for 'type' for given config.
10929 * @param {Object} config Configuration options
10930 * @return {string|null}
10933 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
10934 var allowedTypes
= [
10941 return allowedTypes
.indexOf( config
.type
) !== -1 ? config
.type
: 'text';
10945 * Focus the input and select a specified range within the text.
10947 * @param {number} from Select from offset
10948 * @param {number} [to] Select to offset, defaults to from
10950 * @return {OO.ui.Widget} The widget, for chaining
10952 OO
.ui
.TextInputWidget
.prototype.selectRange = function ( from, to
) {
10953 var isBackwards
, start
, end
,
10954 input
= this.$input
[ 0 ];
10958 isBackwards
= to
< from;
10959 start
= isBackwards
? to
: from;
10960 end
= isBackwards
? from : to
;
10965 input
.setSelectionRange( start
, end
, isBackwards
? 'backward' : 'forward' );
10967 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
10968 // Rather than expensively check if the input is attached every time, just check
10969 // if it was the cause of an error being thrown. If not, rethrow the error.
10970 if ( this.getElementDocument().body
.contains( input
) ) {
10978 * Get an object describing the current selection range in a directional manner
10980 * @return {Object} Object containing 'from' and 'to' offsets
10982 OO
.ui
.TextInputWidget
.prototype.getRange = function () {
10983 var input
= this.$input
[ 0 ],
10984 start
= input
.selectionStart
,
10985 end
= input
.selectionEnd
,
10986 isBackwards
= input
.selectionDirection
=== 'backward';
10989 from: isBackwards
? end
: start
,
10990 to
: isBackwards
? start
: end
10995 * Get the length of the text input value.
10997 * This could differ from the length of #getValue if the
10998 * value gets filtered
11000 * @return {number} Input length
11002 OO
.ui
.TextInputWidget
.prototype.getInputLength = function () {
11003 return this.$input
[ 0 ].value
.length
;
11007 * Focus the input and select the entire text.
11010 * @return {OO.ui.Widget} The widget, for chaining
11012 OO
.ui
.TextInputWidget
.prototype.select = function () {
11013 return this.selectRange( 0, this.getInputLength() );
11017 * Focus the input and move the cursor to the start.
11020 * @return {OO.ui.Widget} The widget, for chaining
11022 OO
.ui
.TextInputWidget
.prototype.moveCursorToStart = function () {
11023 return this.selectRange( 0 );
11027 * Focus the input and move the cursor to the end.
11030 * @return {OO.ui.Widget} The widget, for chaining
11032 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
11033 return this.selectRange( this.getInputLength() );
11037 * Insert new content into the input.
11039 * @param {string} content Content to be inserted
11041 * @return {OO.ui.Widget} The widget, for chaining
11043 OO
.ui
.TextInputWidget
.prototype.insertContent = function ( content
) {
11045 range
= this.getRange(),
11046 value
= this.getValue();
11048 start
= Math
.min( range
.from, range
.to
);
11049 end
= Math
.max( range
.from, range
.to
);
11051 this.setValue( value
.slice( 0, start
) + content
+ value
.slice( end
) );
11052 this.selectRange( start
+ content
.length
);
11057 * Insert new content either side of a selection.
11059 * @param {string} pre Content to be inserted before the selection
11060 * @param {string} post Content to be inserted after the selection
11062 * @return {OO.ui.Widget} The widget, for chaining
11064 OO
.ui
.TextInputWidget
.prototype.encapsulateContent = function ( pre
, post
) {
11066 range
= this.getRange(),
11067 offset
= pre
.length
;
11069 start
= Math
.min( range
.from, range
.to
);
11070 end
= Math
.max( range
.from, range
.to
);
11072 this.selectRange( start
).insertContent( pre
);
11073 this.selectRange( offset
+ end
).insertContent( post
);
11075 this.selectRange( offset
+ start
, offset
+ end
);
11080 * Set the validation pattern.
11082 * The validation pattern is either a regular expression, a function, or the symbolic name of a
11083 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
11084 * value must contain only numbers).
11086 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
11087 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
11089 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
11090 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
11091 this.validate
= validate
;
11093 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
11098 * Sets the 'invalid' flag appropriately.
11100 * @param {boolean} [isValid] Optionally override validation result
11102 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
11104 setFlag = function ( valid
) {
11106 widget
.$input
.attr( 'aria-invalid', 'true' );
11108 widget
.$input
.removeAttr( 'aria-invalid' );
11110 widget
.setFlags( { invalid
: !valid
} );
11113 if ( isValid
!== undefined ) {
11114 setFlag( isValid
);
11116 this.getValidity().then( function () {
11125 * Get the validity of current value.
11127 * This method returns a promise that resolves if the value is valid and rejects if
11128 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
11130 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
11132 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
11135 function rejectOrResolve( valid
) {
11137 return $.Deferred().resolve().promise();
11139 return $.Deferred().reject().promise();
11143 // Check browser validity and reject if it is invalid
11145 this.$input
[ 0 ].checkValidity
!== undefined &&
11146 this.$input
[ 0 ].checkValidity() === false
11148 return rejectOrResolve( false );
11151 // Run our checks if the browser thinks the field is valid
11152 if ( this.validate
instanceof Function
) {
11153 result
= this.validate( this.getValue() );
11154 if ( result
&& typeof result
.promise
=== 'function' ) {
11155 return result
.promise().then( function ( valid
) {
11156 return rejectOrResolve( valid
);
11159 return rejectOrResolve( result
);
11162 return rejectOrResolve( this.getValue().match( this.validate
) );
11167 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
11169 * @param {string} labelPosition Label position, 'before' or 'after'
11171 * @return {OO.ui.Widget} The widget, for chaining
11173 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
11174 this.labelPosition
= labelPosition
;
11175 if ( this.label
) {
11176 // If there is no label and we only change the position, #updatePosition is a no-op,
11177 // but it takes really a lot of work to do nothing.
11178 this.updatePosition();
11184 * Update the position of the inline label.
11186 * This method is called by #setLabelPosition, and can also be called on its own if
11187 * something causes the label to be mispositioned.
11190 * @return {OO.ui.Widget} The widget, for chaining
11192 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
11193 var after
= this.labelPosition
=== 'after';
11196 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
11197 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
11199 this.valCache
= null;
11200 this.scrollWidth
= null;
11201 this.positionLabel();
11207 * Position the label by setting the correct padding on the input.
11211 * @return {OO.ui.Widget} The widget, for chaining
11213 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
11214 var after
, rtl
, property
, newCss
;
11216 if ( this.isWaitingToBeAttached
) {
11217 // #onElementAttach will be called soon, which calls this method
11222 'padding-right': '',
11226 if ( this.label
) {
11227 this.$element
.append( this.$label
);
11229 this.$label
.detach();
11230 // Clear old values if present
11231 this.$input
.css( newCss
);
11235 after
= this.labelPosition
=== 'after';
11236 rtl
= this.$element
.css( 'direction' ) === 'rtl';
11237 property
= after
=== rtl
? 'padding-left' : 'padding-right';
11239 newCss
[ property
] = this.$label
.outerWidth( true ) + ( after
? this.scrollWidth
: 0 );
11240 // We have to clear the padding on the other side, in case the element direction changed
11241 this.$input
.css( newCss
);
11247 * SearchInputWidgets are TextInputWidgets with `type="search"` assigned and feature a
11248 * {@link OO.ui.mixin.IconElement search icon} by default.
11249 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
11251 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#SearchInputWidget
11254 * @extends OO.ui.TextInputWidget
11257 * @param {Object} [config] Configuration options
11259 OO
.ui
.SearchInputWidget
= function OoUiSearchInputWidget( config
) {
11260 config
= $.extend( {
11264 // Parent constructor
11265 OO
.ui
.SearchInputWidget
.parent
.call( this, config
);
11268 this.connect( this, {
11271 this.$indicator
.on( 'click', this.onIndicatorClick
.bind( this ) );
11274 this.updateSearchIndicator();
11275 this.connect( this, {
11276 disable
: 'onDisable'
11282 OO
.inheritClass( OO
.ui
.SearchInputWidget
, OO
.ui
.TextInputWidget
);
11290 OO
.ui
.SearchInputWidget
.prototype.getSaneType = function () {
11295 * Handle click events on the indicator
11297 * @param {jQuery.Event} e Click event
11298 * @return {boolean}
11300 OO
.ui
.SearchInputWidget
.prototype.onIndicatorClick = function ( e
) {
11301 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
11302 // Clear the text field
11303 this.setValue( '' );
11310 * Update the 'clear' indicator displayed on type: 'search' text
11311 * fields, hiding it when the field is already empty or when it's not
11314 OO
.ui
.SearchInputWidget
.prototype.updateSearchIndicator = function () {
11315 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
11316 this.setIndicator( null );
11318 this.setIndicator( 'clear' );
11323 * Handle change events.
11327 OO
.ui
.SearchInputWidget
.prototype.onChange = function () {
11328 this.updateSearchIndicator();
11332 * Handle disable events.
11334 * @param {boolean} disabled Element is disabled
11337 OO
.ui
.SearchInputWidget
.prototype.onDisable = function () {
11338 this.updateSearchIndicator();
11344 OO
.ui
.SearchInputWidget
.prototype.setReadOnly = function ( state
) {
11345 OO
.ui
.SearchInputWidget
.parent
.prototype.setReadOnly
.call( this, state
);
11346 this.updateSearchIndicator();
11351 * MultilineTextInputWidgets, like HTML textareas, are featuring customization options to
11352 * configure number of rows visible. In addition, these widgets can be autosized to fit user
11353 * inputs and can show {@link OO.ui.mixin.IconElement icons} and
11354 * {@link OO.ui.mixin.IndicatorElement indicators}.
11355 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
11357 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
11360 * // A MultilineTextInputWidget.
11361 * var multilineTextInput = new OO.ui.MultilineTextInputWidget( {
11362 * value: 'Text input on multiple lines'
11364 * $( document.body ).append( multilineTextInput.$element );
11366 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#MultilineTextInputWidget
11369 * @extends OO.ui.TextInputWidget
11372 * @param {Object} [config] Configuration options
11373 * @cfg {number} [rows] Number of visible lines in textarea. If used with `autosize`,
11374 * specifies minimum number of rows to display.
11375 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
11376 * Use the #maxRows config to specify a maximum number of displayed rows.
11377 * @cfg {number} [maxRows] Maximum number of rows to display when #autosize is set to true.
11378 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
11380 OO
.ui
.MultilineTextInputWidget
= function OoUiMultilineTextInputWidget( config
) {
11381 config
= $.extend( {
11384 // Parent constructor
11385 OO
.ui
.MultilineTextInputWidget
.parent
.call( this, config
);
11388 this.autosize
= !!config
.autosize
;
11389 this.styleHeight
= null;
11390 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
11391 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
11393 // Clone for resizing
11394 if ( this.autosize
) {
11395 this.$clone
= this.$input
11397 .removeAttr( 'id' )
11398 .removeAttr( 'name' )
11399 .insertAfter( this.$input
)
11400 .attr( 'aria-hidden', 'true' )
11401 .addClass( 'oo-ui-element-hidden' );
11405 this.connect( this, {
11410 if ( config
.rows
) {
11411 this.$input
.attr( 'rows', config
.rows
);
11413 if ( this.autosize
) {
11414 this.$input
.addClass( 'oo-ui-textInputWidget-autosized' );
11415 this.isWaitingToBeAttached
= true;
11416 this.installParentChangeDetector();
11422 OO
.inheritClass( OO
.ui
.MultilineTextInputWidget
, OO
.ui
.TextInputWidget
);
11424 /* Static Methods */
11429 OO
.ui
.MultilineTextInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
11430 var state
= OO
.ui
.MultilineTextInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
11431 state
.scrollTop
= config
.$input
.scrollTop();
11440 OO
.ui
.MultilineTextInputWidget
.prototype.onElementAttach = function () {
11441 OO
.ui
.MultilineTextInputWidget
.parent
.prototype.onElementAttach
.call( this );
11446 * Handle change events.
11450 OO
.ui
.MultilineTextInputWidget
.prototype.onChange = function () {
11457 OO
.ui
.MultilineTextInputWidget
.prototype.updatePosition = function () {
11458 OO
.ui
.MultilineTextInputWidget
.parent
.prototype.updatePosition
.call( this );
11465 * Modify to emit 'enter' on Ctrl/Meta+Enter, instead of plain Enter
11467 OO
.ui
.MultilineTextInputWidget
.prototype.onKeyPress = function ( e
) {
11469 ( e
.which
=== OO
.ui
.Keys
.ENTER
&& ( e
.ctrlKey
|| e
.metaKey
) ) ||
11470 // Some platforms emit keycode 10 for Control+Enter keypress in a textarea
11473 this.emit( 'enter', e
);
11478 * Automatically adjust the size of the text input.
11480 * This only affects multiline inputs that are {@link #autosize autosized}.
11483 * @return {OO.ui.Widget} The widget, for chaining
11486 OO
.ui
.MultilineTextInputWidget
.prototype.adjustSize = function () {
11487 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
,
11488 idealHeight
, newHeight
, scrollWidth
, property
;
11490 if ( this.$input
.val() !== this.valCache
) {
11491 if ( this.autosize
) {
11493 .val( this.$input
.val() )
11494 .attr( 'rows', this.minRows
)
11495 // Set inline height property to 0 to measure scroll height
11496 .css( 'height', 0 );
11498 this.$clone
.removeClass( 'oo-ui-element-hidden' );
11500 this.valCache
= this.$input
.val();
11502 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
11504 // Remove inline height property to measure natural heights
11505 this.$clone
.css( 'height', '' );
11506 innerHeight
= this.$clone
.innerHeight();
11507 outerHeight
= this.$clone
.outerHeight();
11509 // Measure max rows height
11511 .attr( 'rows', this.maxRows
)
11512 .css( 'height', 'auto' )
11514 maxInnerHeight
= this.$clone
.innerHeight();
11516 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
11517 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
11518 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
11519 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
11521 this.$clone
.addClass( 'oo-ui-element-hidden' );
11523 // Only apply inline height when expansion beyond natural height is needed
11524 // Use the difference between the inner and outer height as a buffer
11525 newHeight
= idealHeight
> innerHeight
? idealHeight
+ ( outerHeight
- innerHeight
) : '';
11526 if ( newHeight
!== this.styleHeight
) {
11527 this.$input
.css( 'height', newHeight
);
11528 this.styleHeight
= newHeight
;
11529 this.emit( 'resize' );
11532 scrollWidth
= this.$input
[ 0 ].offsetWidth
- this.$input
[ 0 ].clientWidth
;
11533 if ( scrollWidth
!== this.scrollWidth
) {
11534 property
= this.$element
.css( 'direction' ) === 'rtl' ? 'left' : 'right';
11536 this.$label
.css( { right
: '', left
: '' } );
11537 this.$indicator
.css( { right
: '', left
: '' } );
11539 if ( scrollWidth
) {
11540 this.$indicator
.css( property
, scrollWidth
);
11541 if ( this.labelPosition
=== 'after' ) {
11542 this.$label
.css( property
, scrollWidth
);
11546 this.scrollWidth
= scrollWidth
;
11547 this.positionLabel();
11557 OO
.ui
.MultilineTextInputWidget
.prototype.getInputElement = function () {
11558 return $( '<textarea>' );
11562 * Check if the input automatically adjusts its size.
11564 * @return {boolean}
11566 OO
.ui
.MultilineTextInputWidget
.prototype.isAutosizing = function () {
11567 return !!this.autosize
;
11573 OO
.ui
.MultilineTextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
11574 OO
.ui
.MultilineTextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
11575 if ( state
.scrollTop
!== undefined ) {
11576 this.$input
.scrollTop( state
.scrollTop
);
11581 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
11582 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
11583 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
11585 * - by typing a value in the text input field. If the value exactly matches the value of a menu
11586 * option, that option will appear to be selected.
11587 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
11590 * After the user chooses an option, its `data` will be used as a new value for the widget.
11591 * A `label` also can be specified for each option: if given, it will be shown instead of the
11592 * `data` in the dropdown menu.
11594 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
11596 * For more information about menus and options, please see the
11597 * [OOUI documentation on MediaWiki][1].
11600 * // A ComboBoxInputWidget.
11601 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11602 * value: 'Option 1',
11604 * { data: 'Option 1' },
11605 * { data: 'Option 2' },
11606 * { data: 'Option 3' }
11609 * $( document.body ).append( comboBox.$element );
11612 * // Example: A ComboBoxInputWidget with additional option labels.
11613 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11614 * value: 'Option 1',
11617 * data: 'Option 1',
11618 * label: 'Option One'
11621 * data: 'Option 2',
11622 * label: 'Option Two'
11625 * data: 'Option 3',
11626 * label: 'Option Three'
11630 * $( document.body ).append( comboBox.$element );
11632 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
11635 * @extends OO.ui.TextInputWidget
11638 * @param {Object} [config] Configuration options
11639 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
11640 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu
11642 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful
11643 * in cases where the expanded menu is larger than its containing `<div>`. The specified overlay
11644 * layer is usually on top of the containing `<div>` and has a larger area. By default, the menu
11645 * uses relative positioning.
11646 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11648 OO
.ui
.ComboBoxInputWidget
= function OoUiComboBoxInputWidget( config
) {
11649 // Configuration initialization
11650 config
= $.extend( {
11651 autocomplete
: false
11654 // ComboBoxInputWidget shouldn't support `multiline`
11655 config
.multiline
= false;
11657 // See InputWidget#reusePreInfuseDOM about `config.$input`
11658 if ( config
.$input
) {
11659 config
.$input
.removeAttr( 'list' );
11662 // Parent constructor
11663 OO
.ui
.ComboBoxInputWidget
.parent
.call( this, config
);
11666 this.$overlay
= ( config
.$overlay
=== true ?
11667 OO
.ui
.getDefaultOverlay() : config
.$overlay
) || this.$element
;
11668 this.dropdownButton
= new OO
.ui
.ButtonWidget( {
11669 classes
: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ],
11670 label
: OO
.ui
.msg( 'ooui-combobox-button-label' ),
11672 invisibleLabel
: true,
11673 disabled
: this.disabled
11675 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend(
11679 $floatableContainer
: this.$element
,
11680 disabled
: this.isDisabled()
11686 this.connect( this, {
11687 change
: 'onInputChange',
11688 enter
: 'onInputEnter'
11690 this.dropdownButton
.connect( this, {
11691 click
: 'onDropdownButtonClick'
11693 this.menu
.connect( this, {
11694 choose
: 'onMenuChoose',
11695 add
: 'onMenuItemsChange',
11696 remove
: 'onMenuItemsChange',
11697 toggle
: 'onMenuToggle'
11701 this.$input
.attr( {
11703 'aria-owns': this.menu
.getElementId(),
11704 'aria-autocomplete': 'list'
11706 this.dropdownButton
.$button
.attr( {
11707 'aria-controls': this.menu
.getElementId()
11709 // Do not override options set via config.menu.items
11710 if ( config
.options
!== undefined ) {
11711 this.setOptions( config
.options
);
11713 this.$field
= $( '<div>' )
11714 .addClass( 'oo-ui-comboBoxInputWidget-field' )
11715 .append( this.$input
, this.dropdownButton
.$element
);
11717 .addClass( 'oo-ui-comboBoxInputWidget' )
11718 .append( this.$field
);
11719 this.$overlay
.append( this.menu
.$element
);
11720 this.onMenuItemsChange();
11725 OO
.inheritClass( OO
.ui
.ComboBoxInputWidget
, OO
.ui
.TextInputWidget
);
11730 * Get the combobox's menu.
11732 * @return {OO.ui.MenuSelectWidget} Menu widget
11734 OO
.ui
.ComboBoxInputWidget
.prototype.getMenu = function () {
11739 * Get the combobox's text input widget.
11741 * @return {OO.ui.TextInputWidget} Text input widget
11743 OO
.ui
.ComboBoxInputWidget
.prototype.getInput = function () {
11748 * Handle input change events.
11751 * @param {string} value New value
11753 OO
.ui
.ComboBoxInputWidget
.prototype.onInputChange = function ( value
) {
11754 var match
= this.menu
.findItemFromData( value
);
11756 this.menu
.selectItem( match
);
11757 if ( this.menu
.findHighlightedItem() ) {
11758 this.menu
.highlightItem( match
);
11761 if ( !this.isDisabled() ) {
11762 this.menu
.toggle( true );
11767 * Handle input enter events.
11771 OO
.ui
.ComboBoxInputWidget
.prototype.onInputEnter = function () {
11772 if ( !this.isDisabled() ) {
11773 this.menu
.toggle( false );
11778 * Handle button click events.
11782 OO
.ui
.ComboBoxInputWidget
.prototype.onDropdownButtonClick = function () {
11783 this.menu
.toggle();
11788 * Handle menu choose events.
11791 * @param {OO.ui.OptionWidget} item Chosen item
11793 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuChoose = function ( item
) {
11794 this.setValue( item
.getData() );
11798 * Handle menu item change events.
11802 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuItemsChange = function () {
11803 var match
= this.menu
.findItemFromData( this.getValue() );
11804 this.menu
.selectItem( match
);
11805 if ( this.menu
.findHighlightedItem() ) {
11806 this.menu
.highlightItem( match
);
11808 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu
.isEmpty() );
11812 * Handle menu toggle events.
11815 * @param {boolean} isVisible Open state of the menu
11817 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuToggle = function ( isVisible
) {
11818 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-open', isVisible
);
11822 * Update the disabled state of the controls
11826 * @return {OO.ui.ComboBoxInputWidget} The widget, for chaining
11828 OO
.ui
.ComboBoxInputWidget
.prototype.updateControlsDisabled = function () {
11829 var disabled
= this.isDisabled() || this.isReadOnly();
11830 if ( this.dropdownButton
) {
11831 this.dropdownButton
.setDisabled( disabled
);
11834 this.menu
.setDisabled( disabled
);
11842 OO
.ui
.ComboBoxInputWidget
.prototype.setDisabled = function () {
11844 OO
.ui
.ComboBoxInputWidget
.parent
.prototype.setDisabled
.apply( this, arguments
);
11845 this.updateControlsDisabled();
11852 OO
.ui
.ComboBoxInputWidget
.prototype.setReadOnly = function () {
11854 OO
.ui
.ComboBoxInputWidget
.parent
.prototype.setReadOnly
.apply( this, arguments
);
11855 this.updateControlsDisabled();
11860 * Set the options available for this input.
11862 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
11864 * @return {OO.ui.Widget} The widget, for chaining
11866 OO
.ui
.ComboBoxInputWidget
.prototype.setOptions = function ( options
) {
11869 .addItems( options
.map( function ( opt
) {
11870 return new OO
.ui
.MenuOptionWidget( {
11872 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
11880 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
11881 * which is a widget that is specified by reference before any optional configuration settings.
11883 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of
11886 * - **left**: The label is placed before the field-widget and aligned with the left margin.
11887 * A left-alignment is used for forms with many fields.
11888 * - **right**: The label is placed before the field-widget and aligned to the right margin.
11889 * A right-alignment is used for long but familiar forms which users tab through,
11890 * verifying the current field with a quick glance at the label.
11891 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
11892 * that users fill out from top to bottom.
11893 * - **inline**: The label is placed after the field-widget and aligned to the left.
11894 * An inline-alignment is best used with checkboxes or radio buttons.
11896 * Help text can either be:
11898 * - accessed via a help icon that appears in the upper right corner of the rendered field layout,
11900 * - shown as a subtle explanation below the label.
11902 * If the help text is brief, or is essential to always expose it, set `helpInline` to `true`.
11903 * If it is long or not essential, leave `helpInline` to its default, `false`.
11905 * Please see the [OOUI documentation on MediaWiki] [1] for examples and more information.
11907 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
11910 * @extends OO.ui.Layout
11911 * @mixins OO.ui.mixin.LabelElement
11912 * @mixins OO.ui.mixin.TitledElement
11915 * @param {OO.ui.Widget} fieldWidget Field widget
11916 * @param {Object} [config] Configuration options
11917 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top'
11919 * @cfg {Array} [errors] Error messages about the widget, which will be
11920 * displayed below the widget.
11921 * @cfg {Array} [warnings] Warning messages about the widget, which will be
11922 * displayed below the widget.
11923 * @cfg {Array} [successMessages] Success messages on user interactions with the widget,
11924 * which will be displayed below the widget.
11925 * The array may contain strings or OO.ui.HtmlSnippet instances.
11926 * @cfg {Array} [notices] Notices about the widget, which will be displayed
11927 * below the widget.
11928 * The array may contain strings or OO.ui.HtmlSnippet instances.
11929 * These are more visible than `help` messages when `helpInline` is set, and so
11930 * might be good for transient messages.
11931 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified
11932 * and `helpInline` is `false`, a "help" icon will appear in the upper-right
11933 * corner of the rendered field; clicking it will display the text in a popup.
11934 * If `helpInline` is `true`, then a subtle description will be shown after the
11936 * @cfg {boolean} [helpInline=false] Whether or not the help should be inline,
11937 * or shown when the "help" icon is clicked.
11938 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if
11940 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11942 * @throws {Error} An error is thrown if no widget is specified
11944 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
11945 // Allow passing positional parameters inside the config object
11946 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
11947 config
= fieldWidget
;
11948 fieldWidget
= config
.fieldWidget
;
11951 // Make sure we have required constructor arguments
11952 if ( fieldWidget
=== undefined ) {
11953 throw new Error( 'Widget not found' );
11956 // Configuration initialization
11957 config
= $.extend( { align
: 'left', helpInline
: false }, config
);
11959 // Parent constructor
11960 OO
.ui
.FieldLayout
.parent
.call( this, config
);
11962 // Mixin constructors
11963 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {
11964 $label
: $( '<label>' )
11966 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( { $titled
: this.$label
}, config
) );
11969 this.fieldWidget
= fieldWidget
;
11971 this.warnings
= [];
11972 this.successMessages
= [];
11974 this.$field
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
11975 this.$messages
= $( '<ul>' );
11976 this.$header
= $( '<span>' );
11977 this.$body
= $( '<div>' );
11979 this.helpInline
= config
.helpInline
;
11982 this.fieldWidget
.connect( this, {
11983 disable
: 'onFieldDisable'
11987 this.$help
= config
.help
?
11988 this.createHelpElement( config
.help
, config
.$overlay
) :
11990 if ( this.fieldWidget
.getInputId() ) {
11991 this.$label
.attr( 'for', this.fieldWidget
.getInputId() );
11992 if ( this.helpInline
) {
11993 this.$help
.attr( 'for', this.fieldWidget
.getInputId() );
11996 this.$label
.on( 'click', function () {
11997 this.fieldWidget
.simulateLabelClick();
11999 if ( this.helpInline
) {
12000 this.$help
.on( 'click', function () {
12001 this.fieldWidget
.simulateLabelClick();
12006 .addClass( 'oo-ui-fieldLayout' )
12007 .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget
.isDisabled() )
12008 .append( this.$body
);
12009 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
12010 this.$header
.addClass( 'oo-ui-fieldLayout-header' );
12011 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
12013 .addClass( 'oo-ui-fieldLayout-field' )
12014 .append( this.fieldWidget
.$element
);
12016 this.setErrors( config
.errors
|| [] );
12017 this.setWarnings( config
.warnings
|| [] );
12018 this.setSuccess( config
.successMessages
|| [] );
12019 this.setNotices( config
.notices
|| [] );
12020 this.setAlignment( config
.align
);
12021 // Call this again to take into account the widget's accessKey
12022 this.updateTitle();
12027 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
12028 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
12029 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
12034 * Handle field disable events.
12037 * @param {boolean} value Field is disabled
12039 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
12040 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
12044 * Get the widget contained by the field.
12046 * @return {OO.ui.Widget} Field widget
12048 OO
.ui
.FieldLayout
.prototype.getField = function () {
12049 return this.fieldWidget
;
12053 * Return `true` if the given field widget can be used with `'inline'` alignment (see
12054 * #setAlignment). Return `false` if it can't or if this can't be determined.
12056 * @return {boolean}
12058 OO
.ui
.FieldLayout
.prototype.isFieldInline = function () {
12059 // This is very simplistic, but should be good enough.
12060 return this.getField().$element
.prop( 'tagName' ).toLowerCase() === 'span';
12065 * @param {string} kind 'error' or 'notice'
12066 * @param {string|OO.ui.HtmlSnippet} text
12069 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
12070 var $listItem
, $icon
, message
;
12071 $listItem
= $( '<li>' );
12072 if ( kind
=== 'error' ) {
12073 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'error' ] } ).$element
;
12074 $listItem
.attr( 'role', 'alert' );
12075 } else if ( kind
=== 'warning' ) {
12076 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
12077 $listItem
.attr( 'role', 'alert' );
12078 } else if ( kind
=== 'success' ) {
12079 $icon
= new OO
.ui
.IconWidget( { icon
: 'check', flags
: [ 'success' ] } ).$element
;
12080 } else if ( kind
=== 'notice' ) {
12081 $icon
= new OO
.ui
.IconWidget( { icon
: 'notice' } ).$element
;
12085 message
= new OO
.ui
.LabelWidget( { label
: text
} );
12087 .append( $icon
, message
.$element
)
12088 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
12093 * Set the field alignment mode.
12096 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
12098 * @return {OO.ui.BookletLayout} The layout, for chaining
12100 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
12101 if ( value
!== this.align
) {
12102 // Default to 'left'
12103 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
12107 if ( value
=== 'inline' && !this.isFieldInline() ) {
12110 // Reorder elements
12112 if ( this.helpInline
) {
12113 if ( value
=== 'top' ) {
12114 this.$header
.append( this.$label
);
12115 this.$body
.append( this.$header
, this.$field
, this.$help
);
12116 } else if ( value
=== 'inline' ) {
12117 this.$header
.append( this.$label
, this.$help
);
12118 this.$body
.append( this.$field
, this.$header
);
12120 this.$header
.append( this.$label
, this.$help
);
12121 this.$body
.append( this.$header
, this.$field
);
12124 if ( value
=== 'top' ) {
12125 this.$header
.append( this.$help
, this.$label
);
12126 this.$body
.append( this.$header
, this.$field
);
12127 } else if ( value
=== 'inline' ) {
12128 this.$header
.append( this.$help
, this.$label
);
12129 this.$body
.append( this.$field
, this.$header
);
12131 this.$header
.append( this.$label
);
12132 this.$body
.append( this.$header
, this.$help
, this.$field
);
12135 // Set classes. The following classes can be used here:
12136 // * oo-ui-fieldLayout-align-left
12137 // * oo-ui-fieldLayout-align-right
12138 // * oo-ui-fieldLayout-align-top
12139 // * oo-ui-fieldLayout-align-inline
12140 if ( this.align
) {
12141 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
12143 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
12144 this.align
= value
;
12151 * Set the list of error messages.
12153 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
12154 * The array may contain strings or OO.ui.HtmlSnippet instances.
12156 * @return {OO.ui.BookletLayout} The layout, for chaining
12158 OO
.ui
.FieldLayout
.prototype.setErrors = function ( errors
) {
12159 this.errors
= errors
.slice();
12160 this.updateMessages();
12165 * Set the list of warning messages.
12167 * @param {Array} warnings Warning messages about the widget, which will be displayed below
12169 * The array may contain strings or OO.ui.HtmlSnippet instances.
12171 * @return {OO.ui.BookletLayout} The layout, for chaining
12173 OO
.ui
.FieldLayout
.prototype.setWarnings = function ( warnings
) {
12174 this.warnings
= warnings
.slice();
12175 this.updateMessages();
12180 * Set the list of success messages.
12182 * @param {Array} successMessages Success messages about the widget, which will be displayed below
12184 * The array may contain strings or OO.ui.HtmlSnippet instances.
12186 * @return {OO.ui.BookletLayout} The layout, for chaining
12188 OO
.ui
.FieldLayout
.prototype.setSuccess = function ( successMessages
) {
12189 this.successMessages
= successMessages
.slice();
12190 this.updateMessages();
12195 * Set the list of notice messages.
12197 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
12198 * The array may contain strings or OO.ui.HtmlSnippet instances.
12200 * @return {OO.ui.BookletLayout} The layout, for chaining
12202 OO
.ui
.FieldLayout
.prototype.setNotices = function ( notices
) {
12203 this.notices
= notices
.slice();
12204 this.updateMessages();
12209 * Update the rendering of error, warning, success and notice messages.
12213 OO
.ui
.FieldLayout
.prototype.updateMessages = function () {
12215 this.$messages
.empty();
12218 this.errors
.length
||
12219 this.warnings
.length
||
12220 this.successMessages
.length
||
12221 this.notices
.length
12223 this.$body
.after( this.$messages
);
12225 this.$messages
.remove();
12229 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
12230 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
12232 for ( i
= 0; i
< this.warnings
.length
; i
++ ) {
12233 this.$messages
.append( this.makeMessage( 'warning', this.warnings
[ i
] ) );
12235 for ( i
= 0; i
< this.successMessages
.length
; i
++ ) {
12236 this.$messages
.append( this.makeMessage( 'success', this.successMessages
[ i
] ) );
12238 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
12239 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
12244 * Include information about the widget's accessKey in our title. TitledElement calls this method.
12245 * (This is a bit of a hack.)
12248 * @param {string} title Tooltip label for 'title' attribute
12251 OO
.ui
.FieldLayout
.prototype.formatTitleWithAccessKey = function ( title
) {
12252 if ( this.fieldWidget
&& this.fieldWidget
.formatTitleWithAccessKey
) {
12253 return this.fieldWidget
.formatTitleWithAccessKey( title
);
12259 * Creates and returns the help element. Also sets the `aria-describedby`
12260 * attribute on the main element of the `fieldWidget`.
12263 * @param {string|OO.ui.HtmlSnippet} [help] Help text.
12264 * @param {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup.
12265 * @return {jQuery} The element that should become `this.$help`.
12267 OO
.ui
.FieldLayout
.prototype.createHelpElement = function ( help
, $overlay
) {
12268 var helpId
, helpWidget
;
12270 if ( this.helpInline
) {
12271 helpWidget
= new OO
.ui
.LabelWidget( {
12273 classes
: [ 'oo-ui-inline-help' ]
12276 helpId
= helpWidget
.getElementId();
12278 helpWidget
= new OO
.ui
.PopupButtonWidget( {
12279 $overlay
: $overlay
,
12283 classes
: [ 'oo-ui-fieldLayout-help' ],
12286 label
: OO
.ui
.msg( 'ooui-field-help' ),
12287 invisibleLabel
: true
12289 if ( help
instanceof OO
.ui
.HtmlSnippet
) {
12290 helpWidget
.getPopup().$body
.html( help
.toString() );
12292 helpWidget
.getPopup().$body
.text( help
);
12295 helpId
= helpWidget
.getPopup().getBodyId();
12298 // Set the 'aria-describedby' attribute on the fieldWidget
12299 // Preference given to an input or a button
12301 this.fieldWidget
.$input
||
12302 this.fieldWidget
.$button
||
12303 this.fieldWidget
.$element
12304 ).attr( 'aria-describedby', helpId
);
12306 return helpWidget
.$element
;
12310 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget,
12311 * a button, and an optional label and/or help text. The field-widget (e.g., a
12312 * {@link OO.ui.TextInputWidget TextInputWidget}), is required and is specified before any optional
12313 * configuration settings.
12315 * Labels can be aligned in one of four ways:
12317 * - **left**: The label is placed before the field-widget and aligned with the left margin.
12318 * A left-alignment is used for forms with many fields.
12319 * - **right**: The label is placed before the field-widget and aligned to the right margin.
12320 * A right-alignment is used for long but familiar forms which users tab through,
12321 * verifying the current field with a quick glance at the label.
12322 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
12323 * that users fill out from top to bottom.
12324 * - **inline**: The label is placed after the field-widget and aligned to the left.
12325 * An inline-alignment is best used with checkboxes or radio buttons.
12327 * Help text is accessed via a help icon that appears in the upper right corner of the rendered
12328 * field layout when help text is specified.
12331 * // Example of an ActionFieldLayout
12332 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
12333 * new OO.ui.TextInputWidget( {
12334 * placeholder: 'Field widget'
12336 * new OO.ui.ButtonWidget( {
12340 * label: 'An ActionFieldLayout. This label is aligned top',
12342 * help: 'This is help text'
12346 * $( document.body ).append( actionFieldLayout.$element );
12349 * @extends OO.ui.FieldLayout
12352 * @param {OO.ui.Widget} fieldWidget Field widget
12353 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
12354 * @param {Object} config
12356 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
12357 // Allow passing positional parameters inside the config object
12358 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
12359 config
= fieldWidget
;
12360 fieldWidget
= config
.fieldWidget
;
12361 buttonWidget
= config
.buttonWidget
;
12364 // Parent constructor
12365 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
12368 this.buttonWidget
= buttonWidget
;
12369 this.$button
= $( '<span>' );
12370 this.$input
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
12373 this.$element
.addClass( 'oo-ui-actionFieldLayout' );
12375 .addClass( 'oo-ui-actionFieldLayout-button' )
12376 .append( this.buttonWidget
.$element
);
12378 .addClass( 'oo-ui-actionFieldLayout-input' )
12379 .append( this.fieldWidget
.$element
);
12380 this.$field
.append( this.$input
, this.$button
);
12385 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
12388 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
12389 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
12390 * configured with a label as well. For more information and examples,
12391 * please see the [OOUI documentation on MediaWiki][1].
12394 * // Example of a fieldset layout
12395 * var input1 = new OO.ui.TextInputWidget( {
12396 * placeholder: 'A text input field'
12399 * var input2 = new OO.ui.TextInputWidget( {
12400 * placeholder: 'A text input field'
12403 * var fieldset = new OO.ui.FieldsetLayout( {
12404 * label: 'Example of a fieldset layout'
12407 * fieldset.addItems( [
12408 * new OO.ui.FieldLayout( input1, {
12409 * label: 'Field One'
12411 * new OO.ui.FieldLayout( input2, {
12412 * label: 'Field Two'
12415 * $( document.body ).append( fieldset.$element );
12417 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
12420 * @extends OO.ui.Layout
12421 * @mixins OO.ui.mixin.IconElement
12422 * @mixins OO.ui.mixin.LabelElement
12423 * @mixins OO.ui.mixin.GroupElement
12426 * @param {Object} [config] Configuration options
12427 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset.
12428 * See OO.ui.FieldLayout for more information about fields.
12429 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon
12430 * will appear in the upper-right corner of the rendered field; clicking it will display the text
12431 * in a popup. For important messages, you are advised to use `notices`, as they are always shown.
12432 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
12433 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
12435 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
12436 // Configuration initialization
12437 config
= config
|| {};
12439 // Parent constructor
12440 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
12442 // Mixin constructors
12443 OO
.ui
.mixin
.IconElement
.call( this, config
);
12444 OO
.ui
.mixin
.LabelElement
.call( this, config
);
12445 OO
.ui
.mixin
.GroupElement
.call( this, config
);
12448 this.$header
= $( '<legend>' );
12449 if ( config
.help
) {
12450 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
12451 $overlay
: config
.$overlay
,
12455 classes
: [ 'oo-ui-fieldsetLayout-help' ],
12458 label
: OO
.ui
.msg( 'ooui-field-help' ),
12459 invisibleLabel
: true
12461 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
12462 this.popupButtonWidget
.getPopup().$body
.html( config
.help
.toString() );
12464 this.popupButtonWidget
.getPopup().$body
.text( config
.help
);
12466 this.$help
= this.popupButtonWidget
.$element
;
12468 this.$help
= $( [] );
12473 .addClass( 'oo-ui-fieldsetLayout-header' )
12474 .append( this.$icon
, this.$label
, this.$help
);
12475 this.$group
.addClass( 'oo-ui-fieldsetLayout-group' );
12477 .addClass( 'oo-ui-fieldsetLayout' )
12478 .prepend( this.$header
, this.$group
);
12479 if ( Array
.isArray( config
.items
) ) {
12480 this.addItems( config
.items
);
12486 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
12487 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
12488 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
12489 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
12491 /* Static Properties */
12497 OO
.ui
.FieldsetLayout
.static.tagName
= 'fieldset';
12500 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use
12501 * browser-based form submission for the fields instead of handling them in JavaScript. Form layouts
12502 * can be configured with an HTML form action, an encoding type, and a method using the #action,
12503 * #enctype, and #method configs, respectively.
12504 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
12506 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
12507 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
12508 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
12509 * some fancier controls. Some controls have both regular and InputWidget variants, for example
12510 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
12511 * often have simplified APIs to match the capabilities of HTML forms.
12512 * See the [OOUI documentation on MediaWiki] [2] for more information about InputWidgets.
12514 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Forms
12515 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
12518 * // Example of a form layout that wraps a fieldset layout.
12519 * var input1 = new OO.ui.TextInputWidget( {
12520 * placeholder: 'Username'
12522 * input2 = new OO.ui.TextInputWidget( {
12523 * placeholder: 'Password',
12526 * submit = new OO.ui.ButtonInputWidget( {
12529 * fieldset = new OO.ui.FieldsetLayout( {
12530 * label: 'A form layout'
12533 * fieldset.addItems( [
12534 * new OO.ui.FieldLayout( input1, {
12535 * label: 'Username',
12538 * new OO.ui.FieldLayout( input2, {
12539 * label: 'Password',
12542 * new OO.ui.FieldLayout( submit )
12544 * var form = new OO.ui.FormLayout( {
12545 * items: [ fieldset ],
12546 * action: '/api/formhandler',
12549 * $( document.body ).append( form.$element );
12552 * @extends OO.ui.Layout
12553 * @mixins OO.ui.mixin.GroupElement
12556 * @param {Object} [config] Configuration options
12557 * @cfg {string} [method] HTML form `method` attribute
12558 * @cfg {string} [action] HTML form `action` attribute
12559 * @cfg {string} [enctype] HTML form `enctype` attribute
12560 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
12562 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
12565 // Configuration initialization
12566 config
= config
|| {};
12568 // Parent constructor
12569 OO
.ui
.FormLayout
.parent
.call( this, config
);
12571 // Mixin constructors
12572 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( { $group
: this.$element
}, config
) );
12575 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
12577 // Make sure the action is safe
12578 action
= config
.action
;
12579 if ( action
!== undefined && !OO
.ui
.isSafeUrl( action
) ) {
12580 action
= './' + action
;
12585 .addClass( 'oo-ui-formLayout' )
12587 method
: config
.method
,
12589 enctype
: config
.enctype
12591 if ( Array
.isArray( config
.items
) ) {
12592 this.addItems( config
.items
);
12598 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
12599 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
12604 * A 'submit' event is emitted when the form is submitted.
12609 /* Static Properties */
12615 OO
.ui
.FormLayout
.static.tagName
= 'form';
12620 * Handle form submit events.
12623 * @param {jQuery.Event} e Submit event
12625 * @return {OO.ui.FormLayout} The layout, for chaining
12627 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
12628 if ( this.emit( 'submit' ) ) {
12634 * PanelLayouts expand to cover the entire area of their parent. They can be configured with
12635 * scrolling, padding, and a frame, and are often used together with
12636 * {@link OO.ui.StackLayout StackLayouts}.
12639 * // Example of a panel layout
12640 * var panel = new OO.ui.PanelLayout( {
12644 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
12646 * $( document.body ).append( panel.$element );
12649 * @extends OO.ui.Layout
12652 * @param {Object} [config] Configuration options
12653 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
12654 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
12655 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
12656 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside
12659 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
12660 // Configuration initialization
12661 config
= $.extend( {
12668 // Parent constructor
12669 OO
.ui
.PanelLayout
.parent
.call( this, config
);
12672 this.$element
.addClass( 'oo-ui-panelLayout' );
12673 if ( config
.scrollable
) {
12674 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
12676 if ( config
.padded
) {
12677 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
12679 if ( config
.expanded
) {
12680 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
12682 if ( config
.framed
) {
12683 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
12689 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
12691 /* Static Methods */
12696 OO
.ui
.PanelLayout
.static.reusePreInfuseDOM = function ( node
, config
) {
12697 config
= OO
.ui
.PanelLayout
.parent
.static.reusePreInfuseDOM( node
, config
);
12698 if ( config
.preserveContent
!== false ) {
12699 config
.$content
= $( node
).contents();
12707 * Focus the panel layout
12709 * The default implementation just focuses the first focusable element in the panel
12711 OO
.ui
.PanelLayout
.prototype.focus = function () {
12712 OO
.ui
.findFocusable( this.$element
).focus();
12716 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
12717 * items), with small margins between them. Convenient when you need to put a number of block-level
12718 * widgets on a single line next to each other.
12720 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
12723 * // HorizontalLayout with a text input and a label.
12724 * var layout = new OO.ui.HorizontalLayout( {
12726 * new OO.ui.LabelWidget( { label: 'Label' } ),
12727 * new OO.ui.TextInputWidget( { value: 'Text' } )
12730 * $( document.body ).append( layout.$element );
12733 * @extends OO.ui.Layout
12734 * @mixins OO.ui.mixin.GroupElement
12737 * @param {Object} [config] Configuration options
12738 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
12740 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
12741 // Configuration initialization
12742 config
= config
|| {};
12744 // Parent constructor
12745 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
12747 // Mixin constructors
12748 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( { $group
: this.$element
}, config
) );
12751 this.$element
.addClass( 'oo-ui-horizontalLayout' );
12752 if ( Array
.isArray( config
.items
) ) {
12753 this.addItems( config
.items
);
12759 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
12760 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);
12763 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
12764 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
12765 * (to adjust the value in increments) to allow the user to enter a number.
12768 * // A NumberInputWidget.
12769 * var numberInput = new OO.ui.NumberInputWidget( {
12770 * label: 'NumberInputWidget',
12771 * input: { value: 5 },
12775 * $( document.body ).append( numberInput.$element );
12778 * @extends OO.ui.TextInputWidget
12781 * @param {Object} [config] Configuration options
12782 * @cfg {Object} [minusButton] Configuration options to pass to the
12783 * {@link OO.ui.ButtonWidget decrementing button widget}.
12784 * @cfg {Object} [plusButton] Configuration options to pass to the
12785 * {@link OO.ui.ButtonWidget incrementing button widget}.
12786 * @cfg {number} [min=-Infinity] Minimum allowed value
12787 * @cfg {number} [max=Infinity] Maximum allowed value
12788 * @cfg {number|null} [step] If specified, the field only accepts values that are multiples of this.
12789 * @cfg {number} [buttonStep=step||1] Delta when using the buttons or Up/Down arrow keys.
12790 * Defaults to `step` if specified, otherwise `1`.
12791 * @cfg {number} [pageStep=10*buttonStep] Delta when using the Page-up/Page-down keys.
12792 * Defaults to 10 times `buttonStep`.
12793 * @cfg {boolean} [showButtons=true] Whether to show the plus and minus buttons.
12795 OO
.ui
.NumberInputWidget
= function OoUiNumberInputWidget( config
) {
12796 var $field
= $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' );
12798 // Configuration initialization
12799 config
= $.extend( {
12805 // For backward compatibility
12806 $.extend( config
, config
.input
);
12809 // Parent constructor
12810 OO
.ui
.NumberInputWidget
.parent
.call( this, $.extend( config
, {
12814 if ( config
.showButtons
) {
12815 this.minusButton
= new OO
.ui
.ButtonWidget( $.extend(
12817 disabled
: this.isDisabled(),
12819 classes
: [ 'oo-ui-numberInputWidget-minusButton' ],
12824 this.minusButton
.$element
.attr( 'aria-hidden', 'true' );
12825 this.plusButton
= new OO
.ui
.ButtonWidget( $.extend(
12827 disabled
: this.isDisabled(),
12829 classes
: [ 'oo-ui-numberInputWidget-plusButton' ],
12834 this.plusButton
.$element
.attr( 'aria-hidden', 'true' );
12839 keydown
: this.onKeyDown
.bind( this ),
12840 'wheel mousewheel DOMMouseScroll': this.onWheel
.bind( this )
12842 if ( config
.showButtons
) {
12843 this.plusButton
.connect( this, {
12844 click
: [ 'onButtonClick', +1 ]
12846 this.minusButton
.connect( this, {
12847 click
: [ 'onButtonClick', -1 ]
12852 $field
.append( this.$input
);
12853 if ( config
.showButtons
) {
12855 .prepend( this.minusButton
.$element
)
12856 .append( this.plusButton
.$element
);
12860 if ( config
.allowInteger
|| config
.isInteger
) {
12861 // Backward compatibility
12864 this.setRange( config
.min
, config
.max
);
12865 this.setStep( config
.buttonStep
, config
.pageStep
, config
.step
);
12866 // Set the validation method after we set step and range
12867 // so that it doesn't immediately call setValidityFlag
12868 this.setValidation( this.validateNumber
.bind( this ) );
12871 .addClass( 'oo-ui-numberInputWidget' )
12872 .toggleClass( 'oo-ui-numberInputWidget-buttoned', config
.showButtons
)
12878 OO
.inheritClass( OO
.ui
.NumberInputWidget
, OO
.ui
.TextInputWidget
);
12882 // Backward compatibility
12883 OO
.ui
.NumberInputWidget
.prototype.setAllowInteger = function ( flag
) {
12884 this.setStep( flag
? 1 : null );
12886 // Backward compatibility
12887 OO
.ui
.NumberInputWidget
.prototype.setIsInteger
= OO
.ui
.NumberInputWidget
.prototype.setAllowInteger
;
12889 // Backward compatibility
12890 OO
.ui
.NumberInputWidget
.prototype.getAllowInteger = function () {
12891 return this.step
=== 1;
12893 // Backward compatibility
12894 OO
.ui
.NumberInputWidget
.prototype.getIsInteger
= OO
.ui
.NumberInputWidget
.prototype.getAllowInteger
;
12897 * Set the range of allowed values
12899 * @param {number} min Minimum allowed value
12900 * @param {number} max Maximum allowed value
12902 OO
.ui
.NumberInputWidget
.prototype.setRange = function ( min
, max
) {
12904 throw new Error( 'Minimum (' + min
+ ') must not be greater than maximum (' + max
+ ')' );
12908 this.$input
.attr( 'min', this.min
);
12909 this.$input
.attr( 'max', this.max
);
12910 this.setValidityFlag();
12914 * Get the current range
12916 * @return {number[]} Minimum and maximum values
12918 OO
.ui
.NumberInputWidget
.prototype.getRange = function () {
12919 return [ this.min
, this.max
];
12923 * Set the stepping deltas
12925 * @param {number} [buttonStep=step||1] Delta when using the buttons or up/down arrow keys.
12926 * Defaults to `step` if specified, otherwise `1`.
12927 * @param {number} [pageStep=10*buttonStep] Delta when using the page-up/page-down keys.
12928 * Defaults to 10 times `buttonStep`.
12929 * @param {number|null} [step] If specified, the field only accepts values that are multiples
12932 OO
.ui
.NumberInputWidget
.prototype.setStep = function ( buttonStep
, pageStep
, step
) {
12933 if ( buttonStep
=== undefined ) {
12934 buttonStep
= step
|| 1;
12936 if ( pageStep
=== undefined ) {
12937 pageStep
= 10 * buttonStep
;
12939 if ( step
!== null && step
<= 0 ) {
12940 throw new Error( 'Step value, if given, must be positive' );
12942 if ( buttonStep
<= 0 ) {
12943 throw new Error( 'Button step value must be positive' );
12945 if ( pageStep
<= 0 ) {
12946 throw new Error( 'Page step value must be positive' );
12949 this.buttonStep
= buttonStep
;
12950 this.pageStep
= pageStep
;
12951 this.$input
.attr( 'step', this.step
|| 'any' );
12952 this.setValidityFlag();
12958 OO
.ui
.NumberInputWidget
.prototype.setValue = function ( value
) {
12959 if ( value
=== '' ) {
12960 // Some browsers allow a value in the input even if there isn't one reported by $input.val()
12961 // so here we make sure an 'empty' value is actually displayed as such.
12962 this.$input
.val( '' );
12964 return OO
.ui
.NumberInputWidget
.parent
.prototype.setValue
.call( this, value
);
12968 * Get the current stepping values
12970 * @return {number[]} Button step, page step, and validity step
12972 OO
.ui
.NumberInputWidget
.prototype.getStep = function () {
12973 return [ this.buttonStep
, this.pageStep
, this.step
];
12977 * Get the current value of the widget as a number
12979 * @return {number} May be NaN, or an invalid number
12981 OO
.ui
.NumberInputWidget
.prototype.getNumericValue = function () {
12982 return +this.getValue();
12986 * Adjust the value of the widget
12988 * @param {number} delta Adjustment amount
12990 OO
.ui
.NumberInputWidget
.prototype.adjustValue = function ( delta
) {
12991 var n
, v
= this.getNumericValue();
12994 if ( isNaN( delta
) || !isFinite( delta
) ) {
12995 throw new Error( 'Delta must be a finite number' );
12998 if ( isNaN( v
) ) {
13002 n
= Math
.max( Math
.min( n
, this.max
), this.min
);
13004 n
= Math
.round( n
/ this.step
) * this.step
;
13009 this.setValue( n
);
13016 * @param {string} value Field value
13017 * @return {boolean}
13019 OO
.ui
.NumberInputWidget
.prototype.validateNumber = function ( value
) {
13021 if ( value
=== '' ) {
13022 return !this.isRequired();
13025 if ( isNaN( n
) || !isFinite( n
) ) {
13029 if ( this.step
&& Math
.floor( n
/ this.step
) !== n
/ this.step
) {
13033 if ( n
< this.min
|| n
> this.max
) {
13041 * Handle mouse click events.
13044 * @param {number} dir +1 or -1
13046 OO
.ui
.NumberInputWidget
.prototype.onButtonClick = function ( dir
) {
13047 this.adjustValue( dir
* this.buttonStep
);
13051 * Handle mouse wheel events.
13054 * @param {jQuery.Event} event
13055 * @return {undefined|boolean} False to prevent default if event is handled
13057 OO
.ui
.NumberInputWidget
.prototype.onWheel = function ( event
) {
13060 if ( this.isDisabled() || this.isReadOnly() ) {
13064 if ( this.$input
.is( ':focus' ) ) {
13065 // Standard 'wheel' event
13066 if ( event
.originalEvent
.deltaMode
!== undefined ) {
13067 this.sawWheelEvent
= true;
13069 if ( event
.originalEvent
.deltaY
) {
13070 delta
= -event
.originalEvent
.deltaY
;
13071 } else if ( event
.originalEvent
.deltaX
) {
13072 delta
= event
.originalEvent
.deltaX
;
13075 // Non-standard events
13076 if ( !this.sawWheelEvent
) {
13077 if ( event
.originalEvent
.wheelDeltaX
) {
13078 delta
= -event
.originalEvent
.wheelDeltaX
;
13079 } else if ( event
.originalEvent
.wheelDeltaY
) {
13080 delta
= event
.originalEvent
.wheelDeltaY
;
13081 } else if ( event
.originalEvent
.wheelDelta
) {
13082 delta
= event
.originalEvent
.wheelDelta
;
13083 } else if ( event
.originalEvent
.detail
) {
13084 delta
= -event
.originalEvent
.detail
;
13089 delta
= delta
< 0 ? -1 : 1;
13090 this.adjustValue( delta
* this.buttonStep
);
13098 * Handle key down events.
13101 * @param {jQuery.Event} e Key down event
13102 * @return {undefined|boolean} False to prevent default if event is handled
13104 OO
.ui
.NumberInputWidget
.prototype.onKeyDown = function ( e
) {
13105 if ( this.isDisabled() || this.isReadOnly() ) {
13109 switch ( e
.which
) {
13110 case OO
.ui
.Keys
.UP
:
13111 this.adjustValue( this.buttonStep
);
13113 case OO
.ui
.Keys
.DOWN
:
13114 this.adjustValue( -this.buttonStep
);
13116 case OO
.ui
.Keys
.PAGEUP
:
13117 this.adjustValue( this.pageStep
);
13119 case OO
.ui
.Keys
.PAGEDOWN
:
13120 this.adjustValue( -this.pageStep
);
13126 * Update the disabled state of the controls
13130 * @return {OO.ui.NumberInputWidget} The widget, for chaining
13132 OO
.ui
.NumberInputWidget
.prototype.updateControlsDisabled = function () {
13133 var disabled
= this.isDisabled() || this.isReadOnly();
13134 if ( this.minusButton
) {
13135 this.minusButton
.setDisabled( disabled
);
13137 if ( this.plusButton
) {
13138 this.plusButton
.setDisabled( disabled
);
13146 OO
.ui
.NumberInputWidget
.prototype.setDisabled = function ( disabled
) {
13148 OO
.ui
.NumberInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
13149 this.updateControlsDisabled();
13156 OO
.ui
.NumberInputWidget
.prototype.setReadOnly = function () {
13158 OO
.ui
.NumberInputWidget
.parent
.prototype.setReadOnly
.apply( this, arguments
);
13159 this.updateControlsDisabled();
13164 * SelectFileInputWidgets allow for selecting files, using <input type="file">. These
13165 * widgets can be configured with {@link OO.ui.mixin.IconElement icons}, {@link
13166 * OO.ui.mixin.IndicatorElement indicators} and {@link OO.ui.mixin.TitledElement titles}.
13167 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
13169 * SelectFileInputWidgets must be used in HTML forms, as getValue only returns the filename.
13172 * // A file select input widget.
13173 * var selectFile = new OO.ui.SelectFileInputWidget();
13174 * $( document.body ).append( selectFile.$element );
13176 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets
13179 * @extends OO.ui.InputWidget
13182 * @param {Object} [config] Configuration options
13183 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
13184 * @cfg {boolean} [multiple=false] Allow multiple files to be selected.
13185 * @cfg {string} [placeholder] Text to display when no file is selected.
13186 * @cfg {Object} [button] Config to pass to select file button.
13187 * @cfg {string} [icon] Icon to show next to file info
13189 OO
.ui
.SelectFileInputWidget
= function OoUiSelectFileInputWidget( config
) {
13192 config
= config
|| {};
13194 // Construct buttons before parent method is called (calling setDisabled)
13195 this.selectButton
= new OO
.ui
.ButtonWidget( $.extend( {
13196 $element
: $( '<label>' ),
13197 classes
: [ 'oo-ui-selectFileInputWidget-selectButton' ],
13198 label
: OO
.ui
.msg( 'ooui-selectfile-button-select' )
13199 }, config
.button
) );
13201 // Configuration initialization
13202 config
= $.extend( {
13204 placeholder
: OO
.ui
.msg( 'ooui-selectfile-placeholder' ),
13205 $tabIndexed
: this.selectButton
.$tabIndexed
13208 this.info
= new OO
.ui
.SearchInputWidget( {
13209 classes
: [ 'oo-ui-selectFileInputWidget-info' ],
13210 placeholder
: config
.placeholder
,
13211 // Pass an empty collection so that .focus() always does nothing
13212 $tabIndexed
: $( [] )
13213 } ).setIcon( config
.icon
);
13214 // Set tabindex manually on $input as $tabIndexed has been overridden
13215 this.info
.$input
.attr( 'tabindex', -1 );
13217 // Parent constructor
13218 OO
.ui
.SelectFileInputWidget
.parent
.call( this, config
);
13221 this.currentFiles
= this.filterFiles( this.$input
[ 0 ].files
|| [] );
13222 if ( Array
.isArray( config
.accept
) ) {
13223 this.accept
= config
.accept
;
13225 this.accept
= null;
13227 this.multiple
= !!config
.multiple
;
13230 this.info
.connect( this, { change
: 'onInfoChange' } );
13231 this.selectButton
.$button
.on( {
13232 keypress
: this.onKeyPress
.bind( this )
13235 change
: this.onFileSelected
.bind( this ),
13237 // In IE 11, focussing a file input (by clicking on it) displays a text cursor and scrolls
13238 // the cursor into view (in this case, it scrolls the button, which has 'overflow: hidden').
13239 // Since this messes with our custom styling (the file input has large dimensions and this
13240 // causes the label to scroll out of view), scroll the button back to top. (T192131)
13241 focus: function () {
13242 widget
.$input
.parent().prop( 'scrollTop', 0 );
13245 this.connect( this, { change
: 'updateUI' } );
13247 this.fieldLayout
= new OO
.ui
.ActionFieldLayout( this.info
, this.selectButton
, { align
: 'top' } );
13252 // this.selectButton is tabindexed
13254 // Infused input may have previously by
13255 // TabIndexed, so remove aria-disabled attr.
13256 'aria-disabled': null
13259 if ( this.accept
) {
13260 this.$input
.attr( 'accept', this.accept
.join( ', ' ) );
13262 if ( this.multiple
) {
13263 this.$input
.attr( 'multiple', '' );
13265 this.selectButton
.$button
.append( this.$input
);
13268 .addClass( 'oo-ui-selectFileInputWidget' )
13269 .append( this.fieldLayout
.$element
);
13276 OO
.inheritClass( OO
.ui
.SelectFileInputWidget
, OO
.ui
.InputWidget
);
13278 /* Static properties */
13280 // Set empty title so that browser default tooltips like "No file chosen" don't appear.
13281 // On SelectFileWidget this tooltip will often be incorrect, so create a consistent
13282 // experience on SelectFileInputWidget.
13283 OO
.ui
.SelectFileInputWidget
.static.title
= '';
13288 * Get the filename of the currently selected file.
13290 * @return {string} Filename
13292 OO
.ui
.SelectFileInputWidget
.prototype.getFilename = function () {
13293 if ( this.currentFiles
.length
) {
13294 return this.currentFiles
.map( function ( file
) {
13298 // Try to strip leading fakepath.
13299 return this.getValue().split( '\\' ).pop();
13306 OO
.ui
.SelectFileInputWidget
.prototype.setValue = function ( value
) {
13307 if ( value
=== undefined ) {
13308 // Called during init, don't replace value if just infusing.
13312 // We need to update this.value, but without trying to modify
13313 // the DOM value, which would throw an exception.
13314 if ( this.value
!== value
) {
13315 this.value
= value
;
13316 this.emit( 'change', this.value
);
13319 this.currentFiles
= [];
13321 OO
.ui
.SelectFileInputWidget
.super.prototype.setValue
.call( this, '' );
13326 * Handle file selection from the input.
13329 * @param {jQuery.Event} e
13331 OO
.ui
.SelectFileInputWidget
.prototype.onFileSelected = function ( e
) {
13332 this.currentFiles
= this.filterFiles( e
.target
.files
|| [] );
13336 * Update the user interface when a file is selected or unselected.
13340 OO
.ui
.SelectFileInputWidget
.prototype.updateUI = function () {
13341 this.info
.setValue( this.getFilename() );
13345 * Determine if we should accept this file.
13348 * @param {FileList|File[]} files Files to filter
13349 * @return {File[]} Filter files
13351 OO
.ui
.SelectFileInputWidget
.prototype.filterFiles = function ( files
) {
13352 var accept
= this.accept
;
13354 function mimeAllowed( file
) {
13356 mimeType
= file
.type
;
13358 if ( !accept
|| !mimeType
) {
13362 for ( i
= 0; i
< accept
.length
; i
++ ) {
13363 mimeTest
= accept
[ i
];
13364 if ( mimeTest
=== mimeType
) {
13366 } else if ( mimeTest
.substr( -2 ) === '/*' ) {
13367 mimeTest
= mimeTest
.substr( 0, mimeTest
.length
- 1 );
13368 if ( mimeType
.substr( 0, mimeTest
.length
) === mimeTest
) {
13376 return Array
.prototype.filter
.call( files
, mimeAllowed
);
13380 * Handle info input change events
13382 * The info widget can only be changed by the user
13383 * with the clear button.
13386 * @param {string} value
13388 OO
.ui
.SelectFileInputWidget
.prototype.onInfoChange = function ( value
) {
13389 if ( value
=== '' ) {
13390 this.setValue( null );
13395 * Handle key press events.
13398 * @param {jQuery.Event} e Key press event
13399 * @return {undefined|boolean} False to prevent default if event is handled
13401 OO
.ui
.SelectFileInputWidget
.prototype.onKeyPress = function ( e
) {
13402 if ( !this.isDisabled() && this.$input
&&
13403 ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
13405 // Emit a click to open the file selector.
13406 this.$input
.trigger( 'click' );
13407 // Taking focus from the selectButton means keyUp isn't fired, so fire it manually.
13408 this.selectButton
.onDocumentKeyUp( e
);
13416 OO
.ui
.SelectFileInputWidget
.prototype.setDisabled = function ( disabled
) {
13418 OO
.ui
.SelectFileInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
13420 this.selectButton
.setDisabled( disabled
);
13421 this.info
.setDisabled( disabled
);
13428 //# sourceMappingURL=oojs-ui-core.js.map.json