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-02-21T10:57:07Z
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, otherwise only match descendants
215 * @return {boolean} The node is in the list of target nodes
217 OO
.ui
.contains = function ( containers
, contained
, matchContainers
) {
219 if ( !Array
.isArray( containers
) ) {
220 containers
= [ containers
];
222 for ( i
= containers
.length
- 1; i
>= 0; i
-- ) {
223 if ( ( matchContainers
&& contained
=== containers
[ i
] ) || $.contains( containers
[ i
], contained
) ) {
231 * Return a function, that, as long as it continues to be invoked, will not
232 * be triggered. The function will be called after it stops being called for
233 * N milliseconds. If `immediate` is passed, trigger the function on the
234 * leading edge, instead of the trailing.
236 * Ported from: http://underscorejs.org/underscore.js
238 * @param {Function} func Function to debounce
239 * @param {number} [wait=0] Wait period in milliseconds
240 * @param {boolean} [immediate] Trigger on leading edge
241 * @return {Function} Debounced function
243 OO
.ui
.debounce = function ( func
, wait
, immediate
) {
248 later = function () {
251 func
.apply( context
, args
);
254 if ( immediate
&& !timeout
) {
255 func
.apply( context
, args
);
257 if ( !timeout
|| wait
) {
258 clearTimeout( timeout
);
259 timeout
= setTimeout( later
, wait
);
265 * Puts a console warning with provided message.
267 * @param {string} message Message
269 OO
.ui
.warnDeprecation = function ( message
) {
270 if ( OO
.getProp( window
, 'console', 'warn' ) !== undefined ) {
271 // eslint-disable-next-line no-console
272 console
.warn( message
);
277 * Returns a function, that, when invoked, will only be triggered at most once
278 * during a given window of time. If called again during that window, it will
279 * wait until the window ends and then trigger itself again.
281 * As it's not knowable to the caller whether the function will actually run
282 * when the wrapper is called, return values from the function are entirely
285 * @param {Function} func Function to throttle
286 * @param {number} wait Throttle window length, in milliseconds
287 * @return {Function} Throttled function
289 OO
.ui
.throttle = function ( func
, wait
) {
290 var context
, args
, timeout
,
294 previous
= OO
.ui
.now();
295 func
.apply( context
, args
);
298 // Check how long it's been since the last time the function was
299 // called, and whether it's more or less than the requested throttle
300 // period. If it's less, run the function immediately. If it's more,
301 // set a timeout for the remaining time -- but don't replace an
302 // existing timeout, since that'd indefinitely prolong the wait.
303 var remaining
= wait
- ( OO
.ui
.now() - previous
);
306 if ( remaining
<= 0 ) {
307 // Note: unless wait was ridiculously large, this means we'll
308 // automatically run the first time the function was called in a
309 // given period. (If you provide a wait period larger than the
310 // current Unix timestamp, you *deserve* unexpected behavior.)
311 clearTimeout( timeout
);
313 } else if ( !timeout
) {
314 timeout
= setTimeout( run
, remaining
);
320 * A (possibly faster) way to get the current timestamp as an integer
322 * @return {number} Current timestamp, in milliseconds since the Unix epoch
324 OO
.ui
.now
= Date
.now
|| function () {
325 return new Date().getTime();
329 * Reconstitute a JavaScript object corresponding to a widget created by
330 * the PHP implementation.
332 * This is an alias for `OO.ui.Element.static.infuse()`.
334 * @param {string|HTMLElement|jQuery} idOrNode
335 * A DOM id (if a string) or node for the widget to infuse.
336 * @param {Object} [config] Configuration options
337 * @return {OO.ui.Element}
338 * The `OO.ui.Element` corresponding to this (infusable) document node.
340 OO
.ui
.infuse = function ( idOrNode
, config
) {
341 return OO
.ui
.Element
.static.infuse( idOrNode
, config
);
346 * Message store for the default implementation of OO.ui.msg
348 * Environments that provide a localization system should not use this, but should override
349 * OO.ui.msg altogether.
354 // Tool tip for a button that moves items in a list down one place
355 'ooui-outline-control-move-down': 'Move item down',
356 // Tool tip for a button that moves items in a list up one place
357 'ooui-outline-control-move-up': 'Move item up',
358 // Tool tip for a button that removes items from a list
359 'ooui-outline-control-remove': 'Remove item',
360 // Label for the toolbar group that contains a list of all other available tools
361 'ooui-toolbar-more': 'More',
362 // Label for the fake tool that expands the full list of tools in a toolbar group
363 'ooui-toolgroup-expand': 'More',
364 // Label for the fake tool that collapses the full list of tools in a toolbar group
365 'ooui-toolgroup-collapse': 'Fewer',
366 // Default label for the tooltip for the button that removes a tag item
367 'ooui-item-remove': 'Remove',
368 // Default label for the accept button of a confirmation dialog
369 'ooui-dialog-message-accept': 'OK',
370 // Default label for the reject button of a confirmation dialog
371 'ooui-dialog-message-reject': 'Cancel',
372 // Title for process dialog error description
373 'ooui-dialog-process-error': 'Something went wrong',
374 // Label for process dialog dismiss error button, visible when describing errors
375 'ooui-dialog-process-dismiss': 'Dismiss',
376 // Label for process dialog retry action button, visible when describing only recoverable errors
377 'ooui-dialog-process-retry': 'Try again',
378 // Label for process dialog retry action button, visible when describing only warnings
379 'ooui-dialog-process-continue': 'Continue',
380 // Label for button in combobox input that triggers its dropdown
381 'ooui-combobox-button-label': 'Dropdown for combobox',
382 // Label for the file selection widget's select file button
383 'ooui-selectfile-button-select': 'Select a file',
384 // Label for the file selection widget if file selection is not supported
385 'ooui-selectfile-not-supported': 'File selection is not supported',
386 // Label for the file selection widget when no file is currently selected
387 'ooui-selectfile-placeholder': 'No file is selected',
388 // Label for the file selection widget's drop target
389 'ooui-selectfile-dragdrop-placeholder': 'Drop file here',
390 // Label for the help icon attached to a form field
391 'ooui-field-help': 'Help'
395 * Get a localized message.
397 * After the message key, message parameters may optionally be passed. In the default implementation,
398 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
399 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
400 * they support unnamed, ordered message parameters.
402 * In environments that provide a localization system, this function should be overridden to
403 * return the message translated in the user's language. The default implementation always returns
404 * English messages. An example of doing this with [jQuery.i18n](https://github.com/wikimedia/jquery.i18n)
408 * var i, iLen, button,
409 * messagePath = 'oojs-ui/dist/i18n/',
410 * languages = [ $.i18n().locale, 'ur', 'en' ],
413 * for ( i = 0, iLen = languages.length; i < iLen; i++ ) {
414 * languageMap[ languages[ i ] ] = messagePath + languages[ i ].toLowerCase() + '.json';
417 * $.i18n().load( languageMap ).done( function() {
418 * // Replace the built-in `msg` only once we've loaded the internationalization.
419 * // OOUI uses `OO.ui.deferMsg` for all initially-loaded messages. So long as
420 * // you put off creating any widgets until this promise is complete, no English
421 * // will be displayed.
422 * OO.ui.msg = $.i18n;
424 * // A button displaying "OK" in the default locale
425 * button = new OO.ui.ButtonWidget( {
426 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
429 * $( document.body ).append( button.$element );
431 * // A button displaying "OK" in Urdu
432 * $.i18n().locale = 'ur';
433 * button = new OO.ui.ButtonWidget( {
434 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
437 * $( document.body ).append( button.$element );
440 * @param {string} key Message key
441 * @param {...Mixed} [params] Message parameters
442 * @return {string} Translated message with parameters substituted
444 OO
.ui
.msg = function ( key
) {
445 var message
= messages
[ key
],
446 params
= Array
.prototype.slice
.call( arguments
, 1 );
447 if ( typeof message
=== 'string' ) {
448 // Perform $1 substitution
449 message
= message
.replace( /\$(\d+)/g, function ( unused
, n
) {
450 var i
= parseInt( n
, 10 );
451 return params
[ i
- 1 ] !== undefined ? params
[ i
- 1 ] : '$' + n
;
454 // Return placeholder if message not found
455 message
= '[' + key
+ ']';
462 * Package a message and arguments for deferred resolution.
464 * Use this when you are statically specifying a message and the message may not yet be present.
466 * @param {string} key Message key
467 * @param {...Mixed} [params] Message parameters
468 * @return {Function} Function that returns the resolved message when executed
470 OO
.ui
.deferMsg = function () {
471 var args
= arguments
;
473 return OO
.ui
.msg
.apply( OO
.ui
, args
);
480 * If the message is a function it will be executed, otherwise it will pass through directly.
482 * @param {Function|string} msg Deferred message, or message text
483 * @return {string} Resolved message
485 OO
.ui
.resolveMsg = function ( msg
) {
486 if ( typeof msg
=== 'function' ) {
493 * @param {string} url
496 OO
.ui
.isSafeUrl = function ( url
) {
497 // Keep this function in sync with php/Tag.php
498 var i
, protocolWhitelist
;
500 function stringStartsWith( haystack
, needle
) {
501 return haystack
.substr( 0, needle
.length
) === needle
;
504 protocolWhitelist
= [
505 'bitcoin', 'ftp', 'ftps', 'geo', 'git', 'gopher', 'http', 'https', 'irc', 'ircs',
506 'magnet', 'mailto', 'mms', 'news', 'nntp', 'redis', 'sftp', 'sip', 'sips', 'sms', 'ssh',
507 'svn', 'tel', 'telnet', 'urn', 'worldwind', 'xmpp'
514 for ( i
= 0; i
< protocolWhitelist
.length
; i
++ ) {
515 if ( stringStartsWith( url
, protocolWhitelist
[ i
] + ':' ) ) {
520 // This matches '//' too
521 if ( stringStartsWith( url
, '/' ) || stringStartsWith( url
, './' ) ) {
524 if ( stringStartsWith( url
, '?' ) || stringStartsWith( url
, '#' ) ) {
532 * Check if the user has a 'mobile' device.
534 * For our purposes this means the user is primarily using an
535 * on-screen keyboard, touch input instead of a mouse and may
536 * have a physically small display.
538 * It is left up to implementors to decide how to compute this
539 * so the default implementation always returns false.
541 * @return {boolean} User is on a mobile device
543 OO
.ui
.isMobile = function () {
548 * Get the additional spacing that should be taken into account when displaying elements that are
549 * clipped to the viewport, e.g. dropdown menus and popups. This is meant to be overridden to avoid
550 * such menus overlapping any fixed headers/toolbars/navigation used by the site.
552 * @return {Object} Object with the properties 'top', 'right', 'bottom', 'left', each representing
553 * the extra spacing from that edge of viewport (in pixels)
555 OO
.ui
.getViewportSpacing = function () {
565 * Get the default overlay, which is used by various widgets when they are passed `$overlay: true`.
566 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
568 * @return {jQuery} Default overlay node
570 OO
.ui
.getDefaultOverlay = function () {
571 if ( !OO
.ui
.$defaultOverlay
) {
572 OO
.ui
.$defaultOverlay
= $( '<div>' ).addClass( 'oo-ui-defaultOverlay' );
573 $( document
.body
).append( OO
.ui
.$defaultOverlay
);
575 return OO
.ui
.$defaultOverlay
;
583 * Namespace for OOUI mixins.
585 * Mixins are named according to the type of object they are intended to
586 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
587 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
588 * is intended to be mixed in to an instance of OO.ui.Widget.
596 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
597 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
598 * connected to them and can't be interacted with.
604 * @param {Object} [config] Configuration options
605 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
606 * to the top level (e.g., the outermost div) of the element. See the [OOUI documentation on MediaWiki][2]
608 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches#cssExample
609 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
610 * @cfg {string} [text] Text to insert
611 * @cfg {Array} [content] An array of content elements to append (after #text).
612 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
613 * Instances of OO.ui.Element will have their $element appended.
614 * @cfg {jQuery} [$content] Content elements to append (after #text).
615 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
616 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
617 * Data can also be specified with the #setData method.
619 OO
.ui
.Element
= function OoUiElement( config
) {
620 if ( OO
.ui
.isDemo
) {
621 this.initialConfig
= config
;
623 // Configuration initialization
624 config
= config
|| {};
627 this.$ = function () {
628 OO
.ui
.warnDeprecation( 'this.$ is deprecated, use global $ instead' );
629 return $.apply( this, arguments
);
631 this.elementId
= null;
633 this.data
= config
.data
;
634 this.$element
= config
.$element
||
635 $( document
.createElement( this.getTagName() ) );
636 this.elementGroup
= null;
639 if ( Array
.isArray( config
.classes
) ) {
640 this.$element
.addClass( config
.classes
);
643 this.setElementId( config
.id
);
646 this.$element
.text( config
.text
);
648 if ( config
.content
) {
649 // The `content` property treats plain strings as text; use an
650 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
651 // appropriate $element appended.
652 this.$element
.append( config
.content
.map( function ( v
) {
653 if ( typeof v
=== 'string' ) {
654 // Escape string so it is properly represented in HTML.
655 return document
.createTextNode( v
);
656 } else if ( v
instanceof OO
.ui
.HtmlSnippet
) {
659 } else if ( v
instanceof OO
.ui
.Element
) {
665 if ( config
.$content
) {
666 // The `$content` property treats plain strings as HTML.
667 this.$element
.append( config
.$content
);
673 OO
.initClass( OO
.ui
.Element
);
675 /* Static Properties */
678 * The name of the HTML tag used by the element.
680 * The static value may be ignored if the #getTagName method is overridden.
686 OO
.ui
.Element
.static.tagName
= 'div';
691 * Reconstitute a JavaScript object corresponding to a widget created
692 * by the PHP implementation.
694 * @param {string|HTMLElement|jQuery} idOrNode
695 * A DOM id (if a string) or node for the widget to infuse.
696 * @param {Object} [config] Configuration options
697 * @return {OO.ui.Element}
698 * The `OO.ui.Element` corresponding to this (infusable) document node.
699 * For `Tag` objects emitted on the HTML side (used occasionally for content)
700 * the value returned is a newly-created Element wrapping around the existing
703 OO
.ui
.Element
.static.infuse = function ( idOrNode
, config
) {
704 var obj
= OO
.ui
.Element
.static.unsafeInfuse( idOrNode
, config
, false );
706 if ( typeof idOrNode
=== 'string' ) {
707 // IDs deprecated since 0.29.7
708 OO
.ui
.warnDeprecation(
709 'Passing a string ID to infuse is deprecated. Use an HTMLElement or jQuery collection instead.'
712 // Verify that the type matches up.
713 // FIXME: uncomment after T89721 is fixed, see T90929.
715 if ( !( obj instanceof this['class'] ) ) {
716 throw new Error( 'Infusion type mismatch!' );
723 * Implementation helper for `infuse`; skips the type check and has an
724 * extra property so that only the top-level invocation touches the DOM.
727 * @param {string|HTMLElement|jQuery} idOrNode
728 * @param {Object} [config] Configuration options
729 * @param {jQuery.Promise} [domPromise] A promise that will be resolved
730 * when the top-level widget of this infusion is inserted into DOM,
731 * replacing the original node; only used internally.
732 * @return {OO.ui.Element}
734 OO
.ui
.Element
.static.unsafeInfuse = function ( idOrNode
, config
, domPromise
) {
735 // look for a cached result of a previous infusion.
736 var id
, $elem
, error
, data
, cls
, parts
, parent
, obj
, top
, state
, infusedChildren
;
737 if ( typeof idOrNode
=== 'string' ) {
739 $elem
= $( document
.getElementById( id
) );
741 $elem
= $( idOrNode
);
742 id
= $elem
.attr( 'id' );
744 if ( !$elem
.length
) {
745 if ( typeof idOrNode
=== 'string' ) {
746 error
= 'Widget not found: ' + idOrNode
;
747 } else if ( idOrNode
&& idOrNode
.selector
) {
748 error
= 'Widget not found: ' + idOrNode
.selector
;
750 error
= 'Widget not found';
752 throw new Error( error
);
754 if ( $elem
[ 0 ].oouiInfused
) {
755 $elem
= $elem
[ 0 ].oouiInfused
;
757 data
= $elem
.data( 'ooui-infused' );
760 if ( data
=== true ) {
761 throw new Error( 'Circular dependency! ' + id
);
764 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
765 state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
766 // restore dynamic state after the new element is re-inserted into DOM under infused parent
767 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
768 infusedChildren
= $elem
.data( 'ooui-infused-children' );
769 if ( infusedChildren
&& infusedChildren
.length
) {
770 infusedChildren
.forEach( function ( data
) {
771 var state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
772 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
778 data
= $elem
.attr( 'data-ooui' );
780 throw new Error( 'No infusion data found: ' + id
);
783 data
= JSON
.parse( data
);
787 if ( !( data
&& data
._
) ) {
788 throw new Error( 'No valid infusion data found: ' + id
);
790 if ( data
._
=== 'Tag' ) {
791 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
792 return new OO
.ui
.Element( $.extend( {}, config
, { $element
: $elem
} ) );
794 parts
= data
._
.split( '.' );
795 cls
= OO
.getProp
.apply( OO
, [ window
].concat( parts
) );
796 if ( cls
=== undefined ) {
797 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
800 // Verify that we're creating an OO.ui.Element instance
803 while ( parent
!== undefined ) {
804 if ( parent
=== OO
.ui
.Element
) {
809 parent
= parent
.parent
;
812 if ( parent
!== OO
.ui
.Element
) {
813 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
818 domPromise
= top
.promise();
820 $elem
.data( 'ooui-infused', true ); // prevent loops
821 data
.id
= id
; // implicit
822 infusedChildren
= [];
823 data
= OO
.copy( data
, null, function deserialize( value
) {
825 if ( OO
.isPlainObject( value
) ) {
827 infused
= OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, config
, domPromise
);
828 infusedChildren
.push( infused
);
829 // Flatten the structure
830 infusedChildren
.push
.apply( infusedChildren
, infused
.$element
.data( 'ooui-infused-children' ) || [] );
831 infused
.$element
.removeData( 'ooui-infused-children' );
834 if ( value
.html
!== undefined ) {
835 return new OO
.ui
.HtmlSnippet( value
.html
);
839 // allow widgets to reuse parts of the DOM
840 data
= cls
.static.reusePreInfuseDOM( $elem
[ 0 ], data
);
841 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
842 state
= cls
.static.gatherPreInfuseState( $elem
[ 0 ], data
);
844 // eslint-disable-next-line new-cap
845 obj
= new cls( $.extend( {}, config
, data
) );
846 // If anyone is holding a reference to the old DOM element,
847 // let's allow them to OO.ui.infuse() it and do what they expect, see T105828.
848 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
849 $elem
[ 0 ].oouiInfused
= obj
.$element
;
850 // now replace old DOM with this new DOM.
852 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
853 // so only mutate the DOM if we need to.
854 if ( $elem
[ 0 ] !== obj
.$element
[ 0 ] ) {
855 $elem
.replaceWith( obj
.$element
);
859 obj
.$element
.data( 'ooui-infused', obj
);
860 obj
.$element
.data( 'ooui-infused-children', infusedChildren
);
861 // set the 'data-ooui' attribute so we can identify infused widgets
862 obj
.$element
.attr( 'data-ooui', '' );
863 // restore dynamic state after the new element is inserted into DOM
864 domPromise
.done( obj
.restorePreInfuseState
.bind( obj
, state
) );
869 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
871 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
872 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
873 * constructor, which will be given the enhanced config.
876 * @param {HTMLElement} node
877 * @param {Object} config
880 OO
.ui
.Element
.static.reusePreInfuseDOM = function ( node
, config
) {
885 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of an HTML DOM node
886 * (and its children) that represent an Element of the same class and the given configuration,
887 * generated by the PHP implementation.
889 * This method is called just before `node` is detached from the DOM. The return value of this
890 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
891 * is inserted into DOM to replace `node`.
894 * @param {HTMLElement} node
895 * @param {Object} config
898 OO
.ui
.Element
.static.gatherPreInfuseState = function () {
903 * Get a jQuery function within a specific document.
906 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
907 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
909 * @return {Function} Bound jQuery function
911 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
912 function wrapper( selector
) {
913 return $( selector
, wrapper
.context
);
916 wrapper
.context
= this.getDocument( context
);
919 wrapper
.$iframe
= $iframe
;
926 * Get the document of an element.
929 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
930 * @return {HTMLDocument|null} Document object
932 OO
.ui
.Element
.static.getDocument = function ( obj
) {
933 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
934 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
935 // Empty jQuery selections might have a context
942 ( obj
.nodeType
=== Node
.DOCUMENT_NODE
&& obj
) ||
947 * Get the window of an element or document.
950 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
951 * @return {Window} Window object
953 OO
.ui
.Element
.static.getWindow = function ( obj
) {
954 var doc
= this.getDocument( obj
);
955 return doc
.defaultView
;
959 * Get the direction of an element or document.
962 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
963 * @return {string} Text direction, either 'ltr' or 'rtl'
965 OO
.ui
.Element
.static.getDir = function ( obj
) {
968 if ( obj
instanceof $ ) {
971 isDoc
= obj
.nodeType
=== Node
.DOCUMENT_NODE
;
972 isWin
= obj
.document
!== undefined;
973 if ( isDoc
|| isWin
) {
979 return $( obj
).css( 'direction' );
983 * Get the offset between two frames.
985 * TODO: Make this function not use recursion.
988 * @param {Window} from Window of the child frame
989 * @param {Window} [to=window] Window of the parent frame
990 * @param {Object} [offset] Offset to start with, used internally
991 * @return {Object} Offset object, containing left and top properties
993 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
994 var i
, len
, frames
, frame
, rect
;
1000 offset
= { top
: 0, left
: 0 };
1002 if ( from.parent
=== from ) {
1006 // Get iframe element
1007 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
1008 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
1009 if ( frames
[ i
].contentWindow
=== from ) {
1010 frame
= frames
[ i
];
1015 // Recursively accumulate offset values
1017 rect
= frame
.getBoundingClientRect();
1018 offset
.left
+= rect
.left
;
1019 offset
.top
+= rect
.top
;
1020 if ( from !== to
) {
1021 this.getFrameOffset( from.parent
, offset
);
1028 * Get the offset between two elements.
1030 * The two elements may be in a different frame, but in that case the frame $element is in must
1031 * be contained in the frame $anchor is in.
1034 * @param {jQuery} $element Element whose position to get
1035 * @param {jQuery} $anchor Element to get $element's position relative to
1036 * @return {Object} Translated position coordinates, containing top and left properties
1038 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
1039 var iframe
, iframePos
,
1040 pos
= $element
.offset(),
1041 anchorPos
= $anchor
.offset(),
1042 elementDocument
= this.getDocument( $element
),
1043 anchorDocument
= this.getDocument( $anchor
);
1045 // If $element isn't in the same document as $anchor, traverse up
1046 while ( elementDocument
!== anchorDocument
) {
1047 iframe
= elementDocument
.defaultView
.frameElement
;
1049 throw new Error( '$element frame is not contained in $anchor frame' );
1051 iframePos
= $( iframe
).offset();
1052 pos
.left
+= iframePos
.left
;
1053 pos
.top
+= iframePos
.top
;
1054 elementDocument
= iframe
.ownerDocument
;
1056 pos
.left
-= anchorPos
.left
;
1057 pos
.top
-= anchorPos
.top
;
1062 * Get element border sizes.
1065 * @param {HTMLElement} el Element to measure
1066 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1068 OO
.ui
.Element
.static.getBorders = function ( el
) {
1069 var doc
= el
.ownerDocument
,
1070 win
= doc
.defaultView
,
1071 style
= win
.getComputedStyle( el
, null ),
1073 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
1074 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
1075 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
1076 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
1087 * Get dimensions of an element or window.
1090 * @param {HTMLElement|Window} el Element to measure
1091 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1093 OO
.ui
.Element
.static.getDimensions = function ( el
) {
1095 doc
= el
.ownerDocument
|| el
.document
,
1096 win
= doc
.defaultView
;
1098 if ( win
=== el
|| el
=== doc
.documentElement
) {
1101 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
1103 top
: $win
.scrollTop(),
1104 left
: $win
.scrollLeft()
1106 scrollbar
: { right
: 0, bottom
: 0 },
1110 bottom
: $win
.innerHeight(),
1111 right
: $win
.innerWidth()
1117 borders
: this.getBorders( el
),
1119 top
: $el
.scrollTop(),
1120 left
: $el
.scrollLeft()
1123 right
: $el
.innerWidth() - el
.clientWidth
,
1124 bottom
: $el
.innerHeight() - el
.clientHeight
1126 rect
: el
.getBoundingClientRect()
1132 * Get the number of pixels that an element's content is scrolled to the left.
1134 * Adapted from <https://github.com/othree/jquery.rtl-scroll-type>.
1135 * Original code copyright 2012 Wei-Ko Kao, licensed under the MIT License.
1137 * This function smooths out browser inconsistencies (nicely described in the README at
1138 * <https://github.com/othree/jquery.rtl-scroll-type>) and produces a result consistent
1139 * with Firefox's 'scrollLeft', which seems the sanest.
1143 * @param {HTMLElement|Window} el Element to measure
1144 * @return {number} Scroll position from the left.
1145 * If the element's direction is LTR, this is a positive number between `0` (initial scroll position)
1146 * and `el.scrollWidth - el.clientWidth` (furthest possible scroll position).
1147 * If the element's direction is RTL, this is a negative number between `0` (initial scroll position)
1148 * and `-el.scrollWidth + el.clientWidth` (furthest possible scroll position).
1150 OO
.ui
.Element
.static.getScrollLeft
= ( function () {
1151 var rtlScrollType
= null;
1154 var $definer
= $( '<div>' ).attr( {
1156 style
: 'font-size: 14px; width: 4px; height: 1px; position: absolute; top: -1000px; overflow: scroll;'
1158 definer
= $definer
[ 0 ];
1160 $definer
.appendTo( 'body' );
1161 if ( definer
.scrollLeft
> 0 ) {
1163 rtlScrollType
= 'default';
1165 definer
.scrollLeft
= 1;
1166 if ( definer
.scrollLeft
=== 0 ) {
1167 // Firefox, old Opera
1168 rtlScrollType
= 'negative';
1170 // Internet Explorer, Edge
1171 rtlScrollType
= 'reverse';
1177 return function getScrollLeft( el
) {
1178 var isRoot
= el
.window
=== el
||
1179 el
=== el
.ownerDocument
.body
||
1180 el
=== el
.ownerDocument
.documentElement
,
1181 scrollLeft
= isRoot
? $( window
).scrollLeft() : el
.scrollLeft
,
1182 // All browsers use the correct scroll type ('negative') on the root, so don't
1183 // do any fixups when looking at the root element
1184 direction
= isRoot
? 'ltr' : $( el
).css( 'direction' );
1186 if ( direction
=== 'rtl' ) {
1187 if ( rtlScrollType
=== null ) {
1190 if ( rtlScrollType
=== 'reverse' ) {
1191 scrollLeft
= -scrollLeft
;
1192 } else if ( rtlScrollType
=== 'default' ) {
1193 scrollLeft
= scrollLeft
- el
.scrollWidth
+ el
.clientWidth
;
1202 * Get the root scrollable element of given element's document.
1204 * On Blink-based browsers (Chrome etc.), `document.documentElement` can't be used to get or set
1205 * the scrollTop property; instead we have to use `document.body`. Changing and testing the value
1206 * lets us use 'body' or 'documentElement' based on what is working.
1208 * https://code.google.com/p/chromium/issues/detail?id=303131
1211 * @param {HTMLElement} el Element to find root scrollable parent for
1212 * @return {HTMLElement} Scrollable parent, `document.body` or `document.documentElement`
1213 * depending on browser
1215 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1216 var scrollTop
, body
;
1218 if ( OO
.ui
.scrollableElement
=== undefined ) {
1219 body
= el
.ownerDocument
.body
;
1220 scrollTop
= body
.scrollTop
;
1223 // In some browsers (observed in Chrome 56 on Linux Mint 18.1),
1224 // body.scrollTop doesn't become exactly 1, but a fractional value like 0.76
1225 if ( Math
.round( body
.scrollTop
) === 1 ) {
1226 body
.scrollTop
= scrollTop
;
1227 OO
.ui
.scrollableElement
= 'body';
1229 OO
.ui
.scrollableElement
= 'documentElement';
1233 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1237 * Get closest scrollable container.
1239 * Traverses up until either a scrollable element or the root is reached, in which case the root
1240 * scrollable element will be returned (see #getRootScrollableElement).
1243 * @param {HTMLElement} el Element to find scrollable container for
1244 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1245 * @return {HTMLElement} Closest scrollable container
1247 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1249 // Browsers do not correctly return the computed value of 'overflow' when 'overflow-x' and
1250 // 'overflow-y' have different values, so we need to check the separate properties.
1251 props
= [ 'overflow-x', 'overflow-y' ],
1252 $parent
= $( el
).parent();
1254 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1255 props
= [ 'overflow-' + dimension
];
1258 // Special case for the document root (which doesn't really have any scrollable container, since
1259 // it is the ultimate scrollable container, but this is probably saner than null or exception)
1260 if ( $( el
).is( 'html, body' ) ) {
1261 return this.getRootScrollableElement( el
);
1264 while ( $parent
.length
) {
1265 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1266 return $parent
[ 0 ];
1270 val
= $parent
.css( props
[ i
] );
1271 // We assume that elements with 'overflow' (in any direction) set to 'hidden' will never be
1272 // scrolled in that direction, but they can actually be scrolled programatically. The user can
1273 // unintentionally perform a scroll in such case even if the application doesn't scroll
1274 // programatically, e.g. when jumping to an anchor, or when using built-in find functionality.
1275 // This could cause funny issues...
1276 if ( val
=== 'auto' || val
=== 'scroll' ) {
1277 return $parent
[ 0 ];
1280 $parent
= $parent
.parent();
1282 // The element is unattached... return something mostly sane
1283 return this.getRootScrollableElement( el
);
1287 * Scroll element into view.
1290 * @param {HTMLElement} el Element to scroll into view
1291 * @param {Object} [config] Configuration options
1292 * @param {string} [config.duration='fast'] jQuery animation duration value
1293 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1294 * to scroll in both directions
1295 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1297 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1298 var position
, animations
, container
, $container
, elementDimensions
, containerDimensions
, $window
,
1299 deferred
= $.Deferred();
1301 // Configuration initialization
1302 config
= config
|| {};
1305 container
= this.getClosestScrollableContainer( el
, config
.direction
);
1306 $container
= $( container
);
1307 elementDimensions
= this.getDimensions( el
);
1308 containerDimensions
= this.getDimensions( container
);
1309 $window
= $( this.getWindow( el
) );
1311 // Compute the element's position relative to the container
1312 if ( $container
.is( 'html, body' ) ) {
1313 // If the scrollable container is the root, this is easy
1315 top
: elementDimensions
.rect
.top
,
1316 bottom
: $window
.innerHeight() - elementDimensions
.rect
.bottom
,
1317 left
: elementDimensions
.rect
.left
,
1318 right
: $window
.innerWidth() - elementDimensions
.rect
.right
1321 // Otherwise, we have to subtract el's coordinates from container's coordinates
1323 top
: elementDimensions
.rect
.top
- ( containerDimensions
.rect
.top
+ containerDimensions
.borders
.top
),
1324 bottom
: containerDimensions
.rect
.bottom
- containerDimensions
.borders
.bottom
- containerDimensions
.scrollbar
.bottom
- elementDimensions
.rect
.bottom
,
1325 left
: elementDimensions
.rect
.left
- ( containerDimensions
.rect
.left
+ containerDimensions
.borders
.left
),
1326 right
: containerDimensions
.rect
.right
- containerDimensions
.borders
.right
- containerDimensions
.scrollbar
.right
- elementDimensions
.rect
.right
1330 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1331 if ( position
.top
< 0 ) {
1332 animations
.scrollTop
= containerDimensions
.scroll
.top
+ position
.top
;
1333 } else if ( position
.top
> 0 && position
.bottom
< 0 ) {
1334 animations
.scrollTop
= containerDimensions
.scroll
.top
+ Math
.min( position
.top
, -position
.bottom
);
1337 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1338 if ( position
.left
< 0 ) {
1339 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ position
.left
;
1340 } else if ( position
.left
> 0 && position
.right
< 0 ) {
1341 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ Math
.min( position
.left
, -position
.right
);
1344 if ( !$.isEmptyObject( animations
) ) {
1345 // eslint-disable-next-line jquery/no-animate
1346 $container
.stop( true ).animate( animations
, config
.duration
=== undefined ? 'fast' : config
.duration
);
1347 $container
.queue( function ( next
) {
1354 return deferred
.promise();
1358 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1359 * and reserve space for them, because it probably doesn't.
1361 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1362 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1363 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1364 * and then reattach (or show) them back.
1367 * @param {HTMLElement} el Element to reconsider the scrollbars on
1369 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1370 var i
, len
, scrollLeft
, scrollTop
, nodes
= [];
1371 // Save scroll position
1372 scrollLeft
= el
.scrollLeft
;
1373 scrollTop
= el
.scrollTop
;
1374 // Detach all children
1375 while ( el
.firstChild
) {
1376 nodes
.push( el
.firstChild
);
1377 el
.removeChild( el
.firstChild
);
1380 // eslint-disable-next-line no-void
1381 void el
.offsetHeight
;
1382 // Reattach all children
1383 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1384 el
.appendChild( nodes
[ i
] );
1386 // Restore scroll position (no-op if scrollbars disappeared)
1387 el
.scrollLeft
= scrollLeft
;
1388 el
.scrollTop
= scrollTop
;
1394 * Toggle visibility of an element.
1396 * @param {boolean} [show] Make element visible, omit to toggle visibility
1399 * @return {OO.ui.Element} The element, for chaining
1401 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1402 show
= show
=== undefined ? !this.visible
: !!show
;
1404 if ( show
!== this.isVisible() ) {
1405 this.visible
= show
;
1406 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1407 this.emit( 'toggle', show
);
1414 * Check if element is visible.
1416 * @return {boolean} element is visible
1418 OO
.ui
.Element
.prototype.isVisible = function () {
1419 return this.visible
;
1425 * @return {Mixed} Element data
1427 OO
.ui
.Element
.prototype.getData = function () {
1434 * @param {Mixed} data Element data
1436 * @return {OO.ui.Element} The element, for chaining
1438 OO
.ui
.Element
.prototype.setData = function ( data
) {
1444 * Set the element has an 'id' attribute.
1446 * @param {string} id
1448 * @return {OO.ui.Element} The element, for chaining
1450 OO
.ui
.Element
.prototype.setElementId = function ( id
) {
1451 this.elementId
= id
;
1452 this.$element
.attr( 'id', id
);
1457 * Ensure that the element has an 'id' attribute, setting it to an unique value if it's missing,
1458 * and return its value.
1462 OO
.ui
.Element
.prototype.getElementId = function () {
1463 if ( this.elementId
=== null ) {
1464 this.setElementId( OO
.ui
.generateElementId() );
1466 return this.elementId
;
1470 * Check if element supports one or more methods.
1472 * @param {string|string[]} methods Method or list of methods to check
1473 * @return {boolean} All methods are supported
1475 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1479 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1480 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1481 if ( typeof this[ methods
[ i
] ] === 'function' ) {
1486 return methods
.length
=== support
;
1490 * Update the theme-provided classes.
1492 * @localdoc This is called in element mixins and widget classes any time state changes.
1493 * Updating is debounced, minimizing overhead of changing multiple attributes and
1494 * guaranteeing that theme updates do not occur within an element's constructor
1496 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1497 OO
.ui
.theme
.queueUpdateElementClasses( this );
1501 * Get the HTML tag name.
1503 * Override this method to base the result on instance information.
1505 * @return {string} HTML tag name
1507 OO
.ui
.Element
.prototype.getTagName = function () {
1508 return this.constructor.static.tagName
;
1512 * Check if the element is attached to the DOM
1514 * @return {boolean} The element is attached to the DOM
1516 OO
.ui
.Element
.prototype.isElementAttached = function () {
1517 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1521 * Get the DOM document.
1523 * @return {HTMLDocument} Document object
1525 OO
.ui
.Element
.prototype.getElementDocument = function () {
1526 // Don't cache this in other ways either because subclasses could can change this.$element
1527 return OO
.ui
.Element
.static.getDocument( this.$element
);
1531 * Get the DOM window.
1533 * @return {Window} Window object
1535 OO
.ui
.Element
.prototype.getElementWindow = function () {
1536 return OO
.ui
.Element
.static.getWindow( this.$element
);
1540 * Get closest scrollable container.
1542 * @return {HTMLElement} Closest scrollable container
1544 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1545 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1549 * Get group element is in.
1551 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1553 OO
.ui
.Element
.prototype.getElementGroup = function () {
1554 return this.elementGroup
;
1558 * Set group element is in.
1560 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1562 * @return {OO.ui.Element} The element, for chaining
1564 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1565 this.elementGroup
= group
;
1570 * Scroll element into view.
1572 * @param {Object} [config] Configuration options
1573 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1575 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1577 !this.isElementAttached() ||
1578 !this.isVisible() ||
1579 ( this.getElementGroup() && !this.getElementGroup().isVisible() )
1581 return $.Deferred().resolve();
1583 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1587 * Restore the pre-infusion dynamic state for this widget.
1589 * This method is called after #$element has been inserted into DOM. The parameter is the return
1590 * value of #gatherPreInfuseState.
1593 * @param {Object} state
1595 OO
.ui
.Element
.prototype.restorePreInfuseState = function () {
1599 * Wraps an HTML snippet for use with configuration values which default
1600 * to strings. This bypasses the default html-escaping done to string
1606 * @param {string} [content] HTML content
1608 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
1610 this.content
= content
;
1615 OO
.initClass( OO
.ui
.HtmlSnippet
);
1622 * @return {string} Unchanged HTML snippet.
1624 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
1625 return this.content
;
1629 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1630 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1631 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1632 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1633 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1637 * @extends OO.ui.Element
1638 * @mixins OO.EventEmitter
1641 * @param {Object} [config] Configuration options
1643 OO
.ui
.Layout
= function OoUiLayout( config
) {
1644 // Configuration initialization
1645 config
= config
|| {};
1647 // Parent constructor
1648 OO
.ui
.Layout
.parent
.call( this, config
);
1650 // Mixin constructors
1651 OO
.EventEmitter
.call( this );
1654 this.$element
.addClass( 'oo-ui-layout' );
1659 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1660 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1665 * Reset scroll offsets
1668 * @return {OO.ui.Layout} The layout, for chaining
1670 OO
.ui
.Layout
.prototype.resetScroll = function () {
1671 this.$element
[ 0 ].scrollTop
= 0;
1672 // TODO: Reset scrollLeft in an RTL-aware manner, see OO.ui.Element.static.getScrollLeft.
1678 * Widgets are compositions of one or more OOUI elements that users can both view
1679 * and interact with. All widgets can be configured and modified via a standard API,
1680 * and their state can change dynamically according to a model.
1684 * @extends OO.ui.Element
1685 * @mixins OO.EventEmitter
1688 * @param {Object} [config] Configuration options
1689 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1690 * appearance reflects this state.
1692 OO
.ui
.Widget
= function OoUiWidget( config
) {
1693 // Initialize config
1694 config
= $.extend( { disabled
: false }, config
);
1696 // Parent constructor
1697 OO
.ui
.Widget
.parent
.call( this, config
);
1699 // Mixin constructors
1700 OO
.EventEmitter
.call( this );
1703 this.disabled
= null;
1704 this.wasDisabled
= null;
1707 this.$element
.addClass( 'oo-ui-widget' );
1708 this.setDisabled( !!config
.disabled
);
1713 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1714 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1721 * A 'disable' event is emitted when the disabled state of the widget changes
1722 * (i.e. on disable **and** enable).
1724 * @param {boolean} disabled Widget is disabled
1730 * A 'toggle' event is emitted when the visibility of the widget changes.
1732 * @param {boolean} visible Widget is visible
1738 * Check if the widget is disabled.
1740 * @return {boolean} Widget is disabled
1742 OO
.ui
.Widget
.prototype.isDisabled = function () {
1743 return this.disabled
;
1747 * Set the 'disabled' state of the widget.
1749 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1751 * @param {boolean} disabled Disable widget
1753 * @return {OO.ui.Widget} The widget, for chaining
1755 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
1758 this.disabled
= !!disabled
;
1759 isDisabled
= this.isDisabled();
1760 if ( isDisabled
!== this.wasDisabled
) {
1761 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
1762 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
1763 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
1764 this.emit( 'disable', isDisabled
);
1765 this.updateThemeClasses();
1767 this.wasDisabled
= isDisabled
;
1773 * Update the disabled state, in case of changes in parent widget.
1776 * @return {OO.ui.Widget} The widget, for chaining
1778 OO
.ui
.Widget
.prototype.updateDisabled = function () {
1779 this.setDisabled( this.disabled
);
1784 * Get an ID of a labelable node which is part of this widget, if any, to be used for `<label for>`
1787 * If this function returns null, the widget should have a meaningful #simulateLabelClick method
1790 * @return {string|null} The ID of the labelable element
1792 OO
.ui
.Widget
.prototype.getInputId = function () {
1797 * Simulate the behavior of clicking on a label (a HTML `<label>` element) bound to this input.
1798 * HTML only allows `<label>` to act on specific "labelable" elements; complex widgets might need to
1799 * override this method to provide intuitive, accessible behavior.
1801 * By default, this does nothing. OO.ui.mixin.TabIndexedElement overrides it for focusable widgets.
1802 * Individual widgets may override it too.
1804 * This method is called by OO.ui.LabelWidget and OO.ui.FieldLayout. It should not be called
1807 OO
.ui
.Widget
.prototype.simulateLabelClick = function () {
1818 OO
.ui
.Theme
= function OoUiTheme() {
1819 this.elementClassesQueue
= [];
1820 this.debouncedUpdateQueuedElementClasses
= OO
.ui
.debounce( this.updateQueuedElementClasses
);
1825 OO
.initClass( OO
.ui
.Theme
);
1830 * Get a list of classes to be applied to a widget.
1832 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
1833 * otherwise state transitions will not work properly.
1835 * @param {OO.ui.Element} element Element for which to get classes
1836 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1838 OO
.ui
.Theme
.prototype.getElementClasses = function () {
1839 return { on
: [], off
: [] };
1843 * Update CSS classes provided by the theme.
1845 * For elements with theme logic hooks, this should be called any time there's a state change.
1847 * @param {OO.ui.Element} element Element for which to update classes
1849 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
1850 var $elements
= $( [] ),
1851 classes
= this.getElementClasses( element
);
1853 if ( element
.$icon
) {
1854 $elements
= $elements
.add( element
.$icon
);
1856 if ( element
.$indicator
) {
1857 $elements
= $elements
.add( element
.$indicator
);
1861 .removeClass( classes
.off
)
1862 .addClass( classes
.on
);
1868 OO
.ui
.Theme
.prototype.updateQueuedElementClasses = function () {
1870 for ( i
= 0; i
< this.elementClassesQueue
.length
; i
++ ) {
1871 this.updateElementClasses( this.elementClassesQueue
[ i
] );
1874 this.elementClassesQueue
= [];
1878 * Queue #updateElementClasses to be called for this element.
1880 * @localdoc QUnit tests override this method to directly call #queueUpdateElementClasses,
1881 * to make them synchronous.
1883 * @param {OO.ui.Element} element Element for which to update classes
1885 OO
.ui
.Theme
.prototype.queueUpdateElementClasses = function ( element
) {
1886 // Keep items in the queue unique. Use lastIndexOf to start checking from the end because that's
1887 // the most common case (this method is often called repeatedly for the same element).
1888 if ( this.elementClassesQueue
.lastIndexOf( element
) !== -1 ) {
1891 this.elementClassesQueue
.push( element
);
1892 this.debouncedUpdateQueuedElementClasses();
1896 * Get the transition duration in milliseconds for dialogs opening/closing
1898 * The dialog should be fully rendered this many milliseconds after the
1899 * ready process has executed.
1901 * @return {number} Transition duration in milliseconds
1903 OO
.ui
.Theme
.prototype.getDialogTransitionDuration = function () {
1908 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
1909 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
1910 * order in which users will navigate through the focusable elements via the “tab” key.
1913 * // TabIndexedElement is mixed into the ButtonWidget class
1914 * // to provide a tabIndex property.
1915 * var button1 = new OO.ui.ButtonWidget( {
1919 * button2 = new OO.ui.ButtonWidget( {
1923 * button3 = new OO.ui.ButtonWidget( {
1927 * button4 = new OO.ui.ButtonWidget( {
1931 * $( document.body ).append( button1.$element, button2.$element, button3.$element, button4.$element );
1937 * @param {Object} [config] Configuration options
1938 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
1939 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
1940 * functionality will be applied to it instead.
1941 * @cfg {string|number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
1942 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
1943 * to remove the element from the tab-navigation flow.
1945 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
1946 // Configuration initialization
1947 config
= $.extend( { tabIndex
: 0 }, config
);
1950 this.$tabIndexed
= null;
1951 this.tabIndex
= null;
1954 this.connect( this, { disable
: 'onTabIndexedElementDisable' } );
1957 this.setTabIndex( config
.tabIndex
);
1958 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
1963 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
1968 * Set the element that should use the tabindex functionality.
1970 * This method is used to retarget a tabindex mixin so that its functionality applies
1971 * to the specified element. If an element is currently using the functionality, the mixin’s
1972 * effect on that element is removed before the new element is set up.
1974 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
1976 * @return {OO.ui.Element} The element, for chaining
1978 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
1979 var tabIndex
= this.tabIndex
;
1980 // Remove attributes from old $tabIndexed
1981 this.setTabIndex( null );
1982 // Force update of new $tabIndexed
1983 this.$tabIndexed
= $tabIndexed
;
1984 this.tabIndex
= tabIndex
;
1985 return this.updateTabIndex();
1989 * Set the value of the tabindex.
1991 * @param {string|number|null} tabIndex Tabindex value, or `null` for no tabindex
1993 * @return {OO.ui.Element} The element, for chaining
1995 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
1996 tabIndex
= /^-?\d+$/.test( tabIndex
) ? Number( tabIndex
) : null;
1998 if ( this.tabIndex
!== tabIndex
) {
1999 this.tabIndex
= tabIndex
;
2000 this.updateTabIndex();
2007 * Update the `tabindex` attribute, in case of changes to tab index or
2012 * @return {OO.ui.Element} The element, for chaining
2014 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
2015 if ( this.$tabIndexed
) {
2016 if ( this.tabIndex
!== null ) {
2017 // Do not index over disabled elements
2018 this.$tabIndexed
.attr( {
2019 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
2020 // Support: ChromeVox and NVDA
2021 // These do not seem to inherit aria-disabled from parent elements
2022 'aria-disabled': this.isDisabled().toString()
2025 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
2032 * Handle disable events.
2035 * @param {boolean} disabled Element is disabled
2037 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
2038 this.updateTabIndex();
2042 * Get the value of the tabindex.
2044 * @return {number|null} Tabindex value
2046 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
2047 return this.tabIndex
;
2051 * Get an ID of a focusable element of this widget, if any, to be used for `<label for>` value.
2053 * If the element already has an ID then that is returned, otherwise unique ID is
2054 * generated, set on the element, and returned.
2056 * @return {string|null} The ID of the focusable element
2058 OO
.ui
.mixin
.TabIndexedElement
.prototype.getInputId = function () {
2061 if ( !this.$tabIndexed
) {
2064 if ( !this.isLabelableNode( this.$tabIndexed
) ) {
2068 id
= this.$tabIndexed
.attr( 'id' );
2069 if ( id
=== undefined ) {
2070 id
= OO
.ui
.generateElementId();
2071 this.$tabIndexed
.attr( 'id', id
);
2078 * Whether the node is 'labelable' according to the HTML spec
2079 * (i.e., whether it can be interacted with through a `<label for="…">`).
2080 * See: <https://html.spec.whatwg.org/multipage/forms.html#category-label>.
2083 * @param {jQuery} $node
2086 OO
.ui
.mixin
.TabIndexedElement
.prototype.isLabelableNode = function ( $node
) {
2088 labelableTags
= [ 'button', 'meter', 'output', 'progress', 'select', 'textarea' ],
2089 tagName
= $node
.prop( 'tagName' ).toLowerCase();
2091 if ( tagName
=== 'input' && $node
.attr( 'type' ) !== 'hidden' ) {
2094 if ( labelableTags
.indexOf( tagName
) !== -1 ) {
2101 * Focus this element.
2104 * @return {OO.ui.Element} The element, for chaining
2106 OO
.ui
.mixin
.TabIndexedElement
.prototype.focus = function () {
2107 if ( !this.isDisabled() ) {
2108 this.$tabIndexed
.trigger( 'focus' );
2114 * Blur this element.
2117 * @return {OO.ui.Element} The element, for chaining
2119 OO
.ui
.mixin
.TabIndexedElement
.prototype.blur = function () {
2120 this.$tabIndexed
.trigger( 'blur' );
2125 * @inheritdoc OO.ui.Widget
2127 OO
.ui
.mixin
.TabIndexedElement
.prototype.simulateLabelClick = function () {
2132 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
2133 * interface element that can be configured with access keys for keyboard interaction.
2134 * See the [OOUI documentation on MediaWiki] [1] for examples.
2136 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches#Buttons
2142 * @param {Object} [config] Configuration options
2143 * @cfg {jQuery} [$button] The button element created by the class.
2144 * If this configuration is omitted, the button element will use a generated `<a>`.
2145 * @cfg {boolean} [framed=true] Render the button with a frame
2147 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
2148 // Configuration initialization
2149 config
= config
|| {};
2152 this.$button
= null;
2154 this.active
= config
.active
!== undefined && config
.active
;
2155 this.onDocumentMouseUpHandler
= this.onDocumentMouseUp
.bind( this );
2156 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
2157 this.onDocumentKeyUpHandler
= this.onDocumentKeyUp
.bind( this );
2158 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
2159 this.onClickHandler
= this.onClick
.bind( this );
2160 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
2163 this.$element
.addClass( 'oo-ui-buttonElement' );
2164 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
2165 this.setButtonElement( config
.$button
|| $( '<a>' ) );
2170 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
2172 /* Static Properties */
2175 * Cancel mouse down events.
2177 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
2178 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
2179 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
2184 * @property {boolean}
2186 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
2191 * A 'click' event is emitted when the button element is clicked.
2199 * Set the button element.
2201 * This method is used to retarget a button mixin so that its functionality applies to
2202 * the specified button element instead of the one created by the class. If a button element
2203 * is already set, the method will remove the mixin’s effect on that element.
2205 * @param {jQuery} $button Element to use as button
2207 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
2208 if ( this.$button
) {
2210 .removeClass( 'oo-ui-buttonElement-button' )
2211 .removeAttr( 'role accesskey' )
2213 mousedown
: this.onMouseDownHandler
,
2214 keydown
: this.onKeyDownHandler
,
2215 click
: this.onClickHandler
,
2216 keypress
: this.onKeyPressHandler
2220 this.$button
= $button
2221 .addClass( 'oo-ui-buttonElement-button' )
2223 mousedown
: this.onMouseDownHandler
,
2224 keydown
: this.onKeyDownHandler
,
2225 click
: this.onClickHandler
,
2226 keypress
: this.onKeyPressHandler
2229 // Add `role="button"` on `<a>` elements, where it's needed
2230 // `toUpperCase()` is added for XHTML documents
2231 if ( this.$button
.prop( 'tagName' ).toUpperCase() === 'A' ) {
2232 this.$button
.attr( 'role', 'button' );
2237 * Handles mouse down events.
2240 * @param {jQuery.Event} e Mouse down event
2241 * @return {undefined/boolean} False to prevent default if event is handled
2243 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
2244 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
2247 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
2248 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
2249 // reliably remove the pressed class
2250 this.getElementDocument().addEventListener( 'mouseup', this.onDocumentMouseUpHandler
, true );
2251 // Prevent change of focus unless specifically configured otherwise
2252 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
2258 * Handles document mouse up events.
2261 * @param {MouseEvent} e Mouse up event
2263 OO
.ui
.mixin
.ButtonElement
.prototype.onDocumentMouseUp = function ( e
) {
2264 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
2267 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
2268 // Stop listening for mouseup, since we only needed this once
2269 this.getElementDocument().removeEventListener( 'mouseup', this.onDocumentMouseUpHandler
, true );
2272 // Deprecated alias since 0.28.3
2273 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp = function () {
2274 OO
.ui
.warnDeprecation( 'onMouseUp is deprecated, use onDocumentMouseUp instead' );
2275 this.onDocumentMouseUp
.apply( this, arguments
);
2279 * Handles mouse click events.
2282 * @param {jQuery.Event} e Mouse click event
2284 * @return {undefined/boolean} False to prevent default if event is handled
2286 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
2287 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
2288 if ( this.emit( 'click' ) ) {
2295 * Handles key down events.
2298 * @param {jQuery.Event} e Key down event
2300 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
2301 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2304 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
2305 // Run the keyup handler no matter where the key is when the button is let go, so we can
2306 // reliably remove the pressed class
2307 this.getElementDocument().addEventListener( 'keyup', this.onDocumentKeyUpHandler
, true );
2311 * Handles document key up events.
2314 * @param {KeyboardEvent} e Key up event
2316 OO
.ui
.mixin
.ButtonElement
.prototype.onDocumentKeyUp = function ( e
) {
2317 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2320 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
2321 // Stop listening for keyup, since we only needed this once
2322 this.getElementDocument().removeEventListener( 'keyup', this.onDocumentKeyUpHandler
, true );
2325 // Deprecated alias since 0.28.3
2326 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyUp = function () {
2327 OO
.ui
.warnDeprecation( 'onKeyUp is deprecated, use onDocumentKeyUp instead' );
2328 this.onDocumentKeyUp
.apply( this, arguments
);
2332 * Handles key press events.
2335 * @param {jQuery.Event} e Key press event
2337 * @return {undefined/boolean} False to prevent default if event is handled
2339 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
2340 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
2341 if ( this.emit( 'click' ) ) {
2348 * Check if button has a frame.
2350 * @return {boolean} Button is framed
2352 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
2357 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
2359 * @param {boolean} [framed] Make button framed, omit to toggle
2361 * @return {OO.ui.Element} The element, for chaining
2363 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
2364 framed
= framed
=== undefined ? !this.framed
: !!framed
;
2365 if ( framed
!== this.framed
) {
2366 this.framed
= framed
;
2368 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
2369 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
2370 this.updateThemeClasses();
2377 * Set the button's active state.
2379 * The active state can be set on:
2381 * - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected
2382 * - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on
2383 * - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page
2386 * @param {boolean} value Make button active
2388 * @return {OO.ui.Element} The element, for chaining
2390 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
2391 this.active
= !!value
;
2392 this.$element
.toggleClass( 'oo-ui-buttonElement-active', this.active
);
2393 this.updateThemeClasses();
2398 * Check if the button is active
2401 * @return {boolean} The button is active
2403 OO
.ui
.mixin
.ButtonElement
.prototype.isActive = function () {
2408 * Any OOUI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
2409 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
2410 * items from the group is done through the interface the class provides.
2411 * For more information, please see the [OOUI documentation on MediaWiki] [1].
2413 * [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Groups
2416 * @mixins OO.EmitterList
2420 * @param {Object} [config] Configuration options
2421 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
2422 * is omitted, the group element will use a generated `<div>`.
2424 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
2425 // Configuration initialization
2426 config
= config
|| {};
2428 // Mixin constructors
2429 OO
.EmitterList
.call( this, config
);
2435 this.setGroupElement( config
.$group
|| $( '<div>' ) );
2440 OO
.mixinClass( OO
.ui
.mixin
.GroupElement
, OO
.EmitterList
);
2447 * A change event is emitted when the set of selected items changes.
2449 * @param {OO.ui.Element[]} items Items currently in the group
2455 * Set the group element.
2457 * If an element is already set, items will be moved to the new element.
2459 * @param {jQuery} $group Element to use as group
2461 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
2464 this.$group
= $group
;
2465 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2466 this.$group
.append( this.items
[ i
].$element
);
2471 * Find an item by its data.
2473 * Only the first item with matching data will be returned. To return all matching items,
2474 * use the #findItemsFromData method.
2476 * @param {Object} data Item data to search for
2477 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2479 OO
.ui
.mixin
.GroupElement
.prototype.findItemFromData = function ( data
) {
2481 hash
= OO
.getHash( data
);
2483 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2484 item
= this.items
[ i
];
2485 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2494 * Find items by their data.
2496 * All items with matching data will be returned. To return only the first match, use the #findItemFromData method instead.
2498 * @param {Object} data Item data to search for
2499 * @return {OO.ui.Element[]} Items with equivalent data
2501 OO
.ui
.mixin
.GroupElement
.prototype.findItemsFromData = function ( data
) {
2503 hash
= OO
.getHash( data
),
2506 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2507 item
= this.items
[ i
];
2508 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2517 * Add items to the group.
2519 * Items will be added to the end of the group array unless the optional `index` parameter specifies
2520 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
2522 * @param {OO.ui.Element[]} items An array of items to add to the group
2523 * @param {number} [index] Index of the insertion point
2525 * @return {OO.ui.Element} The element, for chaining
2527 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
2529 if ( items
.length
=== 0 ) {
2534 OO
.EmitterList
.prototype.addItems
.call( this, items
, index
);
2536 this.emit( 'change', this.getItems() );
2543 OO
.ui
.mixin
.GroupElement
.prototype.moveItem = function ( items
, newIndex
) {
2544 // insertItemElements expects this.items to not have been modified yet, so call before the mixin
2545 this.insertItemElements( items
, newIndex
);
2548 newIndex
= OO
.EmitterList
.prototype.moveItem
.call( this, items
, newIndex
);
2556 OO
.ui
.mixin
.GroupElement
.prototype.insertItem = function ( item
, index
) {
2557 item
.setElementGroup( this );
2558 this.insertItemElements( item
, index
);
2561 index
= OO
.EmitterList
.prototype.insertItem
.call( this, item
, index
);
2567 * Insert elements into the group
2570 * @param {OO.ui.Element} itemWidget Item to insert
2571 * @param {number} index Insertion index
2573 OO
.ui
.mixin
.GroupElement
.prototype.insertItemElements = function ( itemWidget
, index
) {
2574 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
2575 this.$group
.append( itemWidget
.$element
);
2576 } else if ( index
=== 0 ) {
2577 this.$group
.prepend( itemWidget
.$element
);
2579 this.items
[ index
].$element
.before( itemWidget
.$element
);
2584 * Remove the specified items from a group.
2586 * Removed items are detached (not removed) from the DOM so that they may be reused.
2587 * To remove all items from a group, you may wish to use the #clearItems method instead.
2589 * @param {OO.ui.Element[]} items An array of items to remove
2591 * @return {OO.ui.Element} The element, for chaining
2593 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
2594 var i
, len
, item
, index
;
2596 if ( items
.length
=== 0 ) {
2600 // Remove specific items elements
2601 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
2603 index
= this.items
.indexOf( item
);
2604 if ( index
!== -1 ) {
2605 item
.setElementGroup( null );
2606 item
.$element
.detach();
2611 OO
.EmitterList
.prototype.removeItems
.call( this, items
);
2613 this.emit( 'change', this.getItems() );
2618 * Clear all items from the group.
2620 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2621 * To remove only a subset of items from a group, use the #removeItems method.
2624 * @return {OO.ui.Element} The element, for chaining
2626 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
2629 // Remove all item elements
2630 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2631 this.items
[ i
].setElementGroup( null );
2632 this.items
[ i
].$element
.detach();
2636 OO
.EmitterList
.prototype.clearItems
.call( this );
2638 this.emit( 'change', this.getItems() );
2643 * LabelElement is often mixed into other classes to generate a label, which
2644 * helps identify the function of an interface element.
2645 * See the [OOUI documentation on MediaWiki] [1] for more information.
2647 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
2653 * @param {Object} [config] Configuration options
2654 * @cfg {jQuery} [$label] The label element created by the class. If this
2655 * configuration is omitted, the label element will use a generated `<span>`.
2656 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
2657 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
2658 * in the future. See the [OOUI documentation on MediaWiki] [2] for examples.
2659 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
2660 * @cfg {boolean} [invisibleLabel] Whether the label should be visually hidden (but still accessible
2661 * to screen-readers).
2663 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
2664 // Configuration initialization
2665 config
= config
|| {};
2670 this.invisibleLabel
= null;
2673 this.setLabel( config
.label
|| this.constructor.static.label
);
2674 this.setLabelElement( config
.$label
|| $( '<span>' ) );
2675 this.setInvisibleLabel( config
.invisibleLabel
);
2680 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
2685 * @event labelChange
2686 * @param {string} value
2689 /* Static Properties */
2692 * The label text. The label can be specified as a plaintext string, a function that will
2693 * produce a string in the future, or `null` for no label. The static value will
2694 * be overridden if a label is specified with the #label config option.
2698 * @property {string|Function|null}
2700 OO
.ui
.mixin
.LabelElement
.static.label
= null;
2702 /* Static methods */
2705 * Highlight the first occurrence of the query in the given text
2707 * @param {string} text Text
2708 * @param {string} query Query to find
2709 * @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
2710 * @return {jQuery} Text with the first match of the query
2711 * sub-string wrapped in highlighted span
2713 OO
.ui
.mixin
.LabelElement
.static.highlightQuery = function ( text
, query
, compare
) {
2716 $result
= $( '<span>' );
2720 qLen
= query
.length
;
2721 for ( i
= 0; offset
=== -1 && i
<= tLen
- qLen
; i
++ ) {
2722 if ( compare( query
, text
.slice( i
, i
+ qLen
) ) === 0 ) {
2727 offset
= text
.toLowerCase().indexOf( query
.toLowerCase() );
2730 if ( !query
.length
|| offset
=== -1 ) {
2731 $result
.text( text
);
2734 document
.createTextNode( text
.slice( 0, offset
) ),
2736 .addClass( 'oo-ui-labelElement-label-highlight' )
2737 .text( text
.slice( offset
, offset
+ query
.length
) ),
2738 document
.createTextNode( text
.slice( offset
+ query
.length
) )
2741 return $result
.contents();
2747 * Set the label element.
2749 * If an element is already set, it will be cleaned up before setting up the new element.
2751 * @param {jQuery} $label Element to use as label
2753 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
2754 if ( this.$label
) {
2755 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
2758 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
2759 this.setLabelContent( this.label
);
2765 * An empty string will result in the label being hidden. A string containing only whitespace will
2766 * be converted to a single ` `.
2768 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
2769 * text; or null for no label
2771 * @return {OO.ui.Element} The element, for chaining
2773 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
2774 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
2775 label
= ( ( typeof label
=== 'string' || label
instanceof $ ) && label
.length
) || ( label
instanceof OO
.ui
.HtmlSnippet
&& label
.toString().length
) ? label
: null;
2777 if ( this.label
!== label
) {
2778 if ( this.$label
) {
2779 this.setLabelContent( label
);
2782 this.emit( 'labelChange' );
2785 this.$element
.toggleClass( 'oo-ui-labelElement', !!this.label
&& !this.invisibleLabel
);
2791 * Set whether the label should be visually hidden (but still accessible to screen-readers).
2793 * @param {boolean} invisibleLabel
2795 * @return {OO.ui.Element} The element, for chaining
2797 OO
.ui
.mixin
.LabelElement
.prototype.setInvisibleLabel = function ( invisibleLabel
) {
2798 invisibleLabel
= !!invisibleLabel
;
2800 if ( this.invisibleLabel
!== invisibleLabel
) {
2801 this.invisibleLabel
= invisibleLabel
;
2802 this.emit( 'labelChange' );
2805 this.$label
.toggleClass( 'oo-ui-labelElement-invisible', this.invisibleLabel
);
2806 // Pretend that there is no label, a lot of CSS has been written with this assumption
2807 this.$element
.toggleClass( 'oo-ui-labelElement', !!this.label
&& !this.invisibleLabel
);
2813 * Set the label as plain text with a highlighted query
2815 * @param {string} text Text label to set
2816 * @param {string} query Substring of text to highlight
2817 * @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
2819 * @return {OO.ui.Element} The element, for chaining
2821 OO
.ui
.mixin
.LabelElement
.prototype.setHighlightedQuery = function ( text
, query
, compare
) {
2822 return this.setLabel( this.constructor.static.highlightQuery( text
, query
, compare
) );
2828 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
2829 * text; or null for no label
2831 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
2836 * Set the content of the label.
2838 * Do not call this method until after the label element has been set by #setLabelElement.
2841 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
2842 * text; or null for no label
2844 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
2845 if ( typeof label
=== 'string' ) {
2846 if ( label
.match( /^\s*$/ ) ) {
2847 // Convert whitespace only string to a single non-breaking space
2848 this.$label
.html( ' ' );
2850 this.$label
.text( label
);
2852 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
2853 this.$label
.html( label
.toString() );
2854 } else if ( label
instanceof $ ) {
2855 this.$label
.empty().append( label
);
2857 this.$label
.empty();
2862 * IconElement is often mixed into other classes to generate an icon.
2863 * Icons are graphics, about the size of normal text. They are used to aid the user
2864 * in locating a control or to convey information in a space-efficient way. See the
2865 * [OOUI documentation on MediaWiki] [1] for a list of icons
2866 * included in the library.
2868 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
2874 * @param {Object} [config] Configuration options
2875 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2876 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2877 * the icon element be set to an existing icon instead of the one generated by this class, set a
2878 * value using a jQuery selection. For example:
2880 * // Use a <div> tag instead of a <span>
2881 * $icon: $( '<div>' )
2882 * // Use an existing icon element instead of the one generated by the class
2883 * $icon: this.$element
2884 * // Use an icon element from a child widget
2885 * $icon: this.childwidget.$element
2886 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
2887 * symbolic names. A map is used for i18n purposes and contains a `default` icon
2888 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
2889 * by the user's language.
2891 * Example of an i18n map:
2893 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2894 * See the [OOUI documentation on MediaWiki] [2] for a list of icons included in the library.
2895 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
2896 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
2897 * text. The icon title is displayed when users move the mouse over the icon.
2899 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
2900 // Configuration initialization
2901 config
= config
|| {};
2906 this.iconTitle
= null;
2908 // `iconTitle`s are deprecated since 0.30.0
2909 if ( config
.iconTitle
!== undefined ) {
2910 OO
.ui
.warnDeprecation( 'IconElement: Widgets with iconTitle set are deprecated, use title instead. See T76638 for details.' );
2914 this.setIcon( config
.icon
|| this.constructor.static.icon
);
2915 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
2916 this.setIconElement( config
.$icon
|| $( '<span>' ) );
2921 OO
.initClass( OO
.ui
.mixin
.IconElement
);
2923 /* Static Properties */
2926 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
2927 * for i18n purposes and contains a `default` icon name and additional names keyed by
2928 * language code. The `default` name is used when no icon is keyed by the user's language.
2930 * Example of an i18n map:
2932 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2934 * Note: the static property will be overridden if the #icon configuration is used.
2938 * @property {Object|string}
2940 OO
.ui
.mixin
.IconElement
.static.icon
= null;
2943 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2944 * function that returns title text, or `null` for no title.
2946 * The static property will be overridden if the #iconTitle configuration is used.
2950 * @property {string|Function|null}
2952 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
2957 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2958 * applies to the specified icon element instead of the one created by the class. If an icon
2959 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2960 * and mixin methods will no longer affect the element.
2962 * @param {jQuery} $icon Element to use as icon
2964 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
2967 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
2968 .removeAttr( 'title' );
2972 .addClass( 'oo-ui-iconElement-icon' )
2973 .toggleClass( 'oo-ui-iconElement-noIcon', !this.icon
)
2974 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
2975 if ( this.iconTitle
!== null ) {
2976 this.$icon
.attr( 'title', this.iconTitle
);
2979 this.updateThemeClasses();
2983 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
2984 * The icon parameter can also be set to a map of icon names. See the #icon config setting
2987 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
2988 * by language code, or `null` to remove the icon.
2990 * @return {OO.ui.Element} The element, for chaining
2992 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
2993 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
2994 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
2996 if ( this.icon
!== icon
) {
2998 if ( this.icon
!== null ) {
2999 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
3001 if ( icon
!== null ) {
3002 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
3008 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
3010 this.$icon
.toggleClass( 'oo-ui-iconElement-noIcon', !this.icon
);
3012 this.updateThemeClasses();
3018 * Set the icon title. Use `null` to remove the title.
3020 * @param {string|Function|null} iconTitle A text string used as the icon title,
3021 * a function that returns title text, or `null` for no title.
3023 * @return {OO.ui.Element} The element, for chaining
3026 OO
.ui
.mixin
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
3028 ( typeof iconTitle
=== 'function' || ( typeof iconTitle
=== 'string' && iconTitle
.length
) ) ?
3029 OO
.ui
.resolveMsg( iconTitle
) : null;
3031 if ( this.iconTitle
!== iconTitle
) {
3032 this.iconTitle
= iconTitle
;
3034 if ( this.iconTitle
!== null ) {
3035 this.$icon
.attr( 'title', iconTitle
);
3037 this.$icon
.removeAttr( 'title' );
3042 // `setIconTitle is deprecated since 0.30.0
3043 if ( iconTitle
!== null ) {
3044 // Avoid a warning when this is called from the constructor with no iconTitle set
3045 OO
.ui
.warnDeprecation( 'IconElement: setIconTitle is deprecated, use setTitle of TitledElement instead. See T76638 for details.' );
3052 * Get the symbolic name of the icon.
3054 * @return {string} Icon name
3056 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
3061 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
3063 * @return {string} Icon title text
3065 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
3066 return this.iconTitle
;
3070 * IndicatorElement is often mixed into other classes to generate an indicator.
3071 * Indicators are small graphics that are generally used in two ways:
3073 * - To draw attention to the status of an item. For example, an indicator might be
3074 * used to show that an item in a list has errors that need to be resolved.
3075 * - To clarify the function of a control that acts in an exceptional way (a button
3076 * that opens a menu instead of performing an action directly, for example).
3078 * For a list of indicators included in the library, please see the
3079 * [OOUI documentation on MediaWiki] [1].
3081 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3087 * @param {Object} [config] Configuration options
3088 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
3089 * configuration is omitted, the indicator element will use a generated `<span>`.
3090 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3091 * See the [OOUI documentation on MediaWiki][2] for a list of indicators included
3093 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3094 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
3095 * or a function that returns title text. The indicator title is displayed when users move
3096 * the mouse over the indicator.
3098 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
3099 // Configuration initialization
3100 config
= config
|| {};
3103 this.$indicator
= null;
3104 this.indicator
= null;
3105 this.indicatorTitle
= null;
3107 // `indicatorTitle`s are deprecated since 0.30.0
3108 if ( config
.indicatorTitle
!== undefined ) {
3109 OO
.ui
.warnDeprecation( 'IndicatorElement: Widgets with indicatorTitle set are deprecated, use title instead. See T76638 for details.' );
3113 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
3114 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
3115 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
3120 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
3122 /* Static Properties */
3125 * Symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3126 * The static property will be overridden if the #indicator configuration is used.
3130 * @property {string|null}
3132 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
3135 * A text string used as the indicator title, a function that returns title text, or `null`
3136 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
3140 * @property {string|Function|null}
3142 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
3147 * Set the indicator element.
3149 * If an element is already set, it will be cleaned up before setting up the new element.
3151 * @param {jQuery} $indicator Element to use as indicator
3153 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
3154 if ( this.$indicator
) {
3156 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
3157 .removeAttr( 'title' );
3160 this.$indicator
= $indicator
3161 .addClass( 'oo-ui-indicatorElement-indicator' )
3162 .toggleClass( 'oo-ui-indicatorElement-noIndicator', !this.indicator
)
3163 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
3164 if ( this.indicatorTitle
!== null ) {
3165 this.$indicator
.attr( 'title', this.indicatorTitle
);
3168 this.updateThemeClasses();
3172 * Set the indicator by its symbolic name: ‘clear’, ‘down’, ‘required’, ‘search’, ‘up’. Use `null` to remove the indicator.
3174 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
3176 * @return {OO.ui.Element} The element, for chaining
3178 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
3179 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
3181 if ( this.indicator
!== indicator
) {
3182 if ( this.$indicator
) {
3183 if ( this.indicator
!== null ) {
3184 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
3186 if ( indicator
!== null ) {
3187 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
3190 this.indicator
= indicator
;
3193 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
3194 if ( this.$indicator
) {
3195 this.$indicator
.toggleClass( 'oo-ui-indicatorElement-noIndicator', !this.indicator
);
3197 this.updateThemeClasses();
3203 * Set the indicator title.
3205 * The title is displayed when a user moves the mouse over the indicator.
3207 * @param {string|Function|null} indicatorTitle Indicator title text, a function that returns text, or
3208 * `null` for no indicator title
3210 * @return {OO.ui.Element} The element, for chaining
3213 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
3215 ( typeof indicatorTitle
=== 'function' || ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ) ?
3216 OO
.ui
.resolveMsg( indicatorTitle
) : null;
3218 if ( this.indicatorTitle
!== indicatorTitle
) {
3219 this.indicatorTitle
= indicatorTitle
;
3220 if ( this.$indicator
) {
3221 if ( this.indicatorTitle
!== null ) {
3222 this.$indicator
.attr( 'title', indicatorTitle
);
3224 this.$indicator
.removeAttr( 'title' );
3229 // `setIndicatorTitle is deprecated since 0.30.0
3230 if ( indicatorTitle
!== null ) {
3231 // Avoid a warning when this is called from the constructor with no indicatorTitle set
3232 OO
.ui
.warnDeprecation( 'IndicatorElement: setIndicatorTitle is deprecated, use setTitle of TitledElement instead. See T76638 for details.' );
3239 * Get the symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3241 * @return {string} Symbolic name of indicator
3243 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
3244 return this.indicator
;
3248 * Get the indicator title.
3250 * The title is displayed when a user moves the mouse over the indicator.
3252 * @return {string} Indicator title text
3254 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
3255 return this.indicatorTitle
;
3259 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
3260 * additional functionality to an element created by another class. The class provides
3261 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
3262 * which are used to customize the look and feel of a widget to better describe its
3263 * importance and functionality.
3265 * The library currently contains the following styling flags for general use:
3267 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
3268 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
3270 * The flags affect the appearance of the buttons:
3273 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
3274 * var button1 = new OO.ui.ButtonWidget( {
3275 * label: 'Progressive',
3276 * flags: 'progressive'
3278 * button2 = new OO.ui.ButtonWidget( {
3279 * label: 'Destructive',
3280 * flags: 'destructive'
3282 * $( document.body ).append( button1.$element, button2.$element );
3284 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
3285 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
3287 * [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
3293 * @param {Object} [config] Configuration options
3294 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'progressive' or 'primary') to apply.
3295 * Please see the [OOUI documentation on MediaWiki] [2] for more information about available flags.
3296 * [2]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
3297 * @cfg {jQuery} [$flagged] The flagged element. By default,
3298 * the flagged functionality is applied to the element created by the class ($element).
3299 * If a different element is specified, the flagged functionality will be applied to it instead.
3301 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
3302 // Configuration initialization
3303 config
= config
|| {};
3307 this.$flagged
= null;
3310 this.setFlags( config
.flags
);
3311 this.setFlaggedElement( config
.$flagged
|| this.$element
);
3318 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
3319 * parameter contains the name of each modified flag and indicates whether it was
3322 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
3323 * that the flag was added, `false` that the flag was removed.
3329 * Set the flagged element.
3331 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
3332 * If an element is already set, the method will remove the mixin’s effect on that element.
3334 * @param {jQuery} $flagged Element that should be flagged
3336 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
3337 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
3338 return 'oo-ui-flaggedElement-' + flag
;
3341 if ( this.$flagged
) {
3342 this.$flagged
.removeClass( classNames
);
3345 this.$flagged
= $flagged
.addClass( classNames
);
3349 * Check if the specified flag is set.
3351 * @param {string} flag Name of flag
3352 * @return {boolean} The flag is set
3354 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
3355 // This may be called before the constructor, thus before this.flags is set
3356 return this.flags
&& ( flag
in this.flags
);
3360 * Get the names of all flags set.
3362 * @return {string[]} Flag names
3364 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
3365 // This may be called before the constructor, thus before this.flags is set
3366 return Object
.keys( this.flags
|| {} );
3373 * @return {OO.ui.Element} The element, for chaining
3376 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
3377 var flag
, className
,
3380 classPrefix
= 'oo-ui-flaggedElement-';
3382 for ( flag
in this.flags
) {
3383 className
= classPrefix
+ flag
;
3384 changes
[ flag
] = false;
3385 delete this.flags
[ flag
];
3386 remove
.push( className
);
3389 if ( this.$flagged
) {
3390 this.$flagged
.removeClass( remove
);
3393 this.updateThemeClasses();
3394 this.emit( 'flag', changes
);
3400 * Add one or more flags.
3402 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
3403 * or an object keyed by flag name with a boolean value that indicates whether the flag should
3404 * be added (`true`) or removed (`false`).
3406 * @return {OO.ui.Element} The element, for chaining
3409 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
3410 var i
, len
, flag
, className
,
3414 classPrefix
= 'oo-ui-flaggedElement-';
3416 if ( typeof flags
=== 'string' ) {
3417 className
= classPrefix
+ flags
;
3419 if ( !this.flags
[ flags
] ) {
3420 this.flags
[ flags
] = true;
3421 add
.push( className
);
3423 } else if ( Array
.isArray( flags
) ) {
3424 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
3426 className
= classPrefix
+ flag
;
3428 if ( !this.flags
[ flag
] ) {
3429 changes
[ flag
] = true;
3430 this.flags
[ flag
] = true;
3431 add
.push( className
);
3434 } else if ( OO
.isPlainObject( flags
) ) {
3435 for ( flag
in flags
) {
3436 className
= classPrefix
+ flag
;
3437 if ( flags
[ flag
] ) {
3439 if ( !this.flags
[ flag
] ) {
3440 changes
[ flag
] = true;
3441 this.flags
[ flag
] = true;
3442 add
.push( className
);
3446 if ( this.flags
[ flag
] ) {
3447 changes
[ flag
] = false;
3448 delete this.flags
[ flag
];
3449 remove
.push( className
);
3455 if ( this.$flagged
) {
3458 .removeClass( remove
);
3461 this.updateThemeClasses();
3462 this.emit( 'flag', changes
);
3468 * TitledElement is mixed into other classes to provide a `title` attribute.
3469 * Titles are rendered by the browser and are made visible when the user moves
3470 * the mouse over the element. Titles are not visible on touch devices.
3473 * // TitledElement provides a `title` attribute to the
3474 * // ButtonWidget class.
3475 * var button = new OO.ui.ButtonWidget( {
3476 * label: 'Button with Title',
3477 * title: 'I am a button'
3479 * $( document.body ).append( button.$element );
3485 * @param {Object} [config] Configuration options
3486 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
3487 * If this config is omitted, the title functionality is applied to $element, the
3488 * element created by the class.
3489 * @cfg {string|Function} [title] The title text or a function that returns text. If
3490 * this config is omitted, the value of the {@link #static-title static title} property is used.
3492 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
3493 // Configuration initialization
3494 config
= config
|| {};
3497 this.$titled
= null;
3501 this.setTitle( config
.title
!== undefined ? config
.title
: this.constructor.static.title
);
3502 this.setTitledElement( config
.$titled
|| this.$element
);
3507 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
3509 /* Static Properties */
3512 * The title text, a function that returns text, or `null` for no title. The value of the static property
3513 * is overridden if the #title config option is used.
3517 * @property {string|Function|null}
3519 OO
.ui
.mixin
.TitledElement
.static.title
= null;
3524 * Set the titled element.
3526 * This method is used to retarget a TitledElement mixin so that its functionality applies to the specified element.
3527 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
3529 * @param {jQuery} $titled Element that should use the 'titled' functionality
3531 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
3532 if ( this.$titled
) {
3533 this.$titled
.removeAttr( 'title' );
3536 this.$titled
= $titled
;
3545 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
3547 * @return {OO.ui.Element} The element, for chaining
3549 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
3550 title
= typeof title
=== 'function' ? OO
.ui
.resolveMsg( title
) : title
;
3551 title
= ( typeof title
=== 'string' && title
.length
) ? title
: null;
3553 if ( this.title
!== title
) {
3562 * Update the title attribute, in case of changes to title or accessKey.
3566 * @return {OO.ui.Element} The element, for chaining
3568 OO
.ui
.mixin
.TitledElement
.prototype.updateTitle = function () {
3569 var title
= this.getTitle();
3570 if ( this.$titled
) {
3571 if ( title
!== null ) {
3572 // Only if this is an AccessKeyedElement
3573 if ( this.formatTitleWithAccessKey
) {
3574 title
= this.formatTitleWithAccessKey( title
);
3576 this.$titled
.attr( 'title', title
);
3578 this.$titled
.removeAttr( 'title' );
3587 * @return {string} Title string
3589 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
3594 * AccessKeyedElement is mixed into other classes to provide an `accesskey` HTML attribute.
3595 * Accesskeys allow an user to go to a specific element by using
3596 * a shortcut combination of a browser specific keys + the key
3600 * // AccessKeyedElement provides an `accesskey` attribute to the
3601 * // ButtonWidget class.
3602 * var button = new OO.ui.ButtonWidget( {
3603 * label: 'Button with Accesskey',
3606 * $( document.body ).append( button.$element );
3612 * @param {Object} [config] Configuration options
3613 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3614 * If this config is omitted, the accesskey functionality is applied to $element, the
3615 * element created by the class.
3616 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3617 * this config is omitted, no accesskey will be added.
3619 OO
.ui
.mixin
.AccessKeyedElement
= function OoUiMixinAccessKeyedElement( config
) {
3620 // Configuration initialization
3621 config
= config
|| {};
3624 this.$accessKeyed
= null;
3625 this.accessKey
= null;
3628 this.setAccessKey( config
.accessKey
|| null );
3629 this.setAccessKeyedElement( config
.$accessKeyed
|| this.$element
);
3631 // If this is also a TitledElement and it initialized before we did, we may have
3632 // to update the title with the access key
3633 if ( this.updateTitle
) {
3640 OO
.initClass( OO
.ui
.mixin
.AccessKeyedElement
);
3642 /* Static Properties */
3645 * The access key, a function that returns a key, or `null` for no accesskey.
3649 * @property {string|Function|null}
3651 OO
.ui
.mixin
.AccessKeyedElement
.static.accessKey
= null;
3656 * Set the accesskeyed element.
3658 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
3659 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
3661 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyed' functionality
3663 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKeyedElement = function ( $accessKeyed
) {
3664 if ( this.$accessKeyed
) {
3665 this.$accessKeyed
.removeAttr( 'accesskey' );
3668 this.$accessKeyed
= $accessKeyed
;
3669 if ( this.accessKey
) {
3670 this.$accessKeyed
.attr( 'accesskey', this.accessKey
);
3677 * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no accesskey
3679 * @return {OO.ui.Element} The element, for chaining
3681 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKey = function ( accessKey
) {
3682 accessKey
= typeof accessKey
=== 'string' ? OO
.ui
.resolveMsg( accessKey
) : null;
3684 if ( this.accessKey
!== accessKey
) {
3685 if ( this.$accessKeyed
) {
3686 if ( accessKey
!== null ) {
3687 this.$accessKeyed
.attr( 'accesskey', accessKey
);
3689 this.$accessKeyed
.removeAttr( 'accesskey' );
3692 this.accessKey
= accessKey
;
3694 // Only if this is a TitledElement
3695 if ( this.updateTitle
) {
3706 * @return {string} accessKey string
3708 OO
.ui
.mixin
.AccessKeyedElement
.prototype.getAccessKey = function () {
3709 return this.accessKey
;
3713 * Add information about the access key to the element's tooltip label.
3714 * (This is only public for hacky usage in FieldLayout.)
3716 * @param {string} title Tooltip label for `title` attribute
3719 OO
.ui
.mixin
.AccessKeyedElement
.prototype.formatTitleWithAccessKey = function ( title
) {
3722 if ( !this.$accessKeyed
) {
3723 // Not initialized yet; the constructor will call updateTitle() which will rerun this function
3726 // Use jquery.accessKeyLabel if available to show modifiers, otherwise just display the single key
3727 if ( $.fn
.updateTooltipAccessKeys
&& $.fn
.updateTooltipAccessKeys
.getAccessKeyLabel
) {
3728 accessKey
= $.fn
.updateTooltipAccessKeys
.getAccessKeyLabel( this.$accessKeyed
[ 0 ] );
3730 accessKey
= this.getAccessKey();
3733 title
+= ' [' + accessKey
+ ']';
3739 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3740 * feels, and functionality can be customized via the class’s configuration options
3741 * and methods. Please see the [OOUI documentation on MediaWiki] [1] for more information
3744 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches
3747 * // A button widget.
3748 * var button = new OO.ui.ButtonWidget( {
3749 * label: 'Button with Icon',
3753 * $( document.body ).append( button.$element );
3755 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3758 * @extends OO.ui.Widget
3759 * @mixins OO.ui.mixin.ButtonElement
3760 * @mixins OO.ui.mixin.IconElement
3761 * @mixins OO.ui.mixin.IndicatorElement
3762 * @mixins OO.ui.mixin.LabelElement
3763 * @mixins OO.ui.mixin.TitledElement
3764 * @mixins OO.ui.mixin.FlaggedElement
3765 * @mixins OO.ui.mixin.TabIndexedElement
3766 * @mixins OO.ui.mixin.AccessKeyedElement
3769 * @param {Object} [config] Configuration options
3770 * @cfg {boolean} [active=false] Whether button should be shown as active
3771 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3772 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3773 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3775 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
3776 // Configuration initialization
3777 config
= config
|| {};
3779 // Parent constructor
3780 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
3782 // Mixin constructors
3783 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
3784 OO
.ui
.mixin
.IconElement
.call( this, config
);
3785 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
3786 OO
.ui
.mixin
.LabelElement
.call( this, config
);
3787 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
3788 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
3789 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
3790 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$button
} ) );
3795 this.noFollow
= false;
3798 this.connect( this, { disable
: 'onDisable' } );
3801 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
3803 .addClass( 'oo-ui-buttonWidget' )
3804 .append( this.$button
);
3805 this.setActive( config
.active
);
3806 this.setHref( config
.href
);
3807 this.setTarget( config
.target
);
3808 this.setNoFollow( config
.noFollow
);
3813 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
3814 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
3815 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
3816 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
3817 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
3818 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
3819 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
3820 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
3821 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
3823 /* Static Properties */
3829 OO
.ui
.ButtonWidget
.static.cancelButtonMouseDownEvents
= false;
3835 OO
.ui
.ButtonWidget
.static.tagName
= 'span';
3840 * Get hyperlink location.
3842 * @return {string} Hyperlink location
3844 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
3849 * Get hyperlink target.
3851 * @return {string} Hyperlink target
3853 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
3858 * Get search engine traversal hint.
3860 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3862 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
3863 return this.noFollow
;
3867 * Set hyperlink location.
3869 * @param {string|null} href Hyperlink location, null to remove
3871 * @return {OO.ui.Widget} The widget, for chaining
3873 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
3874 href
= typeof href
=== 'string' ? href
: null;
3875 if ( href
!== null && !OO
.ui
.isSafeUrl( href
) ) {
3879 if ( href
!== this.href
) {
3888 * Update the `href` attribute, in case of changes to href or
3893 * @return {OO.ui.Widget} The widget, for chaining
3895 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
3896 if ( this.href
!== null && !this.isDisabled() ) {
3897 this.$button
.attr( 'href', this.href
);
3899 this.$button
.removeAttr( 'href' );
3906 * Handle disable events.
3909 * @param {boolean} disabled Element is disabled
3911 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
3916 * Set hyperlink target.
3918 * @param {string|null} target Hyperlink target, null to remove
3919 * @return {OO.ui.Widget} The widget, for chaining
3921 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
3922 target
= typeof target
=== 'string' ? target
: null;
3924 if ( target
!== this.target
) {
3925 this.target
= target
;
3926 if ( target
!== null ) {
3927 this.$button
.attr( 'target', target
);
3929 this.$button
.removeAttr( 'target' );
3937 * Set search engine traversal hint.
3939 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3940 * @return {OO.ui.Widget} The widget, for chaining
3942 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
3943 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
3945 if ( noFollow
!== this.noFollow
) {
3946 this.noFollow
= noFollow
;
3948 this.$button
.attr( 'rel', 'nofollow' );
3950 this.$button
.removeAttr( 'rel' );
3957 // Override method visibility hints from ButtonElement
3968 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3969 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3970 * removed, and cleared from the group.
3973 * // A ButtonGroupWidget with two buttons.
3974 * var button1 = new OO.ui.PopupButtonWidget( {
3975 * label: 'Select a category',
3978 * $content: $( '<p>List of categories…</p>' ),
3983 * button2 = new OO.ui.ButtonWidget( {
3986 * buttonGroup = new OO.ui.ButtonGroupWidget( {
3987 * items: [ button1, button2 ]
3989 * $( document.body ).append( buttonGroup.$element );
3992 * @extends OO.ui.Widget
3993 * @mixins OO.ui.mixin.GroupElement
3994 * @mixins OO.ui.mixin.TitledElement
3997 * @param {Object} [config] Configuration options
3998 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
4000 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
4001 // Configuration initialization
4002 config
= config
|| {};
4004 // Parent constructor
4005 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
4007 // Mixin constructors
4008 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
4009 OO
.ui
.mixin
.TitledElement
.call( this, config
);
4012 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
4013 if ( Array
.isArray( config
.items
) ) {
4014 this.addItems( config
.items
);
4020 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
4021 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
4022 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.TitledElement
);
4024 /* Static Properties */
4030 OO
.ui
.ButtonGroupWidget
.static.tagName
= 'span';
4038 * @return {OO.ui.Widget} The widget, for chaining
4040 OO
.ui
.ButtonGroupWidget
.prototype.focus = function () {
4041 if ( !this.isDisabled() ) {
4042 if ( this.items
[ 0 ] ) {
4043 this.items
[ 0 ].focus();
4052 OO
.ui
.ButtonGroupWidget
.prototype.simulateLabelClick = function () {
4057 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
4058 * which creates a label that identifies the icon’s function. See the [OOUI documentation on MediaWiki] [1]
4059 * for a list of icons included in the library.
4062 * // An IconWidget with a label via LabelWidget.
4063 * var myIcon = new OO.ui.IconWidget( {
4067 * // Create a label.
4068 * iconLabel = new OO.ui.LabelWidget( {
4071 * $( document.body ).append( myIcon.$element, iconLabel.$element );
4073 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
4076 * @extends OO.ui.Widget
4077 * @mixins OO.ui.mixin.IconElement
4078 * @mixins OO.ui.mixin.TitledElement
4079 * @mixins OO.ui.mixin.LabelElement
4080 * @mixins OO.ui.mixin.FlaggedElement
4083 * @param {Object} [config] Configuration options
4085 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
4086 // Configuration initialization
4087 config
= config
|| {};
4089 // Parent constructor
4090 OO
.ui
.IconWidget
.parent
.call( this, config
);
4092 // Mixin constructors
4093 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
4094 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
4095 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
, invisibleLabel
: true } ) );
4096 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
4099 this.$element
.addClass( 'oo-ui-iconWidget' );
4100 // Remove class added by LabelElement initialization. It causes unexpected CSS to apply when
4101 // nested in other widgets, because this widget used to not mix in LabelElement.
4102 this.$element
.removeClass( 'oo-ui-labelElement-label' );
4107 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
4108 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
4109 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
4110 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.LabelElement
);
4111 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
4113 /* Static Properties */
4119 OO
.ui
.IconWidget
.static.tagName
= 'span';
4122 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
4123 * attention to the status of an item or to clarify the function within a control. For a list of
4124 * indicators included in the library, please see the [OOUI documentation on MediaWiki][1].
4127 * // An indicator widget.
4128 * var indicator1 = new OO.ui.IndicatorWidget( {
4129 * indicator: 'required'
4131 * // Create a fieldset layout to add a label.
4132 * fieldset = new OO.ui.FieldsetLayout();
4133 * fieldset.addItems( [
4134 * new OO.ui.FieldLayout( indicator1, {
4135 * label: 'A required indicator:'
4138 * $( document.body ).append( fieldset.$element );
4140 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
4143 * @extends OO.ui.Widget
4144 * @mixins OO.ui.mixin.IndicatorElement
4145 * @mixins OO.ui.mixin.TitledElement
4146 * @mixins OO.ui.mixin.LabelElement
4149 * @param {Object} [config] Configuration options
4151 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
4152 // Configuration initialization
4153 config
= config
|| {};
4155 // Parent constructor
4156 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
4158 // Mixin constructors
4159 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
4160 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
4161 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
, invisibleLabel
: true } ) );
4164 this.$element
.addClass( 'oo-ui-indicatorWidget' );
4165 // Remove class added by LabelElement initialization. It causes unexpected CSS to apply when
4166 // nested in other widgets, because this widget used to not mix in LabelElement.
4167 this.$element
.removeClass( 'oo-ui-labelElement-label' );
4172 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
4173 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
4174 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
4175 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.LabelElement
);
4177 /* Static Properties */
4183 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
4186 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
4187 * be configured with a `label` option that is set to a string, a label node, or a function:
4189 * - String: a plaintext string
4190 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
4191 * label that includes a link or special styling, such as a gray color or additional graphical elements.
4192 * - Function: a function that will produce a string in the future. Functions are used
4193 * in cases where the value of the label is not currently defined.
4195 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
4196 * will come into focus when the label is clicked.
4199 * // Two LabelWidgets.
4200 * var label1 = new OO.ui.LabelWidget( {
4201 * label: 'plaintext label'
4203 * label2 = new OO.ui.LabelWidget( {
4204 * label: $( '<a>' ).attr( 'href', 'default.html' ).text( 'jQuery label' )
4206 * // Create a fieldset layout with fields for each example.
4207 * fieldset = new OO.ui.FieldsetLayout();
4208 * fieldset.addItems( [
4209 * new OO.ui.FieldLayout( label1 ),
4210 * new OO.ui.FieldLayout( label2 )
4212 * $( document.body ).append( fieldset.$element );
4215 * @extends OO.ui.Widget
4216 * @mixins OO.ui.mixin.LabelElement
4217 * @mixins OO.ui.mixin.TitledElement
4220 * @param {Object} [config] Configuration options
4221 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
4222 * Clicking the label will focus the specified input field.
4224 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
4225 // Configuration initialization
4226 config
= config
|| {};
4228 // Parent constructor
4229 OO
.ui
.LabelWidget
.parent
.call( this, config
);
4231 // Mixin constructors
4232 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
4233 OO
.ui
.mixin
.TitledElement
.call( this, config
);
4236 this.input
= config
.input
;
4240 if ( this.input
.getInputId() ) {
4241 this.$element
.attr( 'for', this.input
.getInputId() );
4243 this.$label
.on( 'click', function () {
4244 this.input
.simulateLabelClick();
4248 this.$element
.addClass( 'oo-ui-labelWidget' );
4253 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
4254 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
4255 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
4257 /* Static Properties */
4263 OO
.ui
.LabelWidget
.static.tagName
= 'label';
4266 * PendingElement is a mixin that is used to create elements that notify users that something is happening
4267 * and that they should wait before proceeding. The pending state is visually represented with a pending
4268 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
4269 * field of a {@link OO.ui.TextInputWidget text input widget}.
4271 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
4272 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
4273 * in process dialogs.
4276 * function MessageDialog( config ) {
4277 * MessageDialog.parent.call( this, config );
4279 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
4281 * MessageDialog.static.name = 'myMessageDialog';
4282 * MessageDialog.static.actions = [
4283 * { action: 'save', label: 'Done', flags: 'primary' },
4284 * { label: 'Cancel', flags: 'safe' }
4287 * MessageDialog.prototype.initialize = function () {
4288 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
4289 * this.content = new OO.ui.PanelLayout( { padded: true } );
4290 * this.content.$element.append( '<p>Click the \'Done\' action widget to see its pending state. Note that action widgets can be marked pending in message dialogs but not process dialogs.</p>' );
4291 * this.$body.append( this.content.$element );
4293 * MessageDialog.prototype.getBodyHeight = function () {
4296 * MessageDialog.prototype.getActionProcess = function ( action ) {
4297 * var dialog = this;
4298 * if ( action === 'save' ) {
4299 * dialog.getActions().get({actions: 'save'})[0].pushPending();
4300 * return new OO.ui.Process()
4302 * .next( function () {
4303 * dialog.getActions().get({actions: 'save'})[0].popPending();
4306 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
4309 * var windowManager = new OO.ui.WindowManager();
4310 * $( document.body ).append( windowManager.$element );
4312 * var dialog = new MessageDialog();
4313 * windowManager.addWindows( [ dialog ] );
4314 * windowManager.openWindow( dialog );
4320 * @param {Object} [config] Configuration options
4321 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
4323 OO
.ui
.mixin
.PendingElement
= function OoUiMixinPendingElement( config
) {
4324 // Configuration initialization
4325 config
= config
|| {};
4329 this.$pending
= null;
4332 this.setPendingElement( config
.$pending
|| this.$element
);
4337 OO
.initClass( OO
.ui
.mixin
.PendingElement
);
4342 * Set the pending element (and clean up any existing one).
4344 * @param {jQuery} $pending The element to set to pending.
4346 OO
.ui
.mixin
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
4347 if ( this.$pending
) {
4348 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
4351 this.$pending
= $pending
;
4352 if ( this.pending
> 0 ) {
4353 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
4358 * Check if an element is pending.
4360 * @return {boolean} Element is pending
4362 OO
.ui
.mixin
.PendingElement
.prototype.isPending = function () {
4363 return !!this.pending
;
4367 * Increase the pending counter. The pending state will remain active until the counter is zero
4368 * (i.e., the number of calls to #pushPending and #popPending is the same).
4371 * @return {OO.ui.Element} The element, for chaining
4373 OO
.ui
.mixin
.PendingElement
.prototype.pushPending = function () {
4374 if ( this.pending
=== 0 ) {
4375 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
4376 this.updateThemeClasses();
4384 * Decrease the pending counter. The pending state will remain active until the counter is zero
4385 * (i.e., the number of calls to #pushPending and #popPending is the same).
4388 * @return {OO.ui.Element} The element, for chaining
4390 OO
.ui
.mixin
.PendingElement
.prototype.popPending = function () {
4391 if ( this.pending
=== 1 ) {
4392 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
4393 this.updateThemeClasses();
4395 this.pending
= Math
.max( 0, this.pending
- 1 );
4401 * Element that will stick adjacent to a specified container, even when it is inserted elsewhere
4402 * in the document (for example, in an OO.ui.Window's $overlay).
4404 * The elements's position is automatically calculated and maintained when window is resized or the
4405 * page is scrolled. If you reposition the container manually, you have to call #position to make
4406 * sure the element is still placed correctly.
4408 * As positioning is only possible when both the element and the container are attached to the DOM
4409 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
4410 * the #toggle method to display a floating popup, for example.
4416 * @param {Object} [config] Configuration options
4417 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
4418 * @cfg {jQuery} [$floatableContainer] Node to position adjacent to
4419 * @cfg {string} [verticalPosition='below'] Where to position $floatable vertically:
4420 * 'below': Directly below $floatableContainer, aligning f's top edge with fC's bottom edge
4421 * 'above': Directly above $floatableContainer, aligning f's bottom edge with fC's top edge
4422 * 'top': Align the top edge with $floatableContainer's top edge
4423 * 'bottom': Align the bottom edge with $floatableContainer's bottom edge
4424 * 'center': Vertically align the center with $floatableContainer's center
4425 * @cfg {string} [horizontalPosition='start'] Where to position $floatable horizontally:
4426 * 'before': Directly before $floatableContainer, aligning f's end edge with fC's start edge
4427 * 'after': Directly after $floatableContainer, aligning f's start edge with fC's end edge
4428 * 'start': Align the start (left in LTR, right in RTL) edge with $floatableContainer's start edge
4429 * 'end': Align the end (right in LTR, left in RTL) edge with $floatableContainer's end edge
4430 * 'center': Horizontally align the center with $floatableContainer's center
4431 * @cfg {boolean} [hideWhenOutOfView=true] Whether to hide the floatable element if the container
4434 OO
.ui
.mixin
.FloatableElement
= function OoUiMixinFloatableElement( config
) {
4435 // Configuration initialization
4436 config
= config
|| {};
4439 this.$floatable
= null;
4440 this.$floatableContainer
= null;
4441 this.$floatableWindow
= null;
4442 this.$floatableClosestScrollable
= null;
4443 this.floatableOutOfView
= false;
4444 this.onFloatableScrollHandler
= this.position
.bind( this );
4445 this.onFloatableWindowResizeHandler
= this.position
.bind( this );
4448 this.setFloatableContainer( config
.$floatableContainer
);
4449 this.setFloatableElement( config
.$floatable
|| this.$element
);
4450 this.setVerticalPosition( config
.verticalPosition
|| 'below' );
4451 this.setHorizontalPosition( config
.horizontalPosition
|| 'start' );
4452 this.hideWhenOutOfView
= config
.hideWhenOutOfView
=== undefined ? true : !!config
.hideWhenOutOfView
;
4458 * Set floatable element.
4460 * If an element is already set, it will be cleaned up before setting up the new element.
4462 * @param {jQuery} $floatable Element to make floatable
4464 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableElement = function ( $floatable
) {
4465 if ( this.$floatable
) {
4466 this.$floatable
.removeClass( 'oo-ui-floatableElement-floatable' );
4467 this.$floatable
.css( { left
: '', top
: '' } );
4470 this.$floatable
= $floatable
.addClass( 'oo-ui-floatableElement-floatable' );
4475 * Set floatable container.
4477 * The element will be positioned relative to the specified container.
4479 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
4481 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableContainer = function ( $floatableContainer
) {
4482 this.$floatableContainer
= $floatableContainer
;
4483 if ( this.$floatable
) {
4489 * Change how the element is positioned vertically.
4491 * @param {string} position 'below', 'above', 'top', 'bottom' or 'center'
4493 OO
.ui
.mixin
.FloatableElement
.prototype.setVerticalPosition = function ( position
) {
4494 if ( [ 'below', 'above', 'top', 'bottom', 'center' ].indexOf( position
) === -1 ) {
4495 throw new Error( 'Invalid value for vertical position: ' + position
);
4497 if ( this.verticalPosition
!== position
) {
4498 this.verticalPosition
= position
;
4499 if ( this.$floatable
) {
4506 * Change how the element is positioned horizontally.
4508 * @param {string} position 'before', 'after', 'start', 'end' or 'center'
4510 OO
.ui
.mixin
.FloatableElement
.prototype.setHorizontalPosition = function ( position
) {
4511 if ( [ 'before', 'after', 'start', 'end', 'center' ].indexOf( position
) === -1 ) {
4512 throw new Error( 'Invalid value for horizontal position: ' + position
);
4514 if ( this.horizontalPosition
!== position
) {
4515 this.horizontalPosition
= position
;
4516 if ( this.$floatable
) {
4523 * Toggle positioning.
4525 * Do not turn positioning on until after the element is attached to the DOM and visible.
4527 * @param {boolean} [positioning] Enable positioning, omit to toggle
4529 * @return {OO.ui.Element} The element, for chaining
4531 OO
.ui
.mixin
.FloatableElement
.prototype.togglePositioning = function ( positioning
) {
4532 var closestScrollableOfContainer
;
4534 if ( !this.$floatable
|| !this.$floatableContainer
) {
4538 positioning
= positioning
=== undefined ? !this.positioning
: !!positioning
;
4540 if ( positioning
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4541 OO
.ui
.warnDeprecation( 'FloatableElement#togglePositioning: Before calling this method, the element must be attached to the DOM.' );
4542 this.warnedUnattached
= true;
4545 if ( this.positioning
!== positioning
) {
4546 this.positioning
= positioning
;
4548 closestScrollableOfContainer
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatableContainer
[ 0 ] );
4549 // If the scrollable is the root, we have to listen to scroll events
4550 // on the window because of browser inconsistencies.
4551 if ( $( closestScrollableOfContainer
).is( 'html, body' ) ) {
4552 closestScrollableOfContainer
= OO
.ui
.Element
.static.getWindow( closestScrollableOfContainer
);
4555 if ( positioning
) {
4556 this.$floatableWindow
= $( this.getElementWindow() );
4557 this.$floatableWindow
.on( 'resize', this.onFloatableWindowResizeHandler
);
4559 this.$floatableClosestScrollable
= $( closestScrollableOfContainer
);
4560 this.$floatableClosestScrollable
.on( 'scroll', this.onFloatableScrollHandler
);
4562 // Initial position after visible
4565 if ( this.$floatableWindow
) {
4566 this.$floatableWindow
.off( 'resize', this.onFloatableWindowResizeHandler
);
4567 this.$floatableWindow
= null;
4570 if ( this.$floatableClosestScrollable
) {
4571 this.$floatableClosestScrollable
.off( 'scroll', this.onFloatableScrollHandler
);
4572 this.$floatableClosestScrollable
= null;
4575 this.$floatable
.css( { left
: '', right
: '', top
: '' } );
4583 * Check whether the bottom edge of the given element is within the viewport of the given container.
4586 * @param {jQuery} $element
4587 * @param {jQuery} $container
4590 OO
.ui
.mixin
.FloatableElement
.prototype.isElementInViewport = function ( $element
, $container
) {
4591 var elemRect
, contRect
, topEdgeInBounds
, bottomEdgeInBounds
, leftEdgeInBounds
, rightEdgeInBounds
,
4592 startEdgeInBounds
, endEdgeInBounds
, viewportSpacing
,
4593 direction
= $element
.css( 'direction' );
4595 elemRect
= $element
[ 0 ].getBoundingClientRect();
4596 if ( $container
[ 0 ] === window
) {
4597 viewportSpacing
= OO
.ui
.getViewportSpacing();
4601 right
: document
.documentElement
.clientWidth
,
4602 bottom
: document
.documentElement
.clientHeight
4604 contRect
.top
+= viewportSpacing
.top
;
4605 contRect
.left
+= viewportSpacing
.left
;
4606 contRect
.right
-= viewportSpacing
.right
;
4607 contRect
.bottom
-= viewportSpacing
.bottom
;
4609 contRect
= $container
[ 0 ].getBoundingClientRect();
4612 topEdgeInBounds
= elemRect
.top
>= contRect
.top
&& elemRect
.top
<= contRect
.bottom
;
4613 bottomEdgeInBounds
= elemRect
.bottom
>= contRect
.top
&& elemRect
.bottom
<= contRect
.bottom
;
4614 leftEdgeInBounds
= elemRect
.left
>= contRect
.left
&& elemRect
.left
<= contRect
.right
;
4615 rightEdgeInBounds
= elemRect
.right
>= contRect
.left
&& elemRect
.right
<= contRect
.right
;
4616 if ( direction
=== 'rtl' ) {
4617 startEdgeInBounds
= rightEdgeInBounds
;
4618 endEdgeInBounds
= leftEdgeInBounds
;
4620 startEdgeInBounds
= leftEdgeInBounds
;
4621 endEdgeInBounds
= rightEdgeInBounds
;
4624 if ( this.verticalPosition
=== 'below' && !bottomEdgeInBounds
) {
4627 if ( this.verticalPosition
=== 'above' && !topEdgeInBounds
) {
4630 if ( this.horizontalPosition
=== 'before' && !startEdgeInBounds
) {
4633 if ( this.horizontalPosition
=== 'after' && !endEdgeInBounds
) {
4637 // The other positioning values are all about being inside the container,
4638 // so in those cases all we care about is that any part of the container is visible.
4639 return elemRect
.top
<= contRect
.bottom
&& elemRect
.bottom
>= contRect
.top
&&
4640 elemRect
.left
<= contRect
.right
&& elemRect
.right
>= contRect
.left
;
4644 * Check if the floatable is hidden to the user because it was offscreen.
4646 * @return {boolean} Floatable is out of view
4648 OO
.ui
.mixin
.FloatableElement
.prototype.isFloatableOutOfView = function () {
4649 return this.floatableOutOfView
;
4653 * Position the floatable below its container.
4655 * This should only be done when both of them are attached to the DOM and visible.
4658 * @return {OO.ui.Element} The element, for chaining
4660 OO
.ui
.mixin
.FloatableElement
.prototype.position = function () {
4661 if ( !this.positioning
) {
4666 // To continue, some things need to be true:
4667 // The element must actually be in the DOM
4668 this.isElementAttached() && (
4669 // The closest scrollable is the current window
4670 this.$floatableClosestScrollable
[ 0 ] === this.getElementWindow() ||
4671 // OR is an element in the element's DOM
4672 $.contains( this.getElementDocument(), this.$floatableClosestScrollable
[ 0 ] )
4675 // Abort early if important parts of the widget are no longer attached to the DOM
4679 this.floatableOutOfView
= this.hideWhenOutOfView
&& !this.isElementInViewport( this.$floatableContainer
, this.$floatableClosestScrollable
);
4680 if ( this.floatableOutOfView
) {
4681 this.$floatable
.addClass( 'oo-ui-element-hidden' );
4684 this.$floatable
.removeClass( 'oo-ui-element-hidden' );
4687 this.$floatable
.css( this.computePosition() );
4689 // We updated the position, so re-evaluate the clipping state.
4690 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
4691 // will not notice the need to update itself.)
4692 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
4693 // it not listen to the right events in the right places?
4702 * Compute how #$floatable should be positioned based on the position of #$floatableContainer
4703 * and the positioning settings. This is a helper for #position that shouldn't be called directly,
4704 * but may be overridden by subclasses if they want to change or add to the positioning logic.
4706 * @return {Object} New position to apply with .css(). Keys are 'top', 'left', 'bottom' and 'right'.
4708 OO
.ui
.mixin
.FloatableElement
.prototype.computePosition = function () {
4709 var isBody
, scrollableX
, scrollableY
, containerPos
,
4710 horizScrollbarHeight
, vertScrollbarWidth
, scrollTop
, scrollLeft
,
4711 newPos
= { top
: '', left
: '', bottom
: '', right
: '' },
4712 direction
= this.$floatableContainer
.css( 'direction' ),
4713 $offsetParent
= this.$floatable
.offsetParent();
4715 if ( $offsetParent
.is( 'html' ) ) {
4716 // The innerHeight/Width and clientHeight/Width calculations don't work well on the
4717 // <html> element, but they do work on the <body>
4718 $offsetParent
= $( $offsetParent
[ 0 ].ownerDocument
.body
);
4720 isBody
= $offsetParent
.is( 'body' );
4721 scrollableX
= $offsetParent
.css( 'overflow-x' ) === 'scroll' || $offsetParent
.css( 'overflow-x' ) === 'auto';
4722 scrollableY
= $offsetParent
.css( 'overflow-y' ) === 'scroll' || $offsetParent
.css( 'overflow-y' ) === 'auto';
4724 vertScrollbarWidth
= $offsetParent
.innerWidth() - $offsetParent
.prop( 'clientWidth' );
4725 horizScrollbarHeight
= $offsetParent
.innerHeight() - $offsetParent
.prop( 'clientHeight' );
4726 // We don't need to compute and add scrollTop and scrollLeft if the scrollable container is the body,
4727 // or if it isn't scrollable
4728 scrollTop
= scrollableY
&& !isBody
? $offsetParent
.scrollTop() : 0;
4729 scrollLeft
= scrollableX
&& !isBody
? OO
.ui
.Element
.static.getScrollLeft( $offsetParent
[ 0 ] ) : 0;
4731 // Avoid passing the <body> to getRelativePosition(), because it won't return what we expect
4732 // if the <body> has a margin
4733 containerPos
= isBody
?
4734 this.$floatableContainer
.offset() :
4735 OO
.ui
.Element
.static.getRelativePosition( this.$floatableContainer
, $offsetParent
);
4736 containerPos
.bottom
= containerPos
.top
+ this.$floatableContainer
.outerHeight();
4737 containerPos
.right
= containerPos
.left
+ this.$floatableContainer
.outerWidth();
4738 containerPos
.start
= direction
=== 'rtl' ? containerPos
.right
: containerPos
.left
;
4739 containerPos
.end
= direction
=== 'rtl' ? containerPos
.left
: containerPos
.right
;
4741 if ( this.verticalPosition
=== 'below' ) {
4742 newPos
.top
= containerPos
.bottom
;
4743 } else if ( this.verticalPosition
=== 'above' ) {
4744 newPos
.bottom
= $offsetParent
.outerHeight() - containerPos
.top
;
4745 } else if ( this.verticalPosition
=== 'top' ) {
4746 newPos
.top
= containerPos
.top
;
4747 } else if ( this.verticalPosition
=== 'bottom' ) {
4748 newPos
.bottom
= $offsetParent
.outerHeight() - containerPos
.bottom
;
4749 } else if ( this.verticalPosition
=== 'center' ) {
4750 newPos
.top
= containerPos
.top
+
4751 ( this.$floatableContainer
.height() - this.$floatable
.height() ) / 2;
4754 if ( this.horizontalPosition
=== 'before' ) {
4755 newPos
.end
= containerPos
.start
;
4756 } else if ( this.horizontalPosition
=== 'after' ) {
4757 newPos
.start
= containerPos
.end
;
4758 } else if ( this.horizontalPosition
=== 'start' ) {
4759 newPos
.start
= containerPos
.start
;
4760 } else if ( this.horizontalPosition
=== 'end' ) {
4761 newPos
.end
= containerPos
.end
;
4762 } else if ( this.horizontalPosition
=== 'center' ) {
4763 newPos
.left
= containerPos
.left
+
4764 ( this.$floatableContainer
.width() - this.$floatable
.width() ) / 2;
4767 if ( newPos
.start
!== undefined ) {
4768 if ( direction
=== 'rtl' ) {
4769 newPos
.right
= ( isBody
? $( $offsetParent
[ 0 ].ownerDocument
.documentElement
) : $offsetParent
).outerWidth() - newPos
.start
;
4771 newPos
.left
= newPos
.start
;
4773 delete newPos
.start
;
4775 if ( newPos
.end
!== undefined ) {
4776 if ( direction
=== 'rtl' ) {
4777 newPos
.left
= newPos
.end
;
4779 newPos
.right
= ( isBody
? $( $offsetParent
[ 0 ].ownerDocument
.documentElement
) : $offsetParent
).outerWidth() - newPos
.end
;
4784 // Account for scroll position
4785 if ( newPos
.top
!== '' ) {
4786 newPos
.top
+= scrollTop
;
4788 if ( newPos
.bottom
!== '' ) {
4789 newPos
.bottom
-= scrollTop
;
4791 if ( newPos
.left
!== '' ) {
4792 newPos
.left
+= scrollLeft
;
4794 if ( newPos
.right
!== '' ) {
4795 newPos
.right
-= scrollLeft
;
4798 // Account for scrollbar gutter
4799 if ( newPos
.bottom
!== '' ) {
4800 newPos
.bottom
-= horizScrollbarHeight
;
4802 if ( direction
=== 'rtl' ) {
4803 if ( newPos
.left
!== '' ) {
4804 newPos
.left
-= vertScrollbarWidth
;
4807 if ( newPos
.right
!== '' ) {
4808 newPos
.right
-= vertScrollbarWidth
;
4816 * Element that can be automatically clipped to visible boundaries.
4818 * Whenever the element's natural height changes, you have to call
4819 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
4820 * clipping correctly.
4822 * The dimensions of #$clippableContainer will be compared to the boundaries of the
4823 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
4824 * then #$clippable will be given a fixed reduced height and/or width and will be made
4825 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
4826 * but you can build a static footer by setting #$clippableContainer to an element that contains
4827 * #$clippable and the footer.
4833 * @param {Object} [config] Configuration options
4834 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
4835 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
4836 * omit to use #$clippable
4838 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
4839 // Configuration initialization
4840 config
= config
|| {};
4843 this.$clippable
= null;
4844 this.$clippableContainer
= null;
4845 this.clipping
= false;
4846 this.clippedHorizontally
= false;
4847 this.clippedVertically
= false;
4848 this.$clippableScrollableContainer
= null;
4849 this.$clippableScroller
= null;
4850 this.$clippableWindow
= null;
4851 this.idealWidth
= null;
4852 this.idealHeight
= null;
4853 this.onClippableScrollHandler
= this.clip
.bind( this );
4854 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
4857 if ( config
.$clippableContainer
) {
4858 this.setClippableContainer( config
.$clippableContainer
);
4860 this.setClippableElement( config
.$clippable
|| this.$element
);
4866 * Set clippable element.
4868 * If an element is already set, it will be cleaned up before setting up the new element.
4870 * @param {jQuery} $clippable Element to make clippable
4872 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
4873 if ( this.$clippable
) {
4874 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
4875 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
4876 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4879 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
4884 * Set clippable container.
4886 * This is the container that will be measured when deciding whether to clip. When clipping,
4887 * #$clippable will be resized in order to keep the clippable container fully visible.
4889 * If the clippable container is unset, #$clippable will be used.
4891 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
4893 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableContainer = function ( $clippableContainer
) {
4894 this.$clippableContainer
= $clippableContainer
;
4895 if ( this.$clippable
) {
4903 * Do not turn clipping on until after the element is attached to the DOM and visible.
4905 * @param {boolean} [clipping] Enable clipping, omit to toggle
4907 * @return {OO.ui.Element} The element, for chaining
4909 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
4910 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
4912 if ( clipping
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4913 OO
.ui
.warnDeprecation( 'ClippableElement#toggleClipping: Before calling this method, the element must be attached to the DOM.' );
4914 this.warnedUnattached
= true;
4917 if ( this.clipping
!== clipping
) {
4918 this.clipping
= clipping
;
4920 this.$clippableScrollableContainer
= $( this.getClosestScrollableElementContainer() );
4921 // If the clippable container is the root, we have to listen to scroll events and check
4922 // jQuery.scrollTop on the window because of browser inconsistencies
4923 this.$clippableScroller
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
4924 $( OO
.ui
.Element
.static.getWindow( this.$clippableScrollableContainer
) ) :
4925 this.$clippableScrollableContainer
;
4926 this.$clippableScroller
.on( 'scroll', this.onClippableScrollHandler
);
4927 this.$clippableWindow
= $( this.getElementWindow() )
4928 .on( 'resize', this.onClippableWindowResizeHandler
);
4929 // Initial clip after visible
4932 this.$clippable
.css( {
4940 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4942 this.$clippableScrollableContainer
= null;
4943 this.$clippableScroller
.off( 'scroll', this.onClippableScrollHandler
);
4944 this.$clippableScroller
= null;
4945 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
4946 this.$clippableWindow
= null;
4954 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4956 * @return {boolean} Element will be clipped to the visible area
4958 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
4959 return this.clipping
;
4963 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
4965 * @return {boolean} Part of the element is being clipped
4967 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
4968 return this.clippedHorizontally
|| this.clippedVertically
;
4972 * Check if the right of the element is being clipped by the nearest scrollable container.
4974 * @return {boolean} Part of the element is being clipped
4976 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
4977 return this.clippedHorizontally
;
4981 * Check if the bottom of the element is being clipped by the nearest scrollable container.
4983 * @return {boolean} Part of the element is being clipped
4985 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
4986 return this.clippedVertically
;
4990 * Set the ideal size. These are the dimensions #$clippable will have when it's not being clipped.
4992 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
4993 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
4995 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
4996 this.idealWidth
= width
;
4997 this.idealHeight
= height
;
4999 if ( !this.clipping
) {
5000 // Update dimensions
5001 this.$clippable
.css( { width
: width
, height
: height
} );
5003 // While clipping, idealWidth and idealHeight are not considered
5007 * Return the side of the clippable on which it is "anchored" (aligned to something else).
5008 * ClippableElement will clip the opposite side when reducing element's width.
5010 * Classes that mix in ClippableElement should override this to return 'right' if their
5011 * clippable is absolutely positioned and using 'right: Npx' (and not using 'left').
5012 * If your class also mixes in FloatableElement, this is handled automatically.
5014 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
5015 * always in pixels, even if they were unset or set to 'auto'.)
5017 * When in doubt, 'left' (or 'right' in RTL) is a sane fallback.
5019 * @return {string} 'left' or 'right'
5021 OO
.ui
.mixin
.ClippableElement
.prototype.getHorizontalAnchorEdge = function () {
5022 if ( this.computePosition
&& this.positioning
&& this.computePosition().right
!== '' ) {
5029 * Return the side of the clippable on which it is "anchored" (aligned to something else).
5030 * ClippableElement will clip the opposite side when reducing element's width.
5032 * Classes that mix in ClippableElement should override this to return 'bottom' if their
5033 * clippable is absolutely positioned and using 'bottom: Npx' (and not using 'top').
5034 * If your class also mixes in FloatableElement, this is handled automatically.
5036 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
5037 * always in pixels, even if they were unset or set to 'auto'.)
5039 * When in doubt, 'top' is a sane fallback.
5041 * @return {string} 'top' or 'bottom'
5043 OO
.ui
.mixin
.ClippableElement
.prototype.getVerticalAnchorEdge = function () {
5044 if ( this.computePosition
&& this.positioning
&& this.computePosition().bottom
!== '' ) {
5051 * Clip element to visible boundaries and allow scrolling when needed. You should call this method
5052 * when the element's natural height changes.
5054 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
5055 * overlapped by, the visible area of the nearest scrollable container.
5057 * Because calling clip() when the natural height changes isn't always possible, we also set
5058 * max-height when the element isn't being clipped. This means that if the element tries to grow
5059 * beyond the edge, something reasonable will happen before clip() is called.
5062 * @return {OO.ui.Element} The element, for chaining
5064 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
5065 var extraHeight
, extraWidth
, viewportSpacing
,
5066 desiredWidth
, desiredHeight
, allotedWidth
, allotedHeight
,
5067 naturalWidth
, naturalHeight
, clipWidth
, clipHeight
,
5068 $item
, itemRect
, $viewport
, viewportRect
, availableRect
,
5069 direction
, vertScrollbarWidth
, horizScrollbarHeight
,
5070 // Extra tolerance so that the sloppy code below doesn't result in results that are off
5071 // by one or two pixels. (And also so that we have space to display drop shadows.)
5072 // Chosen by fair dice roll.
5075 if ( !this.clipping
) {
5076 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
5080 function rectIntersection( a
, b
) {
5082 out
.top
= Math
.max( a
.top
, b
.top
);
5083 out
.left
= Math
.max( a
.left
, b
.left
);
5084 out
.bottom
= Math
.min( a
.bottom
, b
.bottom
);
5085 out
.right
= Math
.min( a
.right
, b
.right
);
5089 viewportSpacing
= OO
.ui
.getViewportSpacing();
5091 if ( this.$clippableScrollableContainer
.is( 'html, body' ) ) {
5092 $viewport
= $( this.$clippableScrollableContainer
[ 0 ].ownerDocument
.body
);
5093 // Dimensions of the browser window, rather than the element!
5097 right
: document
.documentElement
.clientWidth
,
5098 bottom
: document
.documentElement
.clientHeight
5100 viewportRect
.top
+= viewportSpacing
.top
;
5101 viewportRect
.left
+= viewportSpacing
.left
;
5102 viewportRect
.right
-= viewportSpacing
.right
;
5103 viewportRect
.bottom
-= viewportSpacing
.bottom
;
5105 $viewport
= this.$clippableScrollableContainer
;
5106 viewportRect
= $viewport
[ 0 ].getBoundingClientRect();
5107 // Convert into a plain object
5108 viewportRect
= $.extend( {}, viewportRect
);
5111 // Account for scrollbar gutter
5112 direction
= $viewport
.css( 'direction' );
5113 vertScrollbarWidth
= $viewport
.innerWidth() - $viewport
.prop( 'clientWidth' );
5114 horizScrollbarHeight
= $viewport
.innerHeight() - $viewport
.prop( 'clientHeight' );
5115 viewportRect
.bottom
-= horizScrollbarHeight
;
5116 if ( direction
=== 'rtl' ) {
5117 viewportRect
.left
+= vertScrollbarWidth
;
5119 viewportRect
.right
-= vertScrollbarWidth
;
5122 // Add arbitrary tolerance
5123 viewportRect
.top
+= buffer
;
5124 viewportRect
.left
+= buffer
;
5125 viewportRect
.right
-= buffer
;
5126 viewportRect
.bottom
-= buffer
;
5128 $item
= this.$clippableContainer
|| this.$clippable
;
5130 extraHeight
= $item
.outerHeight() - this.$clippable
.outerHeight();
5131 extraWidth
= $item
.outerWidth() - this.$clippable
.outerWidth();
5133 itemRect
= $item
[ 0 ].getBoundingClientRect();
5134 // Convert into a plain object
5135 itemRect
= $.extend( {}, itemRect
);
5137 // Item might already be clipped, so we can't just use its dimensions (in case we might need to
5138 // make it larger than before). Extend the rectangle to the maximum size we are allowed to take.
5139 if ( this.getHorizontalAnchorEdge() === 'right' ) {
5140 itemRect
.left
= viewportRect
.left
;
5142 itemRect
.right
= viewportRect
.right
;
5144 if ( this.getVerticalAnchorEdge() === 'bottom' ) {
5145 itemRect
.top
= viewportRect
.top
;
5147 itemRect
.bottom
= viewportRect
.bottom
;
5150 availableRect
= rectIntersection( viewportRect
, itemRect
);
5152 desiredWidth
= Math
.max( 0, availableRect
.right
- availableRect
.left
);
5153 desiredHeight
= Math
.max( 0, availableRect
.bottom
- availableRect
.top
);
5154 // It should never be desirable to exceed the dimensions of the browser viewport... right?
5155 desiredWidth
= Math
.min( desiredWidth
,
5156 document
.documentElement
.clientWidth
- viewportSpacing
.left
- viewportSpacing
.right
);
5157 desiredHeight
= Math
.min( desiredHeight
,
5158 document
.documentElement
.clientHeight
- viewportSpacing
.top
- viewportSpacing
.right
);
5159 allotedWidth
= Math
.ceil( desiredWidth
- extraWidth
);
5160 allotedHeight
= Math
.ceil( desiredHeight
- extraHeight
);
5161 naturalWidth
= this.$clippable
.prop( 'scrollWidth' );
5162 naturalHeight
= this.$clippable
.prop( 'scrollHeight' );
5163 clipWidth
= allotedWidth
< naturalWidth
;
5164 clipHeight
= allotedHeight
< naturalHeight
;
5167 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. See T157672.
5168 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
5169 this.$clippable
.css( 'overflowX', 'scroll' );
5170 // eslint-disable-next-line no-void
5171 void this.$clippable
[ 0 ].offsetHeight
; // Force reflow
5172 this.$clippable
.css( {
5173 width
: Math
.max( 0, allotedWidth
),
5177 this.$clippable
.css( {
5179 width
: this.idealWidth
|| '',
5180 maxWidth
: Math
.max( 0, allotedWidth
)
5184 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. See T157672.
5185 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
5186 this.$clippable
.css( 'overflowY', 'scroll' );
5187 // eslint-disable-next-line no-void
5188 void this.$clippable
[ 0 ].offsetHeight
; // Force reflow
5189 this.$clippable
.css( {
5190 height
: Math
.max( 0, allotedHeight
),
5194 this.$clippable
.css( {
5196 height
: this.idealHeight
|| '',
5197 maxHeight
: Math
.max( 0, allotedHeight
)
5201 // If we stopped clipping in at least one of the dimensions
5202 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
5203 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
5206 this.clippedHorizontally
= clipWidth
;
5207 this.clippedVertically
= clipHeight
;
5213 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
5214 * By default, each popup has an anchor that points toward its origin.
5215 * Please see the [OOUI documentation on MediaWiki.org] [1] for more information and examples.
5217 * Unlike most widgets, PopupWidget is initially hidden and must be shown by calling #toggle.
5221 * var popup = new OO.ui.PopupWidget( {
5222 * $content: $( '<p>Hi there!</p>' ),
5227 * $( document.body ).append( popup.$element );
5228 * // To display the popup, toggle the visibility to 'true'.
5229 * popup.toggle( true );
5231 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups
5234 * @extends OO.ui.Widget
5235 * @mixins OO.ui.mixin.LabelElement
5236 * @mixins OO.ui.mixin.ClippableElement
5237 * @mixins OO.ui.mixin.FloatableElement
5240 * @param {Object} [config] Configuration options
5241 * @cfg {number|null} [width=320] Width of popup in pixels. Pass `null` to use automatic width.
5242 * @cfg {number|null} [height=null] Height of popup in pixels. Pass `null` to use automatic height.
5243 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
5244 * @cfg {string} [position='below'] Where to position the popup relative to $floatableContainer
5245 * 'above': Put popup above $floatableContainer; anchor points down to the horizontal center
5246 * of $floatableContainer
5247 * 'below': Put popup below $floatableContainer; anchor points up to the horizontal center
5248 * of $floatableContainer
5249 * 'before': Put popup to the left (LTR) / right (RTL) of $floatableContainer; anchor points
5250 * endwards (right/left) to the vertical center of $floatableContainer
5251 * 'after': Put popup to the right (LTR) / left (RTL) of $floatableContainer; anchor points
5252 * startwards (left/right) to the vertical center of $floatableContainer
5253 * @cfg {string} [align='center'] How to align the popup to $floatableContainer
5254 * 'forwards': If position is above/below, move the popup as far endwards (right in LTR, left in RTL)
5255 * as possible while still keeping the anchor within the popup;
5256 * if position is before/after, move the popup as far downwards as possible.
5257 * 'backwards': If position is above/below, move the popup as far startwards (left in LTR, right in RTL)
5258 * as possible while still keeping the anchor within the popup;
5259 * if position in before/after, move the popup as far upwards as possible.
5260 * 'center': Horizontally (if position is above/below) or vertically (before/after) align the center
5261 * of the popup with the center of $floatableContainer.
5262 * 'force-left': Alias for 'forwards' in LTR and 'backwards' in RTL
5263 * 'force-right': Alias for 'backwards' in RTL and 'forwards' in LTR
5264 * @cfg {boolean} [autoFlip=true] Whether to automatically switch the popup's position between
5265 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5266 * desired direction to display the popup without clipping
5267 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
5268 * See the [OOUI docs on MediaWiki][3] for an example.
5269 * [3]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#containerExample
5270 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
5271 * @cfg {jQuery} [$content] Content to append to the popup's body
5272 * @cfg {jQuery} [$footer] Content to append to the popup's footer
5273 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
5274 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
5275 * This config option is only relevant if #autoClose is set to `true`. See the [OOUI documentation on MediaWiki][2]
5277 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#autocloseExample
5278 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
5280 * @cfg {boolean} [padded=false] Add padding to the popup's body
5282 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
5283 // Configuration initialization
5284 config
= config
|| {};
5286 // Parent constructor
5287 OO
.ui
.PopupWidget
.parent
.call( this, config
);
5289 // Properties (must be set before ClippableElement constructor call)
5290 this.$body
= $( '<div>' );
5291 this.$popup
= $( '<div>' );
5293 // Mixin constructors
5294 OO
.ui
.mixin
.LabelElement
.call( this, config
);
5295 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, {
5296 $clippable
: this.$body
,
5297 $clippableContainer
: this.$popup
5299 OO
.ui
.mixin
.FloatableElement
.call( this, config
);
5302 this.$anchor
= $( '<div>' );
5303 // If undefined, will be computed lazily in computePosition()
5304 this.$container
= config
.$container
;
5305 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
5306 this.autoClose
= !!config
.autoClose
;
5307 this.transitionTimeout
= null;
5308 this.anchored
= false;
5309 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
5310 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
5313 this.setSize( config
.width
, config
.height
);
5314 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
5315 this.setAlignment( config
.align
|| 'center' );
5316 this.setPosition( config
.position
|| 'below' );
5317 this.setAutoFlip( config
.autoFlip
=== undefined || config
.autoFlip
);
5318 this.setAutoCloseIgnore( config
.$autoCloseIgnore
);
5319 this.$body
.addClass( 'oo-ui-popupWidget-body' );
5320 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
5322 .addClass( 'oo-ui-popupWidget-popup' )
5323 .append( this.$body
);
5325 .addClass( 'oo-ui-popupWidget' )
5326 .append( this.$popup
, this.$anchor
);
5327 // Move content, which was added to #$element by OO.ui.Widget, to the body
5328 // FIXME This is gross, we should use '$body' or something for the config
5329 if ( config
.$content
instanceof $ ) {
5330 this.$body
.append( config
.$content
);
5333 if ( config
.padded
) {
5334 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
5337 if ( config
.head
) {
5338 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
5339 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
5340 this.$head
= $( '<div>' )
5341 .addClass( 'oo-ui-popupWidget-head' )
5342 .append( this.$label
, this.closeButton
.$element
);
5343 this.$popup
.prepend( this.$head
);
5346 if ( config
.$footer
) {
5347 this.$footer
= $( '<div>' )
5348 .addClass( 'oo-ui-popupWidget-footer' )
5349 .append( config
.$footer
);
5350 this.$popup
.append( this.$footer
);
5353 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
5354 // that reference properties not initialized at that time of parent class construction
5355 // TODO: Find a better way to handle post-constructor setup
5356 this.visible
= false;
5357 this.$element
.addClass( 'oo-ui-element-hidden' );
5362 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
5363 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
5364 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
5365 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.FloatableElement
);
5372 * The popup is ready: it is visible and has been positioned and clipped.
5378 * Handles document mouse down events.
5381 * @param {MouseEvent} e Mouse down event
5383 OO
.ui
.PopupWidget
.prototype.onDocumentMouseDown = function ( e
) {
5386 !OO
.ui
.contains( this.$element
.add( this.$autoCloseIgnore
).get(), e
.target
, true )
5388 this.toggle( false );
5392 // Deprecated alias since 0.28.3
5393 OO
.ui
.PopupWidget
.prototype.onMouseDown = function () {
5394 OO
.ui
.warnDeprecation( 'onMouseDown is deprecated, use onDocumentMouseDown instead' );
5395 this.onDocumentMouseDown
.apply( this, arguments
);
5399 * Bind document mouse down listener.
5403 OO
.ui
.PopupWidget
.prototype.bindDocumentMouseDownListener = function () {
5404 // Capture clicks outside popup
5405 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
5406 // We add 'click' event because iOS safari needs to respond to this event.
5407 // We can't use 'touchstart' (as is usually the equivalent to 'mousedown') because
5408 // then it will trigger when scrolling. While iOS Safari has some reported behavior
5409 // of occasionally not emitting 'click' properly, that event seems to be the standard
5410 // that it should be emitting, so we add it to this and will operate the event handler
5411 // on whichever of these events was triggered first
5412 this.getElementDocument().addEventListener( 'click', this.onDocumentMouseDownHandler
, true );
5415 // Deprecated alias since 0.28.3
5416 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
5417 OO
.ui
.warnDeprecation( 'bindMouseDownListener is deprecated, use bindDocumentMouseDownListener instead' );
5418 this.bindDocumentMouseDownListener
.apply( this, arguments
);
5422 * Handles close button click events.
5426 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
5427 if ( this.isVisible() ) {
5428 this.toggle( false );
5433 * Unbind document mouse down listener.
5437 OO
.ui
.PopupWidget
.prototype.unbindDocumentMouseDownListener = function () {
5438 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
5439 this.getElementDocument().removeEventListener( 'click', this.onDocumentMouseDownHandler
, true );
5442 // Deprecated alias since 0.28.3
5443 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
5444 OO
.ui
.warnDeprecation( 'unbindMouseDownListener is deprecated, use unbindDocumentMouseDownListener instead' );
5445 this.unbindDocumentMouseDownListener
.apply( this, arguments
);
5449 * Handles document key down events.
5452 * @param {KeyboardEvent} e Key down event
5454 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
5456 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
5459 this.toggle( false );
5461 e
.stopPropagation();
5466 * Bind document key down listener.
5470 OO
.ui
.PopupWidget
.prototype.bindDocumentKeyDownListener = function () {
5471 this.getElementDocument().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
5474 // Deprecated alias since 0.28.3
5475 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
5476 OO
.ui
.warnDeprecation( 'bindKeyDownListener is deprecated, use bindDocumentKeyDownListener instead' );
5477 this.bindDocumentKeyDownListener
.apply( this, arguments
);
5481 * Unbind document key down listener.
5485 OO
.ui
.PopupWidget
.prototype.unbindDocumentKeyDownListener = function () {
5486 this.getElementDocument().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
5489 // Deprecated alias since 0.28.3
5490 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
5491 OO
.ui
.warnDeprecation( 'unbindKeyDownListener is deprecated, use unbindDocumentKeyDownListener instead' );
5492 this.unbindDocumentKeyDownListener
.apply( this, arguments
);
5496 * Show, hide, or toggle the visibility of the anchor.
5498 * @param {boolean} [show] Show anchor, omit to toggle
5500 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
5501 show
= show
=== undefined ? !this.anchored
: !!show
;
5503 if ( this.anchored
!== show
) {
5505 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
5506 this.$element
.addClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5508 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
5509 this.$element
.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5511 this.anchored
= show
;
5516 * Change which edge the anchor appears on.
5518 * @param {string} edge 'top', 'bottom', 'start' or 'end'
5520 OO
.ui
.PopupWidget
.prototype.setAnchorEdge = function ( edge
) {
5521 if ( [ 'top', 'bottom', 'start', 'end' ].indexOf( edge
) === -1 ) {
5522 throw new Error( 'Invalid value for edge: ' + edge
);
5524 if ( this.anchorEdge
!== null ) {
5525 this.$element
.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5527 this.anchorEdge
= edge
;
5528 if ( this.anchored
) {
5529 this.$element
.addClass( 'oo-ui-popupWidget-anchored-' + edge
);
5534 * Check if the anchor is visible.
5536 * @return {boolean} Anchor is visible
5538 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
5539 return this.anchored
;
5543 * Toggle visibility of the popup. The popup is initially hidden and must be shown by calling
5544 * `.toggle( true )` after its #$element is attached to the DOM.
5546 * Do not show the popup while it is not attached to the DOM. The calculations required to display
5547 * it in the right place and with the right dimensions only work correctly while it is attached.
5548 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
5549 * strictly enforced, so currently it only generates a warning in the browser console.
5554 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
5555 var change
, normalHeight
, oppositeHeight
, normalWidth
, oppositeWidth
;
5556 show
= show
=== undefined ? !this.isVisible() : !!show
;
5558 change
= show
!== this.isVisible();
5560 if ( show
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
5561 OO
.ui
.warnDeprecation( 'PopupWidget#toggle: Before calling this method, the popup must be attached to the DOM.' );
5562 this.warnedUnattached
= true;
5564 if ( show
&& !this.$floatableContainer
&& this.isElementAttached() ) {
5565 // Fall back to the parent node if the floatableContainer is not set
5566 this.setFloatableContainer( this.$element
.parent() );
5569 if ( change
&& show
&& this.autoFlip
) {
5570 // Reset auto-flipping before showing the popup again. It's possible we no longer need to flip
5571 // (e.g. if the user scrolled).
5572 this.isAutoFlipped
= false;
5576 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
5579 this.togglePositioning( show
&& !!this.$floatableContainer
);
5582 if ( this.autoClose
) {
5583 this.bindDocumentMouseDownListener();
5584 this.bindDocumentKeyDownListener();
5586 this.updateDimensions();
5587 this.toggleClipping( true );
5589 if ( this.autoFlip
) {
5590 if ( this.popupPosition
=== 'above' || this.popupPosition
=== 'below' ) {
5591 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5592 // If opening the popup in the normal direction causes it to be clipped, open
5593 // in the opposite one instead
5594 normalHeight
= this.$element
.height();
5595 this.isAutoFlipped
= !this.isAutoFlipped
;
5597 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5598 // If that also causes it to be clipped, open in whichever direction
5599 // we have more space
5600 oppositeHeight
= this.$element
.height();
5601 if ( oppositeHeight
< normalHeight
) {
5602 this.isAutoFlipped
= !this.isAutoFlipped
;
5608 if ( this.popupPosition
=== 'before' || this.popupPosition
=== 'after' ) {
5609 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5610 // If opening the popup in the normal direction causes it to be clipped, open
5611 // in the opposite one instead
5612 normalWidth
= this.$element
.width();
5613 this.isAutoFlipped
= !this.isAutoFlipped
;
5614 // Due to T180173 horizontally clipped PopupWidgets have messed up dimensions,
5615 // which causes positioning to be off. Toggle clipping back and fort to work around.
5616 this.toggleClipping( false );
5618 this.toggleClipping( true );
5619 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5620 // If that also causes it to be clipped, open in whichever direction
5621 // we have more space
5622 oppositeWidth
= this.$element
.width();
5623 if ( oppositeWidth
< normalWidth
) {
5624 this.isAutoFlipped
= !this.isAutoFlipped
;
5625 // Due to T180173 horizontally clipped PopupWidgets have messed up dimensions,
5626 // which causes positioning to be off. Toggle clipping back and fort to work around.
5627 this.toggleClipping( false );
5629 this.toggleClipping( true );
5636 this.emit( 'ready' );
5638 this.toggleClipping( false );
5639 if ( this.autoClose
) {
5640 this.unbindDocumentMouseDownListener();
5641 this.unbindDocumentKeyDownListener();
5650 * Set the size of the popup.
5652 * Changing the size may also change the popup's position depending on the alignment.
5654 * @param {number|null} [width=320] Width in pixels. Pass `null` to use automatic width.
5655 * @param {number|null} [height=null] Height in pixels. Pass `null` to use automatic height.
5656 * @param {boolean} [transition=false] Use a smooth transition
5659 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
5660 this.width
= width
!== undefined ? width
: 320;
5661 this.height
= height
!== undefined ? height
: null;
5662 if ( this.isVisible() ) {
5663 this.updateDimensions( transition
);
5668 * Update the size and position.
5670 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
5671 * be called automatically.
5673 * @param {boolean} [transition=false] Use a smooth transition
5676 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
5679 // Prevent transition from being interrupted
5680 clearTimeout( this.transitionTimeout
);
5682 // Enable transition
5683 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
5689 // Prevent transitioning after transition is complete
5690 this.transitionTimeout
= setTimeout( function () {
5691 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
5694 // Prevent transitioning immediately
5695 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
5702 OO
.ui
.PopupWidget
.prototype.computePosition = function () {
5703 var direction
, align
, vertical
, start
, end
, near
, far
, sizeProp
, popupSize
, anchorSize
, anchorPos
,
5704 anchorOffset
, anchorMargin
, parentPosition
, positionProp
, positionAdjustment
, floatablePos
,
5705 offsetParentPos
, containerPos
, popupPosition
, viewportSpacing
,
5707 anchorCss
= { left
: '', right
: '', top
: '', bottom
: '' },
5708 popupPositionOppositeMap
= {
5716 'force-left': 'backwards',
5717 'force-right': 'forwards'
5720 'force-left': 'forwards',
5721 'force-right': 'backwards'
5733 backwards
: this.anchored
? 'before' : 'end'
5741 if ( !this.$container
) {
5742 // Lazy-initialize $container if not specified in constructor
5743 this.$container
= $( this.getClosestScrollableElementContainer() );
5745 direction
= this.$container
.css( 'direction' );
5747 // Set height and width before we do anything else, since it might cause our measurements
5748 // to change (e.g. due to scrollbars appearing or disappearing), and it also affects centering
5750 width
: this.width
!== null ? this.width
: 'auto',
5751 height
: this.height
!== null ? this.height
: 'auto'
5754 align
= alignMap
[ direction
][ this.align
] || this.align
;
5755 popupPosition
= this.popupPosition
;
5756 if ( this.isAutoFlipped
) {
5757 popupPosition
= popupPositionOppositeMap
[ popupPosition
];
5760 // If the popup is positioned before or after, then the anchor positioning is vertical, otherwise horizontal
5761 vertical
= popupPosition
=== 'before' || popupPosition
=== 'after';
5762 start
= vertical
? 'top' : ( direction
=== 'rtl' ? 'right' : 'left' );
5763 end
= vertical
? 'bottom' : ( direction
=== 'rtl' ? 'left' : 'right' );
5764 near
= vertical
? 'top' : 'left';
5765 far
= vertical
? 'bottom' : 'right';
5766 sizeProp
= vertical
? 'Height' : 'Width';
5767 popupSize
= vertical
? ( this.height
|| this.$popup
.height() ) : ( this.width
|| this.$popup
.width() );
5769 this.setAnchorEdge( anchorEdgeMap
[ popupPosition
] );
5770 this.horizontalPosition
= vertical
? popupPosition
: hPosMap
[ align
];
5771 this.verticalPosition
= vertical
? vPosMap
[ align
] : popupPosition
;
5774 parentPosition
= OO
.ui
.mixin
.FloatableElement
.prototype.computePosition
.call( this );
5775 // Find out which property FloatableElement used for positioning, and adjust that value
5776 positionProp
= vertical
?
5777 ( parentPosition
.top
!== '' ? 'top' : 'bottom' ) :
5778 ( parentPosition
.left
!== '' ? 'left' : 'right' );
5780 // Figure out where the near and far edges of the popup and $floatableContainer are
5781 floatablePos
= this.$floatableContainer
.offset();
5782 floatablePos
[ far
] = floatablePos
[ near
] + this.$floatableContainer
[ 'outer' + sizeProp
]();
5783 // Measure where the offsetParent is and compute our position based on that and parentPosition
5784 offsetParentPos
= this.$element
.offsetParent()[ 0 ] === document
.documentElement
?
5785 { top
: 0, left
: 0 } :
5786 this.$element
.offsetParent().offset();
5788 if ( positionProp
=== near
) {
5789 popupPos
[ near
] = offsetParentPos
[ near
] + parentPosition
[ near
];
5790 popupPos
[ far
] = popupPos
[ near
] + popupSize
;
5792 popupPos
[ far
] = offsetParentPos
[ near
] +
5793 this.$element
.offsetParent()[ 'inner' + sizeProp
]() - parentPosition
[ far
];
5794 popupPos
[ near
] = popupPos
[ far
] - popupSize
;
5797 if ( this.anchored
) {
5798 // Position the anchor (which is positioned relative to the popup) to point to $floatableContainer
5799 anchorPos
= ( floatablePos
[ start
] + floatablePos
[ end
] ) / 2;
5800 anchorOffset
= ( start
=== far
? -1 : 1 ) * ( anchorPos
- popupPos
[ start
] );
5802 // If the anchor is less than 2*anchorSize from either edge, move the popup to make more space
5803 // this.$anchor.width()/height() returns 0 because of the CSS trickery we use, so use scrollWidth/Height
5804 anchorSize
= this.$anchor
[ 0 ][ 'scroll' + sizeProp
];
5805 anchorMargin
= parseFloat( this.$anchor
.css( 'margin-' + start
) );
5806 if ( anchorOffset
+ anchorMargin
< 2 * anchorSize
) {
5807 // Not enough space for the anchor on the start side; pull the popup startwards
5808 positionAdjustment
= ( positionProp
=== start
? -1 : 1 ) *
5809 ( 2 * anchorSize
- ( anchorOffset
+ anchorMargin
) );
5810 } else if ( anchorOffset
+ anchorMargin
> popupSize
- 2 * anchorSize
) {
5811 // Not enough space for the anchor on the end side; pull the popup endwards
5812 positionAdjustment
= ( positionProp
=== end
? -1 : 1 ) *
5813 ( anchorOffset
+ anchorMargin
- ( popupSize
- 2 * anchorSize
) );
5815 positionAdjustment
= 0;
5818 positionAdjustment
= 0;
5821 // Check if the popup will go beyond the edge of this.$container
5822 containerPos
= this.$container
[ 0 ] === document
.documentElement
?
5823 { top
: 0, left
: 0 } :
5824 this.$container
.offset();
5825 containerPos
[ far
] = containerPos
[ near
] + this.$container
[ 'inner' + sizeProp
]();
5826 if ( this.$container
[ 0 ] === document
.documentElement
) {
5827 viewportSpacing
= OO
.ui
.getViewportSpacing();
5828 containerPos
[ near
] += viewportSpacing
[ near
];
5829 containerPos
[ far
] -= viewportSpacing
[ far
];
5831 // Take into account how much the popup will move because of the adjustments we're going to make
5832 popupPos
[ near
] += ( positionProp
=== near
? 1 : -1 ) * positionAdjustment
;
5833 popupPos
[ far
] += ( positionProp
=== near
? 1 : -1 ) * positionAdjustment
;
5834 if ( containerPos
[ near
] + this.containerPadding
> popupPos
[ near
] ) {
5835 // Popup goes beyond the near (left/top) edge, move it to the right/bottom
5836 positionAdjustment
+= ( positionProp
=== near
? 1 : -1 ) *
5837 ( containerPos
[ near
] + this.containerPadding
- popupPos
[ near
] );
5838 } else if ( containerPos
[ far
] - this.containerPadding
< popupPos
[ far
] ) {
5839 // Popup goes beyond the far (right/bottom) edge, move it to the left/top
5840 positionAdjustment
+= ( positionProp
=== far
? 1 : -1 ) *
5841 ( popupPos
[ far
] - ( containerPos
[ far
] - this.containerPadding
) );
5844 if ( this.anchored
) {
5845 // Adjust anchorOffset for positionAdjustment
5846 anchorOffset
+= ( positionProp
=== start
? -1 : 1 ) * positionAdjustment
;
5848 // Position the anchor
5849 anchorCss
[ start
] = anchorOffset
;
5850 this.$anchor
.css( anchorCss
);
5853 // Move the popup if needed
5854 parentPosition
[ positionProp
] += positionAdjustment
;
5856 return parentPosition
;
5860 * Set popup alignment
5862 * @param {string} [align=center] Alignment of the popup, `center`, `force-left`, `force-right`,
5863 * `backwards` or `forwards`.
5865 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
5866 // Validate alignment
5867 if ( [ 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
5870 this.align
= 'center';
5876 * Get popup alignment
5878 * @return {string} Alignment of the popup, `center`, `force-left`, `force-right`,
5879 * `backwards` or `forwards`.
5881 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
5886 * Change the positioning of the popup.
5888 * @param {string} position 'above', 'below', 'before' or 'after'
5890 OO
.ui
.PopupWidget
.prototype.setPosition = function ( position
) {
5891 if ( [ 'above', 'below', 'before', 'after' ].indexOf( position
) === -1 ) {
5894 this.popupPosition
= position
;
5899 * Get popup positioning.
5901 * @return {string} 'above', 'below', 'before' or 'after'
5903 OO
.ui
.PopupWidget
.prototype.getPosition = function () {
5904 return this.popupPosition
;
5908 * Set popup auto-flipping.
5910 * @param {boolean} autoFlip Whether to automatically switch the popup's position between
5911 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5912 * desired direction to display the popup without clipping
5914 OO
.ui
.PopupWidget
.prototype.setAutoFlip = function ( autoFlip
) {
5915 autoFlip
= !!autoFlip
;
5917 if ( this.autoFlip
!== autoFlip
) {
5918 this.autoFlip
= autoFlip
;
5923 * Set which elements will not close the popup when clicked.
5925 * For auto-closing popups, clicks on these elements will not cause the popup to auto-close.
5927 * @param {jQuery} $autoCloseIgnore Elements to ignore for auto-closing
5929 OO
.ui
.PopupWidget
.prototype.setAutoCloseIgnore = function ( $autoCloseIgnore
) {
5930 this.$autoCloseIgnore
= $autoCloseIgnore
;
5934 * Get an ID of the body element, this can be used as the
5935 * `aria-describedby` attribute for an input field.
5937 * @return {string} The ID of the body element
5939 OO
.ui
.PopupWidget
.prototype.getBodyId = function () {
5940 var id
= this.$body
.attr( 'id' );
5941 if ( id
=== undefined ) {
5942 id
= OO
.ui
.generateElementId();
5943 this.$body
.attr( 'id', id
);
5949 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5950 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5951 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5952 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5958 * @param {Object} [config] Configuration options
5959 * @cfg {Object} [popup] Configuration to pass to popup
5960 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5962 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
5963 // Configuration initialization
5964 config
= config
|| {};
5967 this.popup
= new OO
.ui
.PopupWidget( $.extend(
5970 $floatableContainer
: this.$element
5974 $autoCloseIgnore
: this.$element
.add( config
.popup
&& config
.popup
.$autoCloseIgnore
)
5984 * @return {OO.ui.PopupWidget} Popup widget
5986 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
5991 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
5992 * which is used to display additional information or options.
5995 * // A PopupButtonWidget.
5996 * var popupButton = new OO.ui.PopupButtonWidget( {
5997 * label: 'Popup button with options',
6000 * $content: $( '<p>Additional options here.</p>' ),
6002 * align: 'force-left'
6005 * // Append the button to the DOM.
6006 * $( document.body ).append( popupButton.$element );
6009 * @extends OO.ui.ButtonWidget
6010 * @mixins OO.ui.mixin.PopupElement
6013 * @param {Object} [config] Configuration options
6014 * @cfg {jQuery} [$overlay] Render the popup into a separate layer. This configuration is useful in cases where
6015 * the expanded popup is larger than its containing `<div>`. The specified overlay layer is usually on top of the
6016 * containing `<div>` and has a larger area. By default, the popup uses relative positioning.
6017 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
6019 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
6020 // Configuration initialization
6021 config
= config
|| {};
6023 // Parent constructor
6024 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
6026 // Mixin constructors
6027 OO
.ui
.mixin
.PopupElement
.call( this, config
);
6030 this.$overlay
= ( config
.$overlay
=== true ? OO
.ui
.getDefaultOverlay() : config
.$overlay
) || this.$element
;
6033 this.connect( this, { click
: 'onAction' } );
6037 .addClass( 'oo-ui-popupButtonWidget' );
6039 .addClass( 'oo-ui-popupButtonWidget-popup' )
6040 .toggleClass( 'oo-ui-popupButtonWidget-framed-popup', this.isFramed() )
6041 .toggleClass( 'oo-ui-popupButtonWidget-frameless-popup', !this.isFramed() );
6042 this.$overlay
.append( this.popup
.$element
);
6047 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
6048 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
6053 * Handle the button action being triggered.
6057 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
6058 this.popup
.toggle();
6062 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
6064 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
6069 * @mixins OO.ui.mixin.GroupElement
6072 * @param {Object} [config] Configuration options
6074 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
6075 // Mixin constructors
6076 OO
.ui
.mixin
.GroupElement
.call( this, config
);
6081 OO
.mixinClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
6086 * Set the disabled state of the widget.
6088 * This will also update the disabled state of child widgets.
6090 * @param {boolean} disabled Disable widget
6092 * @return {OO.ui.Widget} The widget, for chaining
6094 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
6098 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
6099 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
6101 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
6103 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6104 this.items
[ i
].updateDisabled();
6112 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
6114 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
6115 * allows bidirectional communication.
6117 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
6125 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
6132 * Check if widget is disabled.
6134 * Checks parent if present, making disabled state inheritable.
6136 * @return {boolean} Widget is disabled
6138 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
6139 return this.disabled
||
6140 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
6144 * Set group element is in.
6146 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
6148 * @return {OO.ui.Widget} The widget, for chaining
6150 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
6152 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
6153 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
6155 // Initialize item disabled states
6156 this.updateDisabled();
6162 * OptionWidgets are special elements that can be selected and configured with data. The
6163 * data is often unique for each option, but it does not have to be. OptionWidgets are used
6164 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
6165 * and examples, please see the [OOUI documentation on MediaWiki][1].
6167 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6170 * @extends OO.ui.Widget
6171 * @mixins OO.ui.mixin.ItemWidget
6172 * @mixins OO.ui.mixin.LabelElement
6173 * @mixins OO.ui.mixin.FlaggedElement
6174 * @mixins OO.ui.mixin.AccessKeyedElement
6175 * @mixins OO.ui.mixin.TitledElement
6178 * @param {Object} [config] Configuration options
6180 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
6181 // Configuration initialization
6182 config
= config
|| {};
6184 // Parent constructor
6185 OO
.ui
.OptionWidget
.parent
.call( this, config
);
6187 // Mixin constructors
6188 OO
.ui
.mixin
.ItemWidget
.call( this );
6189 OO
.ui
.mixin
.LabelElement
.call( this, config
);
6190 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
6191 OO
.ui
.mixin
.AccessKeyedElement
.call( this, config
);
6192 OO
.ui
.mixin
.TitledElement
.call( this, config
);
6195 this.selected
= false;
6196 this.highlighted
= false;
6197 this.pressed
= false;
6201 .data( 'oo-ui-optionWidget', this )
6202 // Allow programmatic focussing (and by accesskey), but not tabbing
6203 .attr( 'tabindex', '-1' )
6204 .attr( 'role', 'option' )
6205 .attr( 'aria-selected', 'false' )
6206 .addClass( 'oo-ui-optionWidget' )
6207 .append( this.$label
);
6212 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
6213 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
6214 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
6215 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
6216 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
6217 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.TitledElement
);
6219 /* Static Properties */
6222 * Whether this option can be selected. See #setSelected.
6226 * @property {boolean}
6228 OO
.ui
.OptionWidget
.static.selectable
= true;
6231 * Whether this option can be highlighted. See #setHighlighted.
6235 * @property {boolean}
6237 OO
.ui
.OptionWidget
.static.highlightable
= true;
6240 * Whether this option can be pressed. See #setPressed.
6244 * @property {boolean}
6246 OO
.ui
.OptionWidget
.static.pressable
= true;
6249 * Whether this option will be scrolled into view when it is selected.
6253 * @property {boolean}
6255 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
6260 * Check if the option can be selected.
6262 * @return {boolean} Item is selectable
6264 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
6265 return this.constructor.static.selectable
&& !this.disabled
&& this.isVisible();
6269 * Check if the option can be highlighted. A highlight indicates that the option
6270 * may be selected when a user presses enter or clicks. Disabled items cannot
6273 * @return {boolean} Item is highlightable
6275 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
6276 return this.constructor.static.highlightable
&& !this.disabled
&& this.isVisible();
6280 * Check if the option can be pressed. The pressed state occurs when a user mouses
6281 * down on an item, but has not yet let go of the mouse.
6283 * @return {boolean} Item is pressable
6285 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
6286 return this.constructor.static.pressable
&& !this.disabled
&& this.isVisible();
6290 * Check if the option is selected.
6292 * @return {boolean} Item is selected
6294 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
6295 return this.selected
;
6299 * Check if the option is highlighted. A highlight indicates that the
6300 * item may be selected when a user presses enter or clicks.
6302 * @return {boolean} Item is highlighted
6304 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
6305 return this.highlighted
;
6309 * Check if the option is pressed. The pressed state occurs when a user mouses
6310 * down on an item, but has not yet let go of the mouse. The item may appear
6311 * selected, but it will not be selected until the user releases the mouse.
6313 * @return {boolean} Item is pressed
6315 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
6316 return this.pressed
;
6320 * Set the option’s selected state. In general, all modifications to the selection
6321 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
6322 * method instead of this method.
6324 * @param {boolean} [state=false] Select option
6326 * @return {OO.ui.Widget} The widget, for chaining
6328 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
6329 if ( this.constructor.static.selectable
) {
6330 this.selected
= !!state
;
6332 .toggleClass( 'oo-ui-optionWidget-selected', state
)
6333 .attr( 'aria-selected', state
.toString() );
6334 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
6335 this.scrollElementIntoView();
6337 this.updateThemeClasses();
6343 * Set the option’s highlighted state. In general, all programmatic
6344 * modifications to the highlight should be handled by the
6345 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
6346 * method instead of this method.
6348 * @param {boolean} [state=false] Highlight option
6350 * @return {OO.ui.Widget} The widget, for chaining
6352 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
6353 if ( this.constructor.static.highlightable
) {
6354 this.highlighted
= !!state
;
6355 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
6356 this.updateThemeClasses();
6362 * Set the option’s pressed state. In general, all
6363 * programmatic modifications to the pressed state should be handled by the
6364 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
6365 * method instead of this method.
6367 * @param {boolean} [state=false] Press option
6369 * @return {OO.ui.Widget} The widget, for chaining
6371 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
6372 if ( this.constructor.static.pressable
) {
6373 this.pressed
= !!state
;
6374 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
6375 this.updateThemeClasses();
6381 * Get text to match search strings against.
6383 * The default implementation returns the label text, but subclasses
6384 * can override this to provide more complex behavior.
6386 * @return {string|boolean} String to match search string against
6388 OO
.ui
.OptionWidget
.prototype.getMatchText = function () {
6389 var label
= this.getLabel();
6390 return typeof label
=== 'string' ? label
: this.$label
.text();
6394 * A SelectWidget is of a generic selection of options. The OOUI library contains several types of
6395 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
6396 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
6399 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
6400 * information, please see the [OOUI documentation on MediaWiki][1].
6403 * // A select widget with three options.
6404 * var select = new OO.ui.SelectWidget( {
6406 * new OO.ui.OptionWidget( {
6408 * label: 'Option One',
6410 * new OO.ui.OptionWidget( {
6412 * label: 'Option Two',
6414 * new OO.ui.OptionWidget( {
6416 * label: 'Option Three',
6420 * $( document.body ).append( select.$element );
6422 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6426 * @extends OO.ui.Widget
6427 * @mixins OO.ui.mixin.GroupWidget
6430 * @param {Object} [config] Configuration options
6431 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
6432 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
6433 * the [OOUI documentation on MediaWiki] [2] for examples.
6434 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6436 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
6437 // Configuration initialization
6438 config
= config
|| {};
6440 // Parent constructor
6441 OO
.ui
.SelectWidget
.parent
.call( this, config
);
6443 // Mixin constructors
6444 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
6447 this.pressed
= false;
6448 this.selecting
= null;
6449 this.onDocumentMouseUpHandler
= this.onDocumentMouseUp
.bind( this );
6450 this.onDocumentMouseMoveHandler
= this.onDocumentMouseMove
.bind( this );
6451 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
6452 this.onDocumentKeyPressHandler
= this.onDocumentKeyPress
.bind( this );
6453 this.keyPressBuffer
= '';
6454 this.keyPressBufferTimer
= null;
6455 this.blockMouseOverEvents
= 0;
6458 this.connect( this, {
6462 focusin
: this.onFocus
.bind( this ),
6463 mousedown
: this.onMouseDown
.bind( this ),
6464 mouseover
: this.onMouseOver
.bind( this ),
6465 mouseleave
: this.onMouseLeave
.bind( this )
6470 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
6471 .attr( 'role', 'listbox' );
6472 this.setFocusOwner( this.$element
);
6473 if ( Array
.isArray( config
.items
) ) {
6474 this.addItems( config
.items
);
6480 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
6481 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
6488 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
6490 * @param {OO.ui.OptionWidget|null} item Highlighted item
6496 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
6497 * pressed state of an option.
6499 * @param {OO.ui.OptionWidget|null} item Pressed item
6505 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
6507 * @param {OO.ui.OptionWidget|null} item Selected item
6512 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
6513 * @param {OO.ui.OptionWidget} item Chosen item
6519 * An `add` event is emitted when options are added to the select with the #addItems method.
6521 * @param {OO.ui.OptionWidget[]} items Added items
6522 * @param {number} index Index of insertion point
6528 * A `remove` event is emitted when options are removed from the select with the #clearItems
6529 * or #removeItems methods.
6531 * @param {OO.ui.OptionWidget[]} items Removed items
6537 * Handle focus events
6540 * @param {jQuery.Event} event
6542 OO
.ui
.SelectWidget
.prototype.onFocus = function ( event
) {
6544 if ( event
.target
=== this.$element
[ 0 ] ) {
6545 // This widget was focussed, e.g. by the user tabbing to it.
6546 // The styles for focus state depend on one of the items being selected.
6547 if ( !this.findSelectedItem() ) {
6548 item
= this.findFirstSelectableItem();
6551 if ( event
.target
.tabIndex
=== -1 ) {
6552 // One of the options got focussed (and the event bubbled up here).
6553 // They can't be tabbed to, but they can be activated using accesskeys.
6554 // OptionWidgets and focusable UI elements inside them have tabindex="-1" set.
6555 item
= this.findTargetItem( event
);
6557 // There is something actually user-focusable in one of the labels of the options, and the
6558 // user focussed it (e.g. by tabbing to it). Do nothing (especially, don't change the focus).
6564 if ( item
.constructor.static.highlightable
) {
6565 this.highlightItem( item
);
6567 this.selectItem( item
);
6571 if ( event
.target
!== this.$element
[ 0 ] ) {
6572 this.$focusOwner
.trigger( 'focus' );
6577 * Handle mouse down events.
6580 * @param {jQuery.Event} e Mouse down event
6581 * @return {undefined/boolean} False to prevent default if event is handled
6583 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
6586 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
6587 this.togglePressed( true );
6588 item
= this.findTargetItem( e
);
6589 if ( item
&& item
.isSelectable() ) {
6590 this.pressItem( item
);
6591 this.selecting
= item
;
6592 this.getElementDocument().addEventListener( 'mouseup', this.onDocumentMouseUpHandler
, true );
6593 this.getElementDocument().addEventListener( 'mousemove', this.onDocumentMouseMoveHandler
, true );
6600 * Handle document mouse up events.
6603 * @param {MouseEvent} e Mouse up event
6604 * @return {undefined/boolean} False to prevent default if event is handled
6606 OO
.ui
.SelectWidget
.prototype.onDocumentMouseUp = function ( e
) {
6609 this.togglePressed( false );
6610 if ( !this.selecting
) {
6611 item
= this.findTargetItem( e
);
6612 if ( item
&& item
.isSelectable() ) {
6613 this.selecting
= item
;
6616 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
&& this.selecting
) {
6617 this.pressItem( null );
6618 this.chooseItem( this.selecting
);
6619 this.selecting
= null;
6622 this.getElementDocument().removeEventListener( 'mouseup', this.onDocumentMouseUpHandler
, true );
6623 this.getElementDocument().removeEventListener( 'mousemove', this.onDocumentMouseMoveHandler
, true );
6628 // Deprecated alias since 0.28.3
6629 OO
.ui
.SelectWidget
.prototype.onMouseUp = function () {
6630 OO
.ui
.warnDeprecation( 'onMouseUp is deprecated, use onDocumentMouseUp instead' );
6631 this.onDocumentMouseUp
.apply( this, arguments
);
6635 * Handle document mouse move events.
6638 * @param {MouseEvent} e Mouse move event
6640 OO
.ui
.SelectWidget
.prototype.onDocumentMouseMove = function ( e
) {
6643 if ( !this.isDisabled() && this.pressed
) {
6644 item
= this.findTargetItem( e
);
6645 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
6646 this.pressItem( item
);
6647 this.selecting
= item
;
6652 // Deprecated alias since 0.28.3
6653 OO
.ui
.SelectWidget
.prototype.onMouseMove = function () {
6654 OO
.ui
.warnDeprecation( 'onMouseMove is deprecated, use onDocumentMouseMove instead' );
6655 this.onDocumentMouseMove
.apply( this, arguments
);
6659 * Handle mouse over events.
6662 * @param {jQuery.Event} e Mouse over event
6663 * @return {undefined/boolean} False to prevent default if event is handled
6665 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
6667 if ( this.blockMouseOverEvents
) {
6670 if ( !this.isDisabled() ) {
6671 item
= this.findTargetItem( e
);
6672 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
6678 * Handle mouse leave events.
6681 * @param {jQuery.Event} e Mouse over event
6682 * @return {undefined/boolean} False to prevent default if event is handled
6684 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
6685 if ( !this.isDisabled() ) {
6686 this.highlightItem( null );
6692 * Handle document key down events.
6695 * @param {KeyboardEvent} e Key down event
6697 OO
.ui
.SelectWidget
.prototype.onDocumentKeyDown = function ( e
) {
6700 currentItem
= this.findHighlightedItem() || this.findSelectedItem();
6702 if ( !this.isDisabled() && this.isVisible() ) {
6703 switch ( e
.keyCode
) {
6704 case OO
.ui
.Keys
.ENTER
:
6705 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
6706 // Was only highlighted, now let's select it. No-op if already selected.
6707 this.chooseItem( currentItem
);
6712 case OO
.ui
.Keys
.LEFT
:
6713 this.clearKeyPressBuffer();
6714 nextItem
= this.findRelativeSelectableItem( currentItem
, -1 );
6717 case OO
.ui
.Keys
.DOWN
:
6718 case OO
.ui
.Keys
.RIGHT
:
6719 this.clearKeyPressBuffer();
6720 nextItem
= this.findRelativeSelectableItem( currentItem
, 1 );
6723 case OO
.ui
.Keys
.ESCAPE
:
6724 case OO
.ui
.Keys
.TAB
:
6725 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
6726 currentItem
.setHighlighted( false );
6728 this.unbindDocumentKeyDownListener();
6729 this.unbindDocumentKeyPressListener();
6730 // Don't prevent tabbing away / defocusing
6736 if ( nextItem
.constructor.static.highlightable
) {
6737 this.highlightItem( nextItem
);
6739 this.chooseItem( nextItem
);
6741 this.scrollItemIntoView( nextItem
);
6746 e
.stopPropagation();
6751 // Deprecated alias since 0.28.3
6752 OO
.ui
.SelectWidget
.prototype.onKeyDown = function () {
6753 OO
.ui
.warnDeprecation( 'onKeyDown is deprecated, use onDocumentKeyDown instead' );
6754 this.onDocumentKeyDown
.apply( this, arguments
);
6758 * Bind document key down listener.
6762 OO
.ui
.SelectWidget
.prototype.bindDocumentKeyDownListener = function () {
6763 this.getElementDocument().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
6766 // Deprecated alias since 0.28.3
6767 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
6768 OO
.ui
.warnDeprecation( 'bindKeyDownListener is deprecated, use bindDocumentKeyDownListener instead' );
6769 this.bindDocumentKeyDownListener
.apply( this, arguments
);
6773 * Unbind document key down listener.
6777 OO
.ui
.SelectWidget
.prototype.unbindDocumentKeyDownListener = function () {
6778 this.getElementDocument().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
6781 // Deprecated alias since 0.28.3
6782 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
6783 OO
.ui
.warnDeprecation( 'unbindKeyDownListener is deprecated, use unbindDocumentKeyDownListener instead' );
6784 this.unbindDocumentKeyDownListener
.apply( this, arguments
);
6788 * Scroll item into view, preventing spurious mouse highlight actions from happening.
6790 * @param {OO.ui.OptionWidget} item Item to scroll into view
6792 OO
.ui
.SelectWidget
.prototype.scrollItemIntoView = function ( item
) {
6794 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling
6795 // and around 100-150 ms after it is finished.
6796 this.blockMouseOverEvents
++;
6797 item
.scrollElementIntoView().done( function () {
6798 setTimeout( function () {
6799 widget
.blockMouseOverEvents
--;
6805 * Clear the key-press buffer
6809 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
6810 if ( this.keyPressBufferTimer
) {
6811 clearTimeout( this.keyPressBufferTimer
);
6812 this.keyPressBufferTimer
= null;
6814 this.keyPressBuffer
= '';
6818 * Handle key press events.
6821 * @param {KeyboardEvent} e Key press event
6822 * @return {undefined/boolean} False to prevent default if event is handled
6824 OO
.ui
.SelectWidget
.prototype.onDocumentKeyPress = function ( e
) {
6825 var c
, filter
, item
;
6827 if ( !e
.charCode
) {
6828 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
6829 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
6834 // eslint-disable-next-line no-restricted-properties
6835 if ( String
.fromCodePoint
) {
6836 // eslint-disable-next-line no-restricted-properties
6837 c
= String
.fromCodePoint( e
.charCode
);
6839 c
= String
.fromCharCode( e
.charCode
);
6842 if ( this.keyPressBufferTimer
) {
6843 clearTimeout( this.keyPressBufferTimer
);
6845 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
6847 item
= this.findHighlightedItem() || this.findSelectedItem();
6849 if ( this.keyPressBuffer
=== c
) {
6850 // Common (if weird) special case: typing "xxxx" will cycle through all
6851 // the items beginning with "x".
6853 item
= this.findRelativeSelectableItem( item
, 1 );
6856 this.keyPressBuffer
+= c
;
6859 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
6860 if ( !item
|| !filter( item
) ) {
6861 item
= this.findRelativeSelectableItem( item
, 1, filter
);
6864 if ( this.isVisible() && item
.constructor.static.highlightable
) {
6865 this.highlightItem( item
);
6867 this.chooseItem( item
);
6869 this.scrollItemIntoView( item
);
6873 e
.stopPropagation();
6876 // Deprecated alias since 0.28.3
6877 OO
.ui
.SelectWidget
.prototype.onKeyPress = function () {
6878 OO
.ui
.warnDeprecation( 'onKeyPress is deprecated, use onDocumentKeyPress instead' );
6879 this.onDocumentKeyPress
.apply( this, arguments
);
6883 * Get a matcher for the specific string
6886 * @param {string} s String to match against items
6887 * @param {boolean} [exact=false] Only accept exact matches
6888 * @return {Function} function ( OO.ui.OptionWidget ) => boolean
6890 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
, exact
) {
6893 // eslint-disable-next-line no-restricted-properties
6894 if ( s
.normalize
) {
6895 // eslint-disable-next-line no-restricted-properties
6898 s
= exact
? s
.trim() : s
.replace( /^\s+/, '' );
6899 re
= '^\\s*' + s
.replace( /([\\{}()|.?*+\-^$[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
6903 re
= new RegExp( re
, 'i' );
6904 return function ( item
) {
6905 var matchText
= item
.getMatchText();
6906 // eslint-disable-next-line no-restricted-properties
6907 if ( matchText
.normalize
) {
6908 // eslint-disable-next-line no-restricted-properties
6909 matchText
= matchText
.normalize();
6911 return re
.test( matchText
);
6916 * Bind document key press listener.
6920 OO
.ui
.SelectWidget
.prototype.bindDocumentKeyPressListener = function () {
6921 this.getElementDocument().addEventListener( 'keypress', this.onDocumentKeyPressHandler
, true );
6924 // Deprecated alias since 0.28.3
6925 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
6926 OO
.ui
.warnDeprecation( 'bindKeyPressListener is deprecated, use bindDocumentKeyPressListener instead' );
6927 this.bindDocumentKeyPressListener
.apply( this, arguments
);
6931 * Unbind document key down listener.
6933 * If you override this, be sure to call this.clearKeyPressBuffer() from your
6938 OO
.ui
.SelectWidget
.prototype.unbindDocumentKeyPressListener = function () {
6939 this.getElementDocument().removeEventListener( 'keypress', this.onDocumentKeyPressHandler
, true );
6940 this.clearKeyPressBuffer();
6943 // Deprecated alias since 0.28.3
6944 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
6945 OO
.ui
.warnDeprecation( 'unbindKeyPressListener is deprecated, use unbindDocumentKeyPressListener instead' );
6946 this.unbindDocumentKeyPressListener
.apply( this, arguments
);
6950 * Visibility change handler
6953 * @param {boolean} visible
6955 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
6957 this.clearKeyPressBuffer();
6962 * Get the closest item to a jQuery.Event.
6965 * @param {jQuery.Event} e
6966 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
6968 OO
.ui
.SelectWidget
.prototype.findTargetItem = function ( e
) {
6969 var $option
= $( e
.target
).closest( '.oo-ui-optionWidget' );
6970 if ( !$option
.closest( '.oo-ui-selectWidget' ).is( this.$element
) ) {
6973 return $option
.data( 'oo-ui-optionWidget' ) || null;
6977 * Find selected item.
6979 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
6981 OO
.ui
.SelectWidget
.prototype.findSelectedItem = function () {
6984 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6985 if ( this.items
[ i
].isSelected() ) {
6986 return this.items
[ i
];
6993 * Find highlighted item.
6995 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
6997 OO
.ui
.SelectWidget
.prototype.findHighlightedItem = function () {
7000 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
7001 if ( this.items
[ i
].isHighlighted() ) {
7002 return this.items
[ i
];
7009 * Toggle pressed state.
7011 * Press is a state that occurs when a user mouses down on an item, but
7012 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
7013 * until the user releases the mouse.
7015 * @param {boolean} pressed An option is being pressed
7017 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
7018 if ( pressed
=== undefined ) {
7019 pressed
= !this.pressed
;
7021 if ( pressed
!== this.pressed
) {
7023 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
7024 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
7025 this.pressed
= pressed
;
7030 * Highlight an option. If the `item` param is omitted, no options will be highlighted
7031 * and any existing highlight will be removed. The highlight is mutually exclusive.
7033 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
7036 * @return {OO.ui.Widget} The widget, for chaining
7038 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
7039 var i
, len
, highlighted
,
7042 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
7043 highlighted
= this.items
[ i
] === item
;
7044 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
7045 this.items
[ i
].setHighlighted( highlighted
);
7051 this.$focusOwner
.attr( 'aria-activedescendant', item
.getElementId() );
7053 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
7055 this.emit( 'highlight', item
);
7062 * Fetch an item by its label.
7064 * @param {string} label Label of the item to select.
7065 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
7066 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
7068 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
7070 len
= this.items
.length
,
7071 filter
= this.getItemMatcher( label
, true );
7073 for ( i
= 0; i
< len
; i
++ ) {
7074 item
= this.items
[ i
];
7075 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
7082 filter
= this.getItemMatcher( label
, false );
7083 for ( i
= 0; i
< len
; i
++ ) {
7084 item
= this.items
[ i
];
7085 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
7101 * Programmatically select an option by its label. If the item does not exist,
7102 * all options will be deselected.
7104 * @param {string} [label] Label of the item to select.
7105 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
7108 * @return {OO.ui.Widget} The widget, for chaining
7110 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
7111 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
7112 if ( label
=== undefined || !itemFromLabel
) {
7113 return this.selectItem();
7115 return this.selectItem( itemFromLabel
);
7119 * Programmatically select an option by its data. If the `data` parameter is omitted,
7120 * or if the item does not exist, all options will be deselected.
7122 * @param {Object|string} [data] Value of the item to select, omit to deselect all
7125 * @return {OO.ui.Widget} The widget, for chaining
7127 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
7128 var itemFromData
= this.findItemFromData( data
);
7129 if ( data
=== undefined || !itemFromData
) {
7130 return this.selectItem();
7132 return this.selectItem( itemFromData
);
7136 * Programmatically select an option by its reference. If the `item` parameter is omitted,
7137 * all options will be deselected.
7139 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
7142 * @return {OO.ui.Widget} The widget, for chaining
7144 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
7145 var i
, len
, selected
,
7148 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
7149 selected
= this.items
[ i
] === item
;
7150 if ( this.items
[ i
].isSelected() !== selected
) {
7151 this.items
[ i
].setSelected( selected
);
7156 if ( item
&& !item
.constructor.static.highlightable
) {
7158 this.$focusOwner
.attr( 'aria-activedescendant', item
.getElementId() );
7160 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
7163 this.emit( 'select', item
);
7172 * Press is a state that occurs when a user mouses down on an item, but has not
7173 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
7174 * releases the mouse.
7176 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
7179 * @return {OO.ui.Widget} The widget, for chaining
7181 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
7182 var i
, len
, pressed
,
7185 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
7186 pressed
= this.items
[ i
] === item
;
7187 if ( this.items
[ i
].isPressed() !== pressed
) {
7188 this.items
[ i
].setPressed( pressed
);
7193 this.emit( 'press', item
);
7202 * Note that ‘choose’ should never be modified programmatically. A user can choose
7203 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
7204 * use the #selectItem method.
7206 * This method is identical to #selectItem, but may vary in subclasses that take additional action
7207 * when users choose an item with the keyboard or mouse.
7209 * @param {OO.ui.OptionWidget} item Item to choose
7212 * @return {OO.ui.Widget} The widget, for chaining
7214 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
7216 this.selectItem( item
);
7217 this.emit( 'choose', item
);
7224 * Find an option by its position relative to the specified item (or to the start of the option array,
7225 * if item is `null`). The direction in which to search through the option array is specified with a
7226 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
7227 * `null` if there are no options in the array.
7229 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
7230 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
7231 * @param {Function} [filter] Only consider items for which this function returns
7232 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
7233 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
7235 OO
.ui
.SelectWidget
.prototype.findRelativeSelectableItem = function ( item
, direction
, filter
) {
7236 var currentIndex
, nextIndex
, i
,
7237 increase
= direction
> 0 ? 1 : -1,
7238 len
= this.items
.length
;
7240 if ( item
instanceof OO
.ui
.OptionWidget
) {
7241 currentIndex
= this.items
.indexOf( item
);
7242 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
7244 // If no item is selected and moving forward, start at the beginning.
7245 // If moving backward, start at the end.
7246 nextIndex
= direction
> 0 ? 0 : len
- 1;
7249 for ( i
= 0; i
< len
; i
++ ) {
7250 item
= this.items
[ nextIndex
];
7252 item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() &&
7253 ( !filter
|| filter( item
) )
7257 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
7263 * Find the next selectable item or `null` if there are no selectable items.
7264 * Disabled options and menu-section markers and breaks are not selectable.
7266 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
7268 OO
.ui
.SelectWidget
.prototype.findFirstSelectableItem = function () {
7269 return this.findRelativeSelectableItem( null, 1 );
7273 * Add an array of options to the select. Optionally, an index number can be used to
7274 * specify an insertion point.
7276 * @param {OO.ui.OptionWidget[]} items Items to add
7277 * @param {number} [index] Index to insert items after
7280 * @return {OO.ui.Widget} The widget, for chaining
7282 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
7284 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
7286 // Always provide an index, even if it was omitted
7287 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
7293 * Remove the specified array of options from the select. Options will be detached
7294 * from the DOM, not removed, so they can be reused later. To remove all options from
7295 * the select, you may wish to use the #clearItems method instead.
7297 * @param {OO.ui.OptionWidget[]} items Items to remove
7300 * @return {OO.ui.Widget} The widget, for chaining
7302 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
7305 // Deselect items being removed
7306 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
7308 if ( item
.isSelected() ) {
7309 this.selectItem( null );
7314 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
7316 this.emit( 'remove', items
);
7322 * Clear all options from the select. Options will be detached from the DOM, not removed,
7323 * so that they can be reused later. To remove a subset of options from the select, use
7324 * the #removeItems method.
7328 * @return {OO.ui.Widget} The widget, for chaining
7330 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
7331 var items
= this.items
.slice();
7334 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
7337 this.selectItem( null );
7339 this.emit( 'remove', items
);
7345 * Set the DOM element which has focus while the user is interacting with this SelectWidget.
7347 * This is used to set `aria-activedescendant` and `aria-expanded` on it.
7350 * @param {jQuery} $focusOwner
7352 OO
.ui
.SelectWidget
.prototype.setFocusOwner = function ( $focusOwner
) {
7353 this.$focusOwner
= $focusOwner
;
7357 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
7358 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
7359 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
7360 * options. For more information about options and selects, please see the
7361 * [OOUI documentation on MediaWiki][1].
7364 * // Decorated options in a select widget.
7365 * var select = new OO.ui.SelectWidget( {
7367 * new OO.ui.DecoratedOptionWidget( {
7369 * label: 'Option with icon',
7372 * new OO.ui.DecoratedOptionWidget( {
7374 * label: 'Option with indicator',
7379 * $( document.body ).append( select.$element );
7381 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7384 * @extends OO.ui.OptionWidget
7385 * @mixins OO.ui.mixin.IconElement
7386 * @mixins OO.ui.mixin.IndicatorElement
7389 * @param {Object} [config] Configuration options
7391 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
7392 // Parent constructor
7393 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
7395 // Mixin constructors
7396 OO
.ui
.mixin
.IconElement
.call( this, config
);
7397 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
7401 .addClass( 'oo-ui-decoratedOptionWidget' )
7402 .prepend( this.$icon
)
7403 .append( this.$indicator
);
7408 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
7409 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
7410 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
7413 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
7414 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
7415 * the [OOUI documentation on MediaWiki] [1] for more information.
7417 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
7420 * @extends OO.ui.DecoratedOptionWidget
7423 * @param {Object} [config] Configuration options
7425 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
7426 // Parent constructor
7427 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
7430 this.checkIcon
= new OO
.ui
.IconWidget( {
7432 classes
: [ 'oo-ui-menuOptionWidget-checkIcon' ]
7437 .prepend( this.checkIcon
.$element
)
7438 .addClass( 'oo-ui-menuOptionWidget' );
7443 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
7445 /* Static Properties */
7451 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
7454 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
7455 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
7458 * var dropdown = new OO.ui.DropdownWidget( {
7461 * new OO.ui.MenuSectionOptionWidget( {
7464 * new OO.ui.MenuOptionWidget( {
7466 * label: 'Welsh Corgi'
7468 * new OO.ui.MenuOptionWidget( {
7470 * label: 'Standard Poodle'
7472 * new OO.ui.MenuSectionOptionWidget( {
7475 * new OO.ui.MenuOptionWidget( {
7482 * $( document.body ).append( dropdown.$element );
7485 * @extends OO.ui.DecoratedOptionWidget
7488 * @param {Object} [config] Configuration options
7490 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
7491 // Parent constructor
7492 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
7495 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' )
7496 .removeAttr( 'role aria-selected' );
7501 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
7503 /* Static Properties */
7509 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
7515 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
7518 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
7519 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
7520 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
7521 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
7522 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
7523 * and customized to be opened, closed, and displayed as needed.
7525 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
7526 * mouse outside the menu.
7528 * Menus also have support for keyboard interaction:
7530 * - Enter/Return key: choose and select a menu option
7531 * - Up-arrow key: highlight the previous menu option
7532 * - Down-arrow key: highlight the next menu option
7533 * - Esc key: hide the menu
7535 * Unlike most widgets, MenuSelectWidget is initially hidden and must be shown by calling #toggle.
7537 * Please see the [OOUI documentation on MediaWiki][1] for more information.
7538 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7541 * @extends OO.ui.SelectWidget
7542 * @mixins OO.ui.mixin.ClippableElement
7543 * @mixins OO.ui.mixin.FloatableElement
7546 * @param {Object} [config] Configuration options
7547 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
7548 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
7549 * and {@link OO.ui.mixin.LookupElement LookupElement}
7550 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
7551 * the text the user types. This config is used by {@link OO.ui.TagMultiselectWidget TagMultiselectWidget}
7552 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
7553 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
7554 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
7555 * that button, unless the button (or its parent widget) is passed in here.
7556 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
7557 * @cfg {jQuery} [$autoCloseIgnore] If these elements are clicked, don't auto-hide the menu.
7558 * @cfg {boolean} [hideOnChoose=true] Hide the menu when the user chooses an option.
7559 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
7560 * @cfg {boolean} [highlightOnFilter] Highlight the first result when filtering
7561 * @param {number|string} [width] Width of the menu as a number of pixels or CSS string with unit suffix,
7562 * used by {@link OO.ui.mixin.ClippableElement ClippableElement}
7564 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
7565 // Configuration initialization
7566 config
= config
|| {};
7568 // Parent constructor
7569 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
7571 // Mixin constructors
7572 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
7573 OO
.ui
.mixin
.FloatableElement
.call( this, config
);
7575 // Initial vertical positions other than 'center' will result in
7576 // the menu being flipped if there is not enough space in the container.
7577 // Store the original position so we know what to reset to.
7578 this.originalVerticalPosition
= this.verticalPosition
;
7581 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
7582 this.hideOnChoose
= config
.hideOnChoose
=== undefined || !!config
.hideOnChoose
;
7583 this.filterFromInput
= !!config
.filterFromInput
;
7584 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
7585 this.$widget
= config
.widget
? config
.widget
.$element
: null;
7586 this.$autoCloseIgnore
= config
.$autoCloseIgnore
|| $( [] );
7587 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
7588 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
7589 this.highlightOnFilter
= !!config
.highlightOnFilter
;
7590 this.width
= config
.width
;
7593 this.$element
.addClass( 'oo-ui-menuSelectWidget' );
7594 if ( config
.widget
) {
7595 this.setFocusOwner( config
.widget
.$tabIndexed
);
7598 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
7599 // that reference properties not initialized at that time of parent class construction
7600 // TODO: Find a better way to handle post-constructor setup
7601 this.visible
= false;
7602 this.$element
.addClass( 'oo-ui-element-hidden' );
7603 this.$focusOwner
.attr( 'aria-expanded', 'false' );
7608 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
7609 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
7610 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.FloatableElement
);
7617 * The menu is ready: it is visible and has been positioned and clipped.
7620 /* Static properties */
7623 * Positions to flip to if there isn't room in the container for the
7624 * menu in a specific direction.
7626 * @property {Object.<string,string>}
7628 OO
.ui
.MenuSelectWidget
.static.flippedPositions
= {
7638 * Handles document mouse down events.
7641 * @param {MouseEvent} e Mouse down event
7643 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
7647 this.$element
.add( this.$widget
).add( this.$autoCloseIgnore
).get(),
7652 this.toggle( false );
7659 OO
.ui
.MenuSelectWidget
.prototype.onDocumentKeyDown = function ( e
) {
7660 var currentItem
= this.findHighlightedItem() || this.findSelectedItem();
7662 if ( !this.isDisabled() && this.isVisible() ) {
7663 switch ( e
.keyCode
) {
7664 case OO
.ui
.Keys
.LEFT
:
7665 case OO
.ui
.Keys
.RIGHT
:
7666 // Do nothing if a text field is associated, arrow keys will be handled natively
7667 if ( !this.$input
) {
7668 OO
.ui
.MenuSelectWidget
.parent
.prototype.onDocumentKeyDown
.call( this, e
);
7671 case OO
.ui
.Keys
.ESCAPE
:
7672 case OO
.ui
.Keys
.TAB
:
7673 if ( currentItem
) {
7674 currentItem
.setHighlighted( false );
7676 this.toggle( false );
7677 // Don't prevent tabbing away, prevent defocusing
7678 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
7680 e
.stopPropagation();
7684 OO
.ui
.MenuSelectWidget
.parent
.prototype.onDocumentKeyDown
.call( this, e
);
7691 * Update menu item visibility and clipping after input changes (if filterFromInput is enabled)
7692 * or after items were added/removed (always).
7696 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
7697 var i
, item
, items
, visible
, section
, sectionEmpty
, filter
, exactFilter
,
7699 len
= this.items
.length
,
7700 showAll
= !this.isVisible(),
7703 if ( this.$input
&& this.filterFromInput
) {
7704 filter
= showAll
? null : this.getItemMatcher( this.$input
.val() );
7705 exactFilter
= this.getItemMatcher( this.$input
.val(), true );
7706 // Hide non-matching options, and also hide section headers if all options
7707 // in their section are hidden.
7708 for ( i
= 0; i
< len
; i
++ ) {
7709 item
= this.items
[ i
];
7710 if ( item
instanceof OO
.ui
.MenuSectionOptionWidget
) {
7712 // If the previous section was empty, hide its header
7713 section
.toggle( showAll
|| !sectionEmpty
);
7716 sectionEmpty
= true;
7717 } else if ( item
instanceof OO
.ui
.OptionWidget
) {
7718 visible
= showAll
|| filter( item
);
7719 exactMatch
= exactMatch
|| exactFilter( item
);
7720 anyVisible
= anyVisible
|| visible
;
7721 sectionEmpty
= sectionEmpty
&& !visible
;
7722 item
.toggle( visible
);
7725 // Process the final section
7727 section
.toggle( showAll
|| !sectionEmpty
);
7730 if ( anyVisible
&& this.items
.length
&& !exactMatch
) {
7731 this.scrollItemIntoView( this.items
[ 0 ] );
7734 if ( !anyVisible
) {
7735 this.highlightItem( null );
7738 this.$element
.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible
);
7740 if ( this.highlightOnFilter
) {
7741 // Highlight the first item on the list
7743 items
= this.getItems();
7744 for ( i
= 0; i
< items
.length
; i
++ ) {
7745 if ( items
[ i
].isVisible() ) {
7750 this.highlightItem( item
);
7755 // Reevaluate clipping
7762 OO
.ui
.MenuSelectWidget
.prototype.bindDocumentKeyDownListener = function () {
7763 if ( this.$input
) {
7764 this.$input
.on( 'keydown', this.onDocumentKeyDownHandler
);
7766 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindDocumentKeyDownListener
.call( this );
7773 OO
.ui
.MenuSelectWidget
.prototype.unbindDocumentKeyDownListener = function () {
7774 if ( this.$input
) {
7775 this.$input
.off( 'keydown', this.onDocumentKeyDownHandler
);
7777 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindDocumentKeyDownListener
.call( this );
7784 OO
.ui
.MenuSelectWidget
.prototype.bindDocumentKeyPressListener = function () {
7785 if ( this.$input
) {
7786 if ( this.filterFromInput
) {
7787 this.$input
.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
7788 this.updateItemVisibility();
7791 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindDocumentKeyPressListener
.call( this );
7798 OO
.ui
.MenuSelectWidget
.prototype.unbindDocumentKeyPressListener = function () {
7799 if ( this.$input
) {
7800 if ( this.filterFromInput
) {
7801 this.$input
.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
7802 this.updateItemVisibility();
7805 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindDocumentKeyPressListener
.call( this );
7812 * When a user chooses an item, the menu is closed, unless the hideOnChoose config option is set to false.
7814 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
7815 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
7817 * @param {OO.ui.OptionWidget} item Item to choose
7819 * @return {OO.ui.Widget} The widget, for chaining
7821 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
7822 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
7823 if ( this.hideOnChoose
) {
7824 this.toggle( false );
7832 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
7834 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
7836 this.updateItemVisibility();
7844 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
7846 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
7848 this.updateItemVisibility();
7856 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
7858 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
7860 this.updateItemVisibility();
7866 * Toggle visibility of the menu. The menu is initially hidden and must be shown by calling
7867 * `.toggle( true )` after its #$element is attached to the DOM.
7869 * Do not show the menu while it is not attached to the DOM. The calculations required to display
7870 * it in the right place and with the right dimensions only work correctly while it is attached.
7871 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
7872 * strictly enforced, so currently it only generates a warning in the browser console.
7877 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
7878 var change
, originalHeight
, flippedHeight
;
7880 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
7881 change
= visible
!== this.isVisible();
7883 if ( visible
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
7884 OO
.ui
.warnDeprecation( 'MenuSelectWidget#toggle: Before calling this method, the menu must be attached to the DOM.' );
7885 this.warnedUnattached
= true;
7888 if ( change
&& visible
) {
7889 // Reset position before showing the popup again. It's possible we no longer need to flip
7890 // (e.g. if the user scrolled).
7891 this.setVerticalPosition( this.originalVerticalPosition
);
7895 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
7901 this.setIdealSize( this.width
);
7902 } else if ( this.$floatableContainer
) {
7903 this.$clippable
.css( 'width', 'auto' );
7905 this.$floatableContainer
[ 0 ].offsetWidth
> this.$clippable
[ 0 ].offsetWidth
?
7906 // Dropdown is smaller than handle so expand to width
7907 this.$floatableContainer
[ 0 ].offsetWidth
:
7908 // Dropdown is larger than handle so auto size
7911 this.$clippable
.css( 'width', '' );
7914 this.togglePositioning( !!this.$floatableContainer
);
7915 this.toggleClipping( true );
7917 this.bindDocumentKeyDownListener();
7918 this.bindDocumentKeyPressListener();
7921 ( this.isClippedVertically() || this.isFloatableOutOfView() ) &&
7922 this.originalVerticalPosition
!== 'center'
7924 // If opening the menu in one direction causes it to be clipped, flip it
7925 originalHeight
= this.$element
.height();
7926 this.setVerticalPosition(
7927 this.constructor.static.flippedPositions
[ this.originalVerticalPosition
]
7929 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
7930 // If flipping also causes it to be clipped, open in whichever direction
7931 // we have more space
7932 flippedHeight
= this.$element
.height();
7933 if ( originalHeight
> flippedHeight
) {
7934 this.setVerticalPosition( this.originalVerticalPosition
);
7938 // Note that we do not flip the menu's opening direction if the clipping changes
7939 // later (e.g. after the user scrolls), that seems like it would be annoying
7941 this.$focusOwner
.attr( 'aria-expanded', 'true' );
7943 if ( this.findSelectedItem() ) {
7944 this.$focusOwner
.attr( 'aria-activedescendant', this.findSelectedItem().getElementId() );
7945 this.findSelectedItem().scrollElementIntoView( { duration
: 0 } );
7949 if ( this.autoHide
) {
7950 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
7953 this.emit( 'ready' );
7955 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
7956 this.unbindDocumentKeyDownListener();
7957 this.unbindDocumentKeyPressListener();
7958 this.$focusOwner
.attr( 'aria-expanded', 'false' );
7959 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
7960 this.togglePositioning( false );
7961 this.toggleClipping( false );
7969 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
7970 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
7971 * users can interact with it.
7973 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7974 * OO.ui.DropdownInputWidget instead.
7977 * // A DropdownWidget with a menu that contains three options.
7978 * var dropDown = new OO.ui.DropdownWidget( {
7979 * label: 'Dropdown menu: Select a menu option',
7982 * new OO.ui.MenuOptionWidget( {
7986 * new OO.ui.MenuOptionWidget( {
7990 * new OO.ui.MenuOptionWidget( {
7998 * $( document.body ).append( dropDown.$element );
8000 * dropDown.getMenu().selectItemByData( 'b' );
8002 * dropDown.getMenu().findSelectedItem().getData(); // Returns 'b'.
8004 * For more information, please see the [OOUI documentation on MediaWiki] [1].
8006 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
8009 * @extends OO.ui.Widget
8010 * @mixins OO.ui.mixin.IconElement
8011 * @mixins OO.ui.mixin.IndicatorElement
8012 * @mixins OO.ui.mixin.LabelElement
8013 * @mixins OO.ui.mixin.TitledElement
8014 * @mixins OO.ui.mixin.TabIndexedElement
8017 * @param {Object} [config] Configuration options
8018 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.MenuSelectWidget menu select widget}
8019 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
8020 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
8021 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
8022 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
8024 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
8025 // Configuration initialization
8026 config
= $.extend( { indicator
: 'down' }, config
);
8028 // Parent constructor
8029 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
8031 // Properties (must be set before TabIndexedElement constructor call)
8032 this.$handle
= $( '<button>' );
8033 this.$overlay
= ( config
.$overlay
=== true ? OO
.ui
.getDefaultOverlay() : config
.$overlay
) || this.$element
;
8035 // Mixin constructors
8036 OO
.ui
.mixin
.IconElement
.call( this, config
);
8037 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
8038 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8039 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
8040 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
8043 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend( {
8045 $floatableContainer
: this.$element
8050 click
: this.onClick
.bind( this ),
8051 keydown
: this.onKeyDown
.bind( this ),
8052 // Hack? Handle type-to-search when menu is not expanded and not handling its own events
8053 keypress
: this.menu
.onDocumentKeyPressHandler
,
8054 blur
: this.menu
.clearKeyPressBuffer
.bind( this.menu
)
8056 this.menu
.connect( this, {
8057 select
: 'onMenuSelect',
8058 toggle
: 'onMenuToggle'
8063 .addClass( 'oo-ui-dropdownWidget-handle' )
8066 'aria-owns': this.menu
.getElementId(),
8067 'aria-haspopup': 'listbox'
8069 .append( this.$icon
, this.$label
, this.$indicator
);
8071 .addClass( 'oo-ui-dropdownWidget' )
8072 .append( this.$handle
);
8073 this.$overlay
.append( this.menu
.$element
);
8078 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
8079 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
8080 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
8081 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
8082 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
8083 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
8090 * @return {OO.ui.MenuSelectWidget} Menu of widget
8092 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
8097 * Handles menu select events.
8100 * @param {OO.ui.MenuOptionWidget} item Selected menu item
8102 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
8106 this.setLabel( null );
8110 selectedLabel
= item
.getLabel();
8112 // If the label is a DOM element, clone it, because setLabel will append() it
8113 if ( selectedLabel
instanceof $ ) {
8114 selectedLabel
= selectedLabel
.clone();
8117 this.setLabel( selectedLabel
);
8121 * Handle menu toggle events.
8124 * @param {boolean} isVisible Open state of the menu
8126 OO
.ui
.DropdownWidget
.prototype.onMenuToggle = function ( isVisible
) {
8127 this.$element
.toggleClass( 'oo-ui-dropdownWidget-open', isVisible
);
8131 * Handle mouse click events.
8134 * @param {jQuery.Event} e Mouse click event
8135 * @return {undefined/boolean} False to prevent default if event is handled
8137 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
8138 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
8145 * Handle key down events.
8148 * @param {jQuery.Event} e Key down event
8149 * @return {undefined/boolean} False to prevent default if event is handled
8151 OO
.ui
.DropdownWidget
.prototype.onKeyDown = function ( e
) {
8153 !this.isDisabled() &&
8155 e
.which
=== OO
.ui
.Keys
.ENTER
||
8157 e
.which
=== OO
.ui
.Keys
.SPACE
&&
8158 // Avoid conflicts with type-to-search, see SelectWidget#onKeyPress.
8159 // Space only closes the menu is the user is not typing to search.
8160 this.menu
.keyPressBuffer
=== ''
8163 !this.menu
.isVisible() &&
8165 e
.which
=== OO
.ui
.Keys
.UP
||
8166 e
.which
=== OO
.ui
.Keys
.DOWN
8177 * RadioOptionWidget is an option widget that looks like a radio button.
8178 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
8179 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8181 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8184 * @extends OO.ui.OptionWidget
8187 * @param {Object} [config] Configuration options
8189 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
8190 // Configuration initialization
8191 config
= config
|| {};
8193 // Properties (must be done before parent constructor which calls #setDisabled)
8194 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
8196 // Parent constructor
8197 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
8200 // Remove implicit role, we're handling it ourselves
8201 this.radio
.$input
.attr( 'role', 'presentation' );
8203 .addClass( 'oo-ui-radioOptionWidget' )
8204 .attr( 'role', 'radio' )
8205 .attr( 'aria-checked', 'false' )
8206 .removeAttr( 'aria-selected' )
8207 .prepend( this.radio
.$element
);
8212 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
8214 /* Static Properties */
8220 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
8226 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
8232 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
8238 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
8245 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
8246 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
8248 this.radio
.setSelected( state
);
8250 .attr( 'aria-checked', state
.toString() )
8251 .removeAttr( 'aria-selected' );
8259 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
8260 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
8262 this.radio
.setDisabled( this.isDisabled() );
8268 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
8269 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
8270 * an interface for adding, removing and selecting options.
8271 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8273 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8274 * OO.ui.RadioSelectInputWidget instead.
8277 * // A RadioSelectWidget with RadioOptions.
8278 * var option1 = new OO.ui.RadioOptionWidget( {
8280 * label: 'Selected radio option'
8282 * option2 = new OO.ui.RadioOptionWidget( {
8284 * label: 'Unselected radio option'
8286 * radioSelect = new OO.ui.RadioSelectWidget( {
8287 * items: [ option1, option2 ]
8290 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
8291 * radioSelect.selectItem( option1 );
8293 * $( document.body ).append( radioSelect.$element );
8295 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8299 * @extends OO.ui.SelectWidget
8300 * @mixins OO.ui.mixin.TabIndexedElement
8303 * @param {Object} [config] Configuration options
8305 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
8306 // Parent constructor
8307 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
8309 // Mixin constructors
8310 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
8314 focus
: this.bindDocumentKeyDownListener
.bind( this ),
8315 blur
: this.unbindDocumentKeyDownListener
.bind( this )
8320 .addClass( 'oo-ui-radioSelectWidget' )
8321 .attr( 'role', 'radiogroup' );
8326 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
8327 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
8330 * MultioptionWidgets are special elements that can be selected and configured with data. The
8331 * data is often unique for each option, but it does not have to be. MultioptionWidgets are used
8332 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
8333 * and examples, please see the [OOUI documentation on MediaWiki][1].
8335 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8338 * @extends OO.ui.Widget
8339 * @mixins OO.ui.mixin.ItemWidget
8340 * @mixins OO.ui.mixin.LabelElement
8341 * @mixins OO.ui.mixin.TitledElement
8344 * @param {Object} [config] Configuration options
8345 * @cfg {boolean} [selected=false] Whether the option is initially selected
8347 OO
.ui
.MultioptionWidget
= function OoUiMultioptionWidget( config
) {
8348 // Configuration initialization
8349 config
= config
|| {};
8351 // Parent constructor
8352 OO
.ui
.MultioptionWidget
.parent
.call( this, config
);
8354 // Mixin constructors
8355 OO
.ui
.mixin
.ItemWidget
.call( this );
8356 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8357 OO
.ui
.mixin
.TitledElement
.call( this, config
);
8360 this.selected
= null;
8364 .addClass( 'oo-ui-multioptionWidget' )
8365 .append( this.$label
);
8366 this.setSelected( config
.selected
);
8371 OO
.inheritClass( OO
.ui
.MultioptionWidget
, OO
.ui
.Widget
);
8372 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.ItemWidget
);
8373 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.LabelElement
);
8374 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.TitledElement
);
8381 * A change event is emitted when the selected state of the option changes.
8383 * @param {boolean} selected Whether the option is now selected
8389 * Check if the option is selected.
8391 * @return {boolean} Item is selected
8393 OO
.ui
.MultioptionWidget
.prototype.isSelected = function () {
8394 return this.selected
;
8398 * Set the option’s selected state. In general, all modifications to the selection
8399 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
8400 * method instead of this method.
8402 * @param {boolean} [state=false] Select option
8404 * @return {OO.ui.Widget} The widget, for chaining
8406 OO
.ui
.MultioptionWidget
.prototype.setSelected = function ( state
) {
8408 if ( this.selected
!== state
) {
8409 this.selected
= state
;
8410 this.emit( 'change', state
);
8411 this.$element
.toggleClass( 'oo-ui-multioptionWidget-selected', state
);
8417 * MultiselectWidget allows selecting multiple options from a list.
8419 * For more information about menus and options, please see the [OOUI documentation on MediaWiki][1].
8421 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
8425 * @extends OO.ui.Widget
8426 * @mixins OO.ui.mixin.GroupWidget
8427 * @mixins OO.ui.mixin.TitledElement
8430 * @param {Object} [config] Configuration options
8431 * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
8433 OO
.ui
.MultiselectWidget
= function OoUiMultiselectWidget( config
) {
8434 // Parent constructor
8435 OO
.ui
.MultiselectWidget
.parent
.call( this, config
);
8437 // Configuration initialization
8438 config
= config
|| {};
8440 // Mixin constructors
8441 OO
.ui
.mixin
.GroupWidget
.call( this, config
);
8442 OO
.ui
.mixin
.TitledElement
.call( this, config
);
8445 this.aggregate( { change
: 'select' } );
8446 // This is mostly for compatibility with TagMultiselectWidget... normally, 'change' is emitted
8447 // by GroupElement only when items are added/removed
8448 this.connect( this, { select
: [ 'emit', 'change' ] } );
8451 if ( config
.items
) {
8452 this.addItems( config
.items
);
8454 this.$group
.addClass( 'oo-ui-multiselectWidget-group' );
8455 this.$element
.addClass( 'oo-ui-multiselectWidget' )
8456 .append( this.$group
);
8461 OO
.inheritClass( OO
.ui
.MultiselectWidget
, OO
.ui
.Widget
);
8462 OO
.mixinClass( OO
.ui
.MultiselectWidget
, OO
.ui
.mixin
.GroupWidget
);
8463 OO
.mixinClass( OO
.ui
.MultiselectWidget
, OO
.ui
.mixin
.TitledElement
);
8470 * A change event is emitted when the set of items changes, or an item is selected or deselected.
8476 * A select event is emitted when an item is selected or deselected.
8482 * Find options that are selected.
8484 * @return {OO.ui.MultioptionWidget[]} Selected options
8486 OO
.ui
.MultiselectWidget
.prototype.findSelectedItems = function () {
8487 return this.items
.filter( function ( item
) {
8488 return item
.isSelected();
8493 * Find the data of options that are selected.
8495 * @return {Object[]|string[]} Values of selected options
8497 OO
.ui
.MultiselectWidget
.prototype.findSelectedItemsData = function () {
8498 return this.findSelectedItems().map( function ( item
) {
8504 * Select options by reference. Options not mentioned in the `items` array will be deselected.
8506 * @param {OO.ui.MultioptionWidget[]} items Items to select
8508 * @return {OO.ui.Widget} The widget, for chaining
8510 OO
.ui
.MultiselectWidget
.prototype.selectItems = function ( items
) {
8511 this.items
.forEach( function ( item
) {
8512 var selected
= items
.indexOf( item
) !== -1;
8513 item
.setSelected( selected
);
8519 * Select items by their data. Options not mentioned in the `datas` array will be deselected.
8521 * @param {Object[]|string[]} datas Values of items to select
8523 * @return {OO.ui.Widget} The widget, for chaining
8525 OO
.ui
.MultiselectWidget
.prototype.selectItemsByData = function ( datas
) {
8528 items
= datas
.map( function ( data
) {
8529 return widget
.findItemFromData( data
);
8531 this.selectItems( items
);
8536 * CheckboxMultioptionWidget is an option widget that looks like a checkbox.
8537 * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
8538 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8540 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8543 * @extends OO.ui.MultioptionWidget
8546 * @param {Object} [config] Configuration options
8548 OO
.ui
.CheckboxMultioptionWidget
= function OoUiCheckboxMultioptionWidget( config
) {
8549 // Configuration initialization
8550 config
= config
|| {};
8552 // Properties (must be done before parent constructor which calls #setDisabled)
8553 this.checkbox
= new OO
.ui
.CheckboxInputWidget();
8555 // Parent constructor
8556 OO
.ui
.CheckboxMultioptionWidget
.parent
.call( this, config
);
8559 this.checkbox
.on( 'change', this.onCheckboxChange
.bind( this ) );
8560 this.$element
.on( 'keydown', this.onKeyDown
.bind( this ) );
8564 .addClass( 'oo-ui-checkboxMultioptionWidget' )
8565 .prepend( this.checkbox
.$element
);
8570 OO
.inheritClass( OO
.ui
.CheckboxMultioptionWidget
, OO
.ui
.MultioptionWidget
);
8572 /* Static Properties */
8578 OO
.ui
.CheckboxMultioptionWidget
.static.tagName
= 'label';
8583 * Handle checkbox selected state change.
8587 OO
.ui
.CheckboxMultioptionWidget
.prototype.onCheckboxChange = function () {
8588 this.setSelected( this.checkbox
.isSelected() );
8594 OO
.ui
.CheckboxMultioptionWidget
.prototype.setSelected = function ( state
) {
8595 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setSelected
.call( this, state
);
8596 this.checkbox
.setSelected( state
);
8603 OO
.ui
.CheckboxMultioptionWidget
.prototype.setDisabled = function ( disabled
) {
8604 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
8605 this.checkbox
.setDisabled( this.isDisabled() );
8612 OO
.ui
.CheckboxMultioptionWidget
.prototype.focus = function () {
8613 this.checkbox
.focus();
8617 * Handle key down events.
8620 * @param {jQuery.Event} e
8622 OO
.ui
.CheckboxMultioptionWidget
.prototype.onKeyDown = function ( e
) {
8624 element
= this.getElementGroup(),
8627 if ( e
.keyCode
=== OO
.ui
.Keys
.LEFT
|| e
.keyCode
=== OO
.ui
.Keys
.UP
) {
8628 nextItem
= element
.getRelativeFocusableItem( this, -1 );
8629 } else if ( e
.keyCode
=== OO
.ui
.Keys
.RIGHT
|| e
.keyCode
=== OO
.ui
.Keys
.DOWN
) {
8630 nextItem
= element
.getRelativeFocusableItem( this, 1 );
8640 * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
8641 * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
8642 * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
8643 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8645 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8646 * OO.ui.CheckboxMultiselectInputWidget instead.
8649 * // A CheckboxMultiselectWidget with CheckboxMultioptions.
8650 * var option1 = new OO.ui.CheckboxMultioptionWidget( {
8653 * label: 'Selected checkbox'
8655 * option2 = new OO.ui.CheckboxMultioptionWidget( {
8657 * label: 'Unselected checkbox'
8659 * multiselect = new OO.ui.CheckboxMultiselectWidget( {
8660 * items: [ option1, option2 ]
8662 * $( document.body ).append( multiselect.$element );
8664 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8667 * @extends OO.ui.MultiselectWidget
8670 * @param {Object} [config] Configuration options
8672 OO
.ui
.CheckboxMultiselectWidget
= function OoUiCheckboxMultiselectWidget( config
) {
8673 // Parent constructor
8674 OO
.ui
.CheckboxMultiselectWidget
.parent
.call( this, config
);
8677 this.$lastClicked
= null;
8680 this.$group
.on( 'click', this.onClick
.bind( this ) );
8684 .addClass( 'oo-ui-checkboxMultiselectWidget' );
8689 OO
.inheritClass( OO
.ui
.CheckboxMultiselectWidget
, OO
.ui
.MultiselectWidget
);
8694 * Get an option by its position relative to the specified item (or to the start of the option array,
8695 * if item is `null`). The direction in which to search through the option array is specified with a
8696 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
8697 * `null` if there are no options in the array.
8699 * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
8700 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
8701 * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items in the select
8703 OO
.ui
.CheckboxMultiselectWidget
.prototype.getRelativeFocusableItem = function ( item
, direction
) {
8704 var currentIndex
, nextIndex
, i
,
8705 increase
= direction
> 0 ? 1 : -1,
8706 len
= this.items
.length
;
8709 currentIndex
= this.items
.indexOf( item
);
8710 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
8712 // If no item is selected and moving forward, start at the beginning.
8713 // If moving backward, start at the end.
8714 nextIndex
= direction
> 0 ? 0 : len
- 1;
8717 for ( i
= 0; i
< len
; i
++ ) {
8718 item
= this.items
[ nextIndex
];
8719 if ( item
&& !item
.isDisabled() ) {
8722 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
8728 * Handle click events on checkboxes.
8730 * @param {jQuery.Event} e
8732 OO
.ui
.CheckboxMultiselectWidget
.prototype.onClick = function ( e
) {
8733 var $options
, lastClickedIndex
, nowClickedIndex
, i
, direction
, wasSelected
, items
,
8734 $lastClicked
= this.$lastClicked
,
8735 $nowClicked
= $( e
.target
).closest( '.oo-ui-checkboxMultioptionWidget' )
8736 .not( '.oo-ui-widget-disabled' );
8738 // Allow selecting multiple options at once by Shift-clicking them
8739 if ( $lastClicked
&& $nowClicked
.length
&& e
.shiftKey
) {
8740 $options
= this.$group
.find( '.oo-ui-checkboxMultioptionWidget' );
8741 lastClickedIndex
= $options
.index( $lastClicked
);
8742 nowClickedIndex
= $options
.index( $nowClicked
);
8743 // If it's the same item, either the user is being silly, or it's a fake event generated by the
8744 // browser. In either case we don't need custom handling.
8745 if ( nowClickedIndex
!== lastClickedIndex
) {
8747 wasSelected
= items
[ nowClickedIndex
].isSelected();
8748 direction
= nowClickedIndex
> lastClickedIndex
? 1 : -1;
8750 // This depends on the DOM order of the items and the order of the .items array being the same.
8751 for ( i
= lastClickedIndex
; i
!== nowClickedIndex
; i
+= direction
) {
8752 if ( !items
[ i
].isDisabled() ) {
8753 items
[ i
].setSelected( !wasSelected
);
8756 // For the now-clicked element, use immediate timeout to allow the browser to do its own
8757 // handling first, then set our value. The order in which events happen is different for
8758 // clicks on the <input> and on the <label> and there are additional fake clicks fired for
8759 // non-click actions that change the checkboxes.
8761 setTimeout( function () {
8762 if ( !items
[ nowClickedIndex
].isDisabled() ) {
8763 items
[ nowClickedIndex
].setSelected( !wasSelected
);
8769 if ( $nowClicked
.length
) {
8770 this.$lastClicked
= $nowClicked
;
8778 * @return {OO.ui.Widget} The widget, for chaining
8780 OO
.ui
.CheckboxMultiselectWidget
.prototype.focus = function () {
8782 if ( !this.isDisabled() ) {
8783 item
= this.getRelativeFocusableItem( null, 1 );
8794 OO
.ui
.CheckboxMultiselectWidget
.prototype.simulateLabelClick = function () {
8799 * Progress bars visually display the status of an operation, such as a download,
8800 * and can be either determinate or indeterminate:
8802 * - **determinate** process bars show the percent of an operation that is complete.
8804 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
8805 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
8806 * not use percentages.
8808 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
8811 * // Examples of determinate and indeterminate progress bars.
8812 * var progressBar1 = new OO.ui.ProgressBarWidget( {
8815 * var progressBar2 = new OO.ui.ProgressBarWidget();
8817 * // Create a FieldsetLayout to layout progress bars.
8818 * var fieldset = new OO.ui.FieldsetLayout;
8819 * fieldset.addItems( [
8820 * new OO.ui.FieldLayout( progressBar1, {
8821 * label: 'Determinate',
8824 * new OO.ui.FieldLayout( progressBar2, {
8825 * label: 'Indeterminate',
8829 * $( document.body ).append( fieldset.$element );
8832 * @extends OO.ui.Widget
8835 * @param {Object} [config] Configuration options
8836 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
8837 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
8838 * By default, the progress bar is indeterminate.
8840 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
8841 // Configuration initialization
8842 config
= config
|| {};
8844 // Parent constructor
8845 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
8848 this.$bar
= $( '<div>' );
8849 this.progress
= null;
8852 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
8853 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
8856 role
: 'progressbar',
8858 'aria-valuemax': 100
8860 .addClass( 'oo-ui-progressBarWidget' )
8861 .append( this.$bar
);
8866 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
8868 /* Static Properties */
8874 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
8879 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
8881 * @return {number|boolean} Progress percent
8883 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
8884 return this.progress
;
8888 * Set the percent of the process completed or `false` for an indeterminate process.
8890 * @param {number|boolean} progress Progress percent or `false` for indeterminate
8892 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
8893 this.progress
= progress
;
8895 if ( progress
!== false ) {
8896 this.$bar
.css( 'width', this.progress
+ '%' );
8897 this.$element
.attr( 'aria-valuenow', this.progress
);
8899 this.$bar
.css( 'width', '' );
8900 this.$element
.removeAttr( 'aria-valuenow' );
8902 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress
=== false );
8906 * InputWidget is the base class for all input widgets, which
8907 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
8908 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
8909 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
8911 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
8915 * @extends OO.ui.Widget
8916 * @mixins OO.ui.mixin.FlaggedElement
8917 * @mixins OO.ui.mixin.TabIndexedElement
8918 * @mixins OO.ui.mixin.TitledElement
8919 * @mixins OO.ui.mixin.AccessKeyedElement
8922 * @param {Object} [config] Configuration options
8923 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
8924 * @cfg {string} [value=''] The value of the input.
8925 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
8926 * @cfg {string} [inputId] The value of the input’s HTML `id` attribute.
8927 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
8928 * before it is accepted.
8930 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
8931 // Configuration initialization
8932 config
= config
|| {};
8934 // Parent constructor
8935 OO
.ui
.InputWidget
.parent
.call( this, config
);
8938 // See #reusePreInfuseDOM about config.$input
8939 this.$input
= config
.$input
|| this.getInputElement( config
);
8941 this.inputFilter
= config
.inputFilter
;
8943 // Mixin constructors
8944 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
8945 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
8946 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
8947 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$input
} ) );
8950 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
8954 .addClass( 'oo-ui-inputWidget-input' )
8955 .attr( 'name', config
.name
)
8956 .prop( 'disabled', this.isDisabled() );
8958 .addClass( 'oo-ui-inputWidget' )
8959 .append( this.$input
);
8960 this.setValue( config
.value
);
8962 this.setDir( config
.dir
);
8964 if ( config
.inputId
!== undefined ) {
8965 this.setInputId( config
.inputId
);
8971 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
8972 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
8973 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
8974 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
8975 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
8977 /* Static Methods */
8982 OO
.ui
.InputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
8983 config
= OO
.ui
.InputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
8984 // Reusing `$input` lets browsers preserve inputted values across page reloads, see T114134.
8985 config
.$input
= $( node
).find( '.oo-ui-inputWidget-input' );
8992 OO
.ui
.InputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8993 var state
= OO
.ui
.InputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8994 if ( config
.$input
&& config
.$input
.length
) {
8995 state
.value
= config
.$input
.val();
8996 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
8997 state
.focus
= config
.$input
.is( ':focus' );
9007 * A change event is emitted when the value of the input changes.
9009 * @param {string} value
9015 * Get input element.
9017 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
9018 * different circumstances. The element must have a `value` property (like form elements).
9021 * @param {Object} config Configuration options
9022 * @return {jQuery} Input element
9024 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
9025 return $( '<input>' );
9029 * Handle potentially value-changing events.
9032 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
9034 OO
.ui
.InputWidget
.prototype.onEdit = function () {
9036 if ( !this.isDisabled() ) {
9037 // Allow the stack to clear so the value will be updated
9038 setTimeout( function () {
9039 widget
.setValue( widget
.$input
.val() );
9045 * Get the value of the input.
9047 * @return {string} Input value
9049 OO
.ui
.InputWidget
.prototype.getValue = function () {
9050 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
9051 // it, and we won't know unless they're kind enough to trigger a 'change' event.
9052 var value
= this.$input
.val();
9053 if ( this.value
!== value
) {
9054 this.setValue( value
);
9060 * Set the directionality of the input.
9062 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
9064 * @return {OO.ui.Widget} The widget, for chaining
9066 OO
.ui
.InputWidget
.prototype.setDir = function ( dir
) {
9067 this.$input
.prop( 'dir', dir
);
9072 * Set the value of the input.
9074 * @param {string} value New value
9077 * @return {OO.ui.Widget} The widget, for chaining
9079 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
9080 value
= this.cleanUpValue( value
);
9081 // Update the DOM if it has changed. Note that with cleanUpValue, it
9082 // is possible for the DOM value to change without this.value changing.
9083 if ( this.$input
.val() !== value
) {
9084 this.$input
.val( value
);
9086 if ( this.value
!== value
) {
9088 this.emit( 'change', this.value
);
9090 // The first time that the value is set (probably while constructing the widget),
9091 // remember it in defaultValue. This property can be later used to check whether
9092 // the value of the input has been changed since it was created.
9093 if ( this.defaultValue
=== undefined ) {
9094 this.defaultValue
= this.value
;
9095 this.$input
[ 0 ].defaultValue
= this.defaultValue
;
9101 * Clean up incoming value.
9103 * Ensures value is a string, and converts undefined and null to empty string.
9106 * @param {string} value Original value
9107 * @return {string} Cleaned up value
9109 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
9110 if ( value
=== undefined || value
=== null ) {
9112 } else if ( this.inputFilter
) {
9113 return this.inputFilter( String( value
) );
9115 return String( value
);
9122 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
9123 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9124 if ( this.$input
) {
9125 this.$input
.prop( 'disabled', this.isDisabled() );
9131 * Set the 'id' attribute of the `<input>` element.
9133 * @param {string} id
9135 * @return {OO.ui.Widget} The widget, for chaining
9137 OO
.ui
.InputWidget
.prototype.setInputId = function ( id
) {
9138 this.$input
.attr( 'id', id
);
9145 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
9146 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
9147 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
9148 this.setValue( state
.value
);
9150 if ( state
.focus
) {
9156 * Data widget intended for creating `<input type="hidden">` inputs.
9159 * @extends OO.ui.Widget
9162 * @param {Object} [config] Configuration options
9163 * @cfg {string} [value=''] The value of the input.
9164 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
9166 OO
.ui
.HiddenInputWidget
= function OoUiHiddenInputWidget( config
) {
9167 // Configuration initialization
9168 config
= $.extend( { value
: '', name
: '' }, config
);
9170 // Parent constructor
9171 OO
.ui
.HiddenInputWidget
.parent
.call( this, config
);
9174 this.$element
.attr( {
9176 value
: config
.value
,
9179 this.$element
.removeAttr( 'aria-disabled' );
9184 OO
.inheritClass( OO
.ui
.HiddenInputWidget
, OO
.ui
.Widget
);
9186 /* Static Properties */
9192 OO
.ui
.HiddenInputWidget
.static.tagName
= 'input';
9195 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
9196 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
9197 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
9198 * HTML `<button>` (the default) or an HTML `<input>` tags. See the
9199 * [OOUI documentation on MediaWiki] [1] for more information.
9202 * // A ButtonInputWidget rendered as an HTML button, the default.
9203 * var button = new OO.ui.ButtonInputWidget( {
9204 * label: 'Input button',
9208 * $( document.body ).append( button.$element );
9210 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#Button_inputs
9213 * @extends OO.ui.InputWidget
9214 * @mixins OO.ui.mixin.ButtonElement
9215 * @mixins OO.ui.mixin.IconElement
9216 * @mixins OO.ui.mixin.IndicatorElement
9217 * @mixins OO.ui.mixin.LabelElement
9220 * @param {Object} [config] Configuration options
9221 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
9222 * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
9223 * Widgets configured to be an `<input>` do not support {@link #icon icons} and {@link #indicator indicators},
9224 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
9225 * be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
9227 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
9228 // Configuration initialization
9229 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
9231 // See InputWidget#reusePreInfuseDOM about config.$input
9232 if ( config
.$input
) {
9233 config
.$input
.empty();
9236 // Properties (must be set before parent constructor, which calls #setValue)
9237 this.useInputTag
= config
.useInputTag
;
9239 // Parent constructor
9240 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
9242 // Mixin constructors
9243 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
9244 OO
.ui
.mixin
.IconElement
.call( this, config
);
9245 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
9246 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9249 if ( !config
.useInputTag
) {
9250 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
9252 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
9257 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
9258 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
9259 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
9260 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
9261 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
9263 /* Static Properties */
9269 OO
.ui
.ButtonInputWidget
.static.tagName
= 'span';
9277 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
9279 type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ? config
.type
: 'button';
9280 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
9286 * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
9288 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
9289 * text, or `null` for no label
9291 * @return {OO.ui.Widget} The widget, for chaining
9293 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
9294 if ( typeof label
=== 'function' ) {
9295 label
= OO
.ui
.resolveMsg( label
);
9298 if ( this.useInputTag
) {
9299 // Discard non-plaintext labels
9300 if ( typeof label
!== 'string' ) {
9304 this.$input
.val( label
);
9307 return OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
9311 * Set the value of the input.
9313 * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
9314 * they do not support {@link #value values}.
9316 * @param {string} value New value
9318 * @return {OO.ui.Widget} The widget, for chaining
9320 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
9321 if ( !this.useInputTag
) {
9322 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
9330 OO
.ui
.ButtonInputWidget
.prototype.getInputId = function () {
9331 // Disable generating `<label>` elements for buttons. One would very rarely need additional label
9332 // for a button, and it's already a big clickable target, and it causes unexpected rendering.
9337 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
9338 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
9339 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
9340 * alignment. For more information, please see the [OOUI documentation on MediaWiki][1].
9342 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9345 * // An example of selected, unselected, and disabled checkbox inputs.
9346 * var checkbox1 = new OO.ui.CheckboxInputWidget( {
9350 * checkbox2 = new OO.ui.CheckboxInputWidget( {
9353 * checkbox3 = new OO.ui.CheckboxInputWidget( {
9357 * // Create a fieldset layout with fields for each checkbox.
9358 * fieldset = new OO.ui.FieldsetLayout( {
9359 * label: 'Checkboxes'
9361 * fieldset.addItems( [
9362 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
9363 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
9364 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
9366 * $( document.body ).append( fieldset.$element );
9368 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9371 * @extends OO.ui.InputWidget
9374 * @param {Object} [config] Configuration options
9375 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
9377 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
9378 // Configuration initialization
9379 config
= config
|| {};
9381 // Parent constructor
9382 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
9385 this.checkIcon
= new OO
.ui
.IconWidget( {
9387 classes
: [ 'oo-ui-checkboxInputWidget-checkIcon' ]
9392 .addClass( 'oo-ui-checkboxInputWidget' )
9393 // Required for pretty styling in WikimediaUI theme
9394 .append( this.checkIcon
.$element
);
9395 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
9400 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
9402 /* Static Properties */
9408 OO
.ui
.CheckboxInputWidget
.static.tagName
= 'span';
9410 /* Static Methods */
9415 OO
.ui
.CheckboxInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9416 var state
= OO
.ui
.CheckboxInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9417 state
.checked
= config
.$input
.prop( 'checked' );
9427 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
9428 return $( '<input>' ).attr( 'type', 'checkbox' );
9434 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
9436 if ( !this.isDisabled() ) {
9437 // Allow the stack to clear so the value will be updated
9438 setTimeout( function () {
9439 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
9445 * Set selection state of this checkbox.
9447 * @param {boolean} state `true` for selected
9449 * @return {OO.ui.Widget} The widget, for chaining
9451 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
9453 if ( this.selected
!== state
) {
9454 this.selected
= state
;
9455 this.$input
.prop( 'checked', this.selected
);
9456 this.emit( 'change', this.selected
);
9458 // The first time that the selection state is set (probably while constructing the widget),
9459 // remember it in defaultSelected. This property can be later used to check whether
9460 // the selection state of the input has been changed since it was created.
9461 if ( this.defaultSelected
=== undefined ) {
9462 this.defaultSelected
= this.selected
;
9463 this.$input
[ 0 ].defaultChecked
= this.defaultSelected
;
9469 * Check if this checkbox is selected.
9471 * @return {boolean} Checkbox is selected
9473 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
9474 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
9475 // it, and we won't know unless they're kind enough to trigger a 'change' event.
9476 var selected
= this.$input
.prop( 'checked' );
9477 if ( this.selected
!== selected
) {
9478 this.setSelected( selected
);
9480 return this.selected
;
9486 OO
.ui
.CheckboxInputWidget
.prototype.simulateLabelClick = function () {
9487 if ( !this.isDisabled() ) {
9488 this.$handle
.trigger( 'click' );
9496 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
9497 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
9498 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
9499 this.setSelected( state
.checked
);
9504 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
9505 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
9506 * of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9507 * more information about input widgets.
9509 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
9510 * are no options. If no `value` configuration option is provided, the first option is selected.
9511 * If you need a state representing no value (no option being selected), use a DropdownWidget.
9513 * This and OO.ui.RadioSelectInputWidget support similar configuration options.
9516 * // A DropdownInputWidget with three options.
9517 * var dropdownInput = new OO.ui.DropdownInputWidget( {
9519 * { data: 'a', label: 'First' },
9520 * { data: 'b', label: 'Second', disabled: true },
9521 * { optgroup: 'Group label' },
9522 * { data: 'c', label: 'First sub-item)' }
9525 * $( document.body ).append( dropdownInput.$element );
9527 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9530 * @extends OO.ui.InputWidget
9533 * @param {Object} [config] Configuration options
9534 * @cfg {Object[]} [options=[]] Array of menu options in the format described above.
9535 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
9536 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
9537 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
9538 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
9539 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
9541 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
9542 // Configuration initialization
9543 config
= config
|| {};
9545 // Properties (must be done before parent constructor which calls #setDisabled)
9546 this.dropdownWidget
= new OO
.ui
.DropdownWidget( $.extend(
9548 $overlay
: config
.$overlay
9552 // Set up the options before parent constructor, which uses them to validate config.value.
9553 // Use this instead of setOptions() because this.$input is not set up yet.
9554 this.setOptionsData( config
.options
|| [] );
9556 // Parent constructor
9557 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
9560 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
9564 .addClass( 'oo-ui-dropdownInputWidget' )
9565 .append( this.dropdownWidget
.$element
);
9566 this.setTabIndexedElement( this.dropdownWidget
.$tabIndexed
);
9567 this.setTitledElement( this.dropdownWidget
.$handle
);
9572 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
9580 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
9581 return $( '<select>' );
9585 * Handles menu select events.
9588 * @param {OO.ui.MenuOptionWidget|null} item Selected menu item
9590 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
9591 this.setValue( item
? item
.getData() : '' );
9597 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
9599 value
= this.cleanUpValue( value
);
9600 // Only allow setting values that are actually present in the dropdown
9601 selected
= this.dropdownWidget
.getMenu().findItemFromData( value
) ||
9602 this.dropdownWidget
.getMenu().findFirstSelectableItem();
9603 this.dropdownWidget
.getMenu().selectItem( selected
);
9604 value
= selected
? selected
.getData() : '';
9605 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
9606 if ( this.optionsDirty
) {
9607 // We reached this from the constructor or from #setOptions.
9608 // We have to update the <select> element.
9609 this.updateOptionsInterface();
9617 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
9618 this.dropdownWidget
.setDisabled( state
);
9619 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9624 * Set the options available for this input.
9626 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9628 * @return {OO.ui.Widget} The widget, for chaining
9630 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
9631 var value
= this.getValue();
9633 this.setOptionsData( options
);
9635 // Re-set the value to update the visible interface (DropdownWidget and <select>).
9636 // In case the previous value is no longer an available option, select the first valid one.
9637 this.setValue( value
);
9643 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
9645 * This method may be called before the parent constructor, so various properties may not be
9648 * @param {Object[]} options Array of menu options (see #constructor for details).
9651 OO
.ui
.DropdownInputWidget
.prototype.setOptionsData = function ( options
) {
9652 var optionWidgets
, optIndex
, opt
, previousOptgroup
, optionWidget
, optValue
,
9655 this.optionsDirty
= true;
9657 // Go through all the supplied option configs and create either
9658 // MenuSectionOption or MenuOption widgets from each.
9660 for ( optIndex
= 0; optIndex
< options
.length
; optIndex
++ ) {
9661 opt
= options
[ optIndex
];
9663 if ( opt
.optgroup
!== undefined ) {
9664 // Create a <optgroup> menu item.
9665 optionWidget
= widget
.createMenuSectionOptionWidget( opt
.optgroup
);
9666 previousOptgroup
= optionWidget
;
9669 // Create a normal <option> menu item.
9670 optValue
= widget
.cleanUpValue( opt
.data
);
9671 optionWidget
= widget
.createMenuOptionWidget(
9673 opt
.label
!== undefined ? opt
.label
: optValue
9677 // Disable the menu option if it is itself disabled or if its parent optgroup is disabled.
9678 if ( opt
.disabled
!== undefined ||
9679 previousOptgroup
instanceof OO
.ui
.MenuSectionOptionWidget
&& previousOptgroup
.isDisabled() ) {
9680 optionWidget
.setDisabled( true );
9683 optionWidgets
.push( optionWidget
);
9686 this.dropdownWidget
.getMenu().clearItems().addItems( optionWidgets
);
9690 * Create a menu option widget.
9693 * @param {string} data Item data
9694 * @param {string} label Item label
9695 * @return {OO.ui.MenuOptionWidget} Option widget
9697 OO
.ui
.DropdownInputWidget
.prototype.createMenuOptionWidget = function ( data
, label
) {
9698 return new OO
.ui
.MenuOptionWidget( {
9705 * Create a menu section option widget.
9708 * @param {string} label Section item label
9709 * @return {OO.ui.MenuSectionOptionWidget} Menu section option widget
9711 OO
.ui
.DropdownInputWidget
.prototype.createMenuSectionOptionWidget = function ( label
) {
9712 return new OO
.ui
.MenuSectionOptionWidget( {
9718 * Update the user-visible interface to match the internal list of options and value.
9720 * This method must only be called after the parent constructor.
9724 OO
.ui
.DropdownInputWidget
.prototype.updateOptionsInterface = function () {
9726 $optionsContainer
= this.$input
,
9727 defaultValue
= this.defaultValue
,
9730 this.$input
.empty();
9732 this.dropdownWidget
.getMenu().getItems().forEach( function ( optionWidget
) {
9735 if ( !( optionWidget
instanceof OO
.ui
.MenuSectionOptionWidget
) ) {
9736 $optionNode
= $( '<option>' )
9737 .attr( 'value', optionWidget
.getData() )
9738 .text( optionWidget
.getLabel() );
9740 // Remember original selection state. This property can be later used to check whether
9741 // the selection state of the input has been changed since it was created.
9742 $optionNode
[ 0 ].defaultSelected
= ( optionWidget
.getData() === defaultValue
);
9744 $optionsContainer
.append( $optionNode
);
9746 $optionNode
= $( '<optgroup>' )
9747 .attr( 'label', optionWidget
.getLabel() );
9748 widget
.$input
.append( $optionNode
);
9749 $optionsContainer
= $optionNode
;
9752 // Disable the option or optgroup if required.
9753 if ( optionWidget
.isDisabled() ) {
9754 $optionNode
.prop( 'disabled', true );
9758 this.optionsDirty
= false;
9764 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
9765 this.dropdownWidget
.focus();
9772 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
9773 this.dropdownWidget
.blur();
9778 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
9779 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
9780 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
9781 * please see the [OOUI documentation on MediaWiki][1].
9783 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9786 * // An example of selected, unselected, and disabled radio inputs
9787 * var radio1 = new OO.ui.RadioInputWidget( {
9791 * var radio2 = new OO.ui.RadioInputWidget( {
9794 * var radio3 = new OO.ui.RadioInputWidget( {
9798 * // Create a fieldset layout with fields for each radio button.
9799 * var fieldset = new OO.ui.FieldsetLayout( {
9800 * label: 'Radio inputs'
9802 * fieldset.addItems( [
9803 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
9804 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
9805 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
9807 * $( document.body ).append( fieldset.$element );
9809 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9812 * @extends OO.ui.InputWidget
9815 * @param {Object} [config] Configuration options
9816 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
9818 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
9819 // Configuration initialization
9820 config
= config
|| {};
9822 // Parent constructor
9823 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
9827 .addClass( 'oo-ui-radioInputWidget' )
9828 // Required for pretty styling in WikimediaUI theme
9829 .append( $( '<span>' ) );
9830 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
9835 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
9837 /* Static Properties */
9843 OO
.ui
.RadioInputWidget
.static.tagName
= 'span';
9845 /* Static Methods */
9850 OO
.ui
.RadioInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9851 var state
= OO
.ui
.RadioInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9852 state
.checked
= config
.$input
.prop( 'checked' );
9862 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
9863 return $( '<input>' ).attr( 'type', 'radio' );
9869 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
9870 // RadioInputWidget doesn't track its state.
9874 * Set selection state of this radio button.
9876 * @param {boolean} state `true` for selected
9878 * @return {OO.ui.Widget} The widget, for chaining
9880 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
9881 // RadioInputWidget doesn't track its state.
9882 this.$input
.prop( 'checked', state
);
9883 // The first time that the selection state is set (probably while constructing the widget),
9884 // remember it in defaultSelected. This property can be later used to check whether
9885 // the selection state of the input has been changed since it was created.
9886 if ( this.defaultSelected
=== undefined ) {
9887 this.defaultSelected
= state
;
9888 this.$input
[ 0 ].defaultChecked
= this.defaultSelected
;
9894 * Check if this radio button is selected.
9896 * @return {boolean} Radio is selected
9898 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
9899 return this.$input
.prop( 'checked' );
9905 OO
.ui
.RadioInputWidget
.prototype.simulateLabelClick = function () {
9906 if ( !this.isDisabled() ) {
9907 this.$input
.trigger( 'click' );
9915 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
9916 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
9917 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
9918 this.setSelected( state
.checked
);
9923 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
9924 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
9925 * of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9926 * more information about input widgets.
9928 * This and OO.ui.DropdownInputWidget support similar configuration options.
9931 * // A RadioSelectInputWidget with three options
9932 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
9934 * { data: 'a', label: 'First' },
9935 * { data: 'b', label: 'Second'},
9936 * { data: 'c', label: 'Third' }
9939 * $( document.body ).append( radioSelectInput.$element );
9941 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9944 * @extends OO.ui.InputWidget
9947 * @param {Object} [config] Configuration options
9948 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9950 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
9951 // Configuration initialization
9952 config
= config
|| {};
9954 // Properties (must be done before parent constructor which calls #setDisabled)
9955 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
9956 // Set up the options before parent constructor, which uses them to validate config.value.
9957 // Use this instead of setOptions() because this.$input is not set up yet
9958 this.setOptionsData( config
.options
|| [] );
9960 // Parent constructor
9961 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
9964 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
9968 .addClass( 'oo-ui-radioSelectInputWidget' )
9969 .append( this.radioSelectWidget
.$element
);
9970 this.setTabIndexedElement( this.radioSelectWidget
.$tabIndexed
);
9975 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
9977 /* Static Methods */
9982 OO
.ui
.RadioSelectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9983 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9984 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
9991 OO
.ui
.RadioSelectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
9992 config
= OO
.ui
.RadioSelectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
9993 // Cannot reuse the `<input type=radio>` set
9994 delete config
.$input
;
10004 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
10005 // Use this instead of <input type="hidden">, because hidden inputs do not have separate
10006 // 'value' and 'defaultValue' properties, and InputWidget wants to handle 'defaultValue'.
10007 return $( '<input>' ).addClass( 'oo-ui-element-hidden' );
10011 * Handles menu select events.
10014 * @param {OO.ui.RadioOptionWidget} item Selected menu item
10016 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
10017 this.setValue( item
.getData() );
10023 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
10025 value
= this.cleanUpValue( value
);
10026 // Only allow setting values that are actually present in the dropdown
10027 selected
= this.radioSelectWidget
.findItemFromData( value
) ||
10028 this.radioSelectWidget
.findFirstSelectableItem();
10029 this.radioSelectWidget
.selectItem( selected
);
10030 value
= selected
? selected
.getData() : '';
10031 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
10038 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
10039 this.radioSelectWidget
.setDisabled( state
);
10040 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
10045 * Set the options available for this input.
10047 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10049 * @return {OO.ui.Widget} The widget, for chaining
10051 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
10052 var value
= this.getValue();
10054 this.setOptionsData( options
);
10056 // Re-set the value to update the visible interface (RadioSelectWidget).
10057 // In case the previous value is no longer an available option, select the first valid one.
10058 this.setValue( value
);
10064 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
10066 * This method may be called before the parent constructor, so various properties may not be
10069 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10072 OO
.ui
.RadioSelectInputWidget
.prototype.setOptionsData = function ( options
) {
10075 this.radioSelectWidget
10077 .addItems( options
.map( function ( opt
) {
10078 var optValue
= widget
.cleanUpValue( opt
.data
);
10079 return new OO
.ui
.RadioOptionWidget( {
10081 label
: opt
.label
!== undefined ? opt
.label
: optValue
10089 OO
.ui
.RadioSelectInputWidget
.prototype.focus = function () {
10090 this.radioSelectWidget
.focus();
10097 OO
.ui
.RadioSelectInputWidget
.prototype.blur = function () {
10098 this.radioSelectWidget
.blur();
10103 * CheckboxMultiselectInputWidget is a
10104 * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
10105 * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
10106 * HTML `<input type=checkbox>` tags. Please see the [OOUI documentation on MediaWiki][1] for
10107 * more information about input widgets.
10110 * // A CheckboxMultiselectInputWidget with three options.
10111 * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
10113 * { data: 'a', label: 'First' },
10114 * { data: 'b', label: 'Second' },
10115 * { data: 'c', label: 'Third' }
10118 * $( document.body ).append( multiselectInput.$element );
10120 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
10123 * @extends OO.ui.InputWidget
10126 * @param {Object} [config] Configuration options
10127 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: …, disabled: … }`
10129 OO
.ui
.CheckboxMultiselectInputWidget
= function OoUiCheckboxMultiselectInputWidget( config
) {
10130 // Configuration initialization
10131 config
= config
|| {};
10133 // Properties (must be done before parent constructor which calls #setDisabled)
10134 this.checkboxMultiselectWidget
= new OO
.ui
.CheckboxMultiselectWidget();
10135 // Must be set before the #setOptionsData call below
10136 this.inputName
= config
.name
;
10137 // Set up the options before parent constructor, which uses them to validate config.value.
10138 // Use this instead of setOptions() because this.$input is not set up yet
10139 this.setOptionsData( config
.options
|| [] );
10141 // Parent constructor
10142 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.call( this, config
);
10145 this.checkboxMultiselectWidget
.connect( this, { select
: 'onCheckboxesSelect' } );
10149 .addClass( 'oo-ui-checkboxMultiselectInputWidget' )
10150 .append( this.checkboxMultiselectWidget
.$element
);
10151 // We don't use this.$input, but rather the CheckboxInputWidgets inside each option
10152 this.$input
.detach();
10157 OO
.inheritClass( OO
.ui
.CheckboxMultiselectInputWidget
, OO
.ui
.InputWidget
);
10159 /* Static Methods */
10164 OO
.ui
.CheckboxMultiselectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
10165 var state
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
10166 state
.value
= $( node
).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
10167 .toArray().map( function ( el
) { return el
.value
; } );
10174 OO
.ui
.CheckboxMultiselectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
10175 config
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
10176 // Cannot reuse the `<input type=checkbox>` set
10177 delete config
.$input
;
10187 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getInputElement = function () {
10189 return $( '<unused>' );
10193 * Handles CheckboxMultiselectWidget select events.
10197 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.onCheckboxesSelect = function () {
10198 this.setValue( this.checkboxMultiselectWidget
.findSelectedItemsData() );
10204 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getValue = function () {
10205 var value
= this.$element
.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
10206 .toArray().map( function ( el
) { return el
.value
; } );
10207 if ( this.value
!== value
) {
10208 this.setValue( value
);
10216 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setValue = function ( value
) {
10217 value
= this.cleanUpValue( value
);
10218 this.checkboxMultiselectWidget
.selectItemsByData( value
);
10219 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setValue
.call( this, value
);
10220 if ( this.optionsDirty
) {
10221 // We reached this from the constructor or from #setOptions.
10222 // We have to update the <select> element.
10223 this.updateOptionsInterface();
10229 * Clean up incoming value.
10231 * @param {string[]} value Original value
10232 * @return {string[]} Cleaned up value
10234 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.cleanUpValue = function ( value
) {
10235 var i
, singleValue
,
10237 if ( !Array
.isArray( value
) ) {
10240 for ( i
= 0; i
< value
.length
; i
++ ) {
10242 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( this, value
[ i
] );
10243 // Remove options that we don't have here
10244 if ( !this.checkboxMultiselectWidget
.findItemFromData( singleValue
) ) {
10247 cleanValue
.push( singleValue
);
10255 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setDisabled = function ( state
) {
10256 this.checkboxMultiselectWidget
.setDisabled( state
);
10257 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
10262 * Set the options available for this input.
10264 * @param {Object[]} options Array of menu options in the format `{ data: …, label: …, disabled: … }`
10266 * @return {OO.ui.Widget} The widget, for chaining
10268 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setOptions = function ( options
) {
10269 var value
= this.getValue();
10271 this.setOptionsData( options
);
10273 // Re-set the value to update the visible interface (CheckboxMultiselectWidget).
10274 // This will also get rid of any stale options that we just removed.
10275 this.setValue( value
);
10281 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
10283 * This method may be called before the parent constructor, so various properties may not be
10286 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10289 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setOptionsData = function ( options
) {
10292 this.optionsDirty
= true;
10294 this.checkboxMultiselectWidget
10296 .addItems( options
.map( function ( opt
) {
10297 var optValue
, item
, optDisabled
;
10299 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( widget
, opt
.data
);
10300 optDisabled
= opt
.disabled
!== undefined ? opt
.disabled
: false;
10301 item
= new OO
.ui
.CheckboxMultioptionWidget( {
10303 label
: opt
.label
!== undefined ? opt
.label
: optValue
,
10304 disabled
: optDisabled
10306 // Set the 'name' and 'value' for form submission
10307 item
.checkbox
.$input
.attr( 'name', widget
.inputName
);
10308 item
.checkbox
.setValue( optValue
);
10314 * Update the user-visible interface to match the internal list of options and value.
10316 * This method must only be called after the parent constructor.
10320 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.updateOptionsInterface = function () {
10321 var defaultValue
= this.defaultValue
;
10323 this.checkboxMultiselectWidget
.getItems().forEach( function ( item
) {
10324 // Remember original selection state. This property can be later used to check whether
10325 // the selection state of the input has been changed since it was created.
10326 var isDefault
= defaultValue
.indexOf( item
.getData() ) !== -1;
10327 item
.checkbox
.defaultSelected
= isDefault
;
10328 item
.checkbox
.$input
[ 0 ].defaultChecked
= isDefault
;
10331 this.optionsDirty
= false;
10337 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.focus = function () {
10338 this.checkboxMultiselectWidget
.focus();
10343 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
10344 * size of the field as well as its presentation. In addition, these widgets can be configured
10345 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
10346 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
10347 * which modifies incoming values rather than validating them.
10348 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
10350 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
10353 * // A TextInputWidget.
10354 * var textInput = new OO.ui.TextInputWidget( {
10355 * value: 'Text input'
10357 * $( document.body ).append( textInput.$element );
10359 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
10362 * @extends OO.ui.InputWidget
10363 * @mixins OO.ui.mixin.IconElement
10364 * @mixins OO.ui.mixin.IndicatorElement
10365 * @mixins OO.ui.mixin.PendingElement
10366 * @mixins OO.ui.mixin.LabelElement
10369 * @param {Object} [config] Configuration options
10370 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password'
10371 * 'email', 'url' or 'number'.
10372 * @cfg {string} [placeholder] Placeholder text
10373 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
10374 * instruct the browser to focus this widget.
10375 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
10376 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
10378 * For unfortunate historical reasons, this counts the number of UTF-16 code units rather than
10379 * Unicode codepoints, which means that codepoints outside the Basic Multilingual Plane (e.g.
10380 * many emojis) count as 2 characters each.
10381 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
10382 * the value or placeholder text: `'before'` or `'after'`
10383 * @cfg {boolean} [required=false] Mark the field as required with `true`. Implies `indicator: 'required'`.
10384 * Note that `false` & setting `indicator: 'required' will result in no indicator shown.
10385 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
10386 * @cfg {boolean} [spellcheck] Should the browser support spellcheck for this field (`undefined` means
10387 * leaving it up to the browser).
10388 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
10389 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
10390 * (the value must contain only numbers); when RegExp, a regular expression that must match the
10391 * value for it to be considered valid; when Function, a function receiving the value as parameter
10392 * that must return true, or promise resolving to true, for it to be considered valid.
10394 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
10395 // Configuration initialization
10396 config
= $.extend( {
10398 labelPosition
: 'after'
10401 // Parent constructor
10402 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
10404 // Mixin constructors
10405 OO
.ui
.mixin
.IconElement
.call( this, config
);
10406 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
10407 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
10408 OO
.ui
.mixin
.LabelElement
.call( this, config
);
10411 this.type
= this.getSaneType( config
);
10412 this.readOnly
= false;
10413 this.required
= false;
10414 this.validate
= null;
10415 this.scrollWidth
= null;
10417 this.setValidation( config
.validate
);
10418 this.setLabelPosition( config
.labelPosition
);
10422 keypress
: this.onKeyPress
.bind( this ),
10423 blur
: this.onBlur
.bind( this ),
10424 focus
: this.onFocus
.bind( this )
10426 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
10427 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
10428 this.on( 'labelChange', this.updatePosition
.bind( this ) );
10429 this.on( 'change', OO
.ui
.debounce( this.onDebouncedChange
.bind( this ), 250 ) );
10433 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
10434 .append( this.$icon
, this.$indicator
);
10435 this.setReadOnly( !!config
.readOnly
);
10436 this.setRequired( !!config
.required
);
10437 if ( config
.placeholder
!== undefined ) {
10438 this.$input
.attr( 'placeholder', config
.placeholder
);
10440 if ( config
.maxLength
!== undefined ) {
10441 this.$input
.attr( 'maxlength', config
.maxLength
);
10443 if ( config
.autofocus
) {
10444 this.$input
.attr( 'autofocus', 'autofocus' );
10446 if ( config
.autocomplete
=== false ) {
10447 this.$input
.attr( 'autocomplete', 'off' );
10448 // Turning off autocompletion also disables "form caching" when the user navigates to a
10449 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
10451 beforeunload: function () {
10452 this.$input
.removeAttr( 'autocomplete' );
10454 pageshow: function () {
10455 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
10456 // whole page... it shouldn't hurt, though.
10457 this.$input
.attr( 'autocomplete', 'off' );
10461 if ( config
.spellcheck
!== undefined ) {
10462 this.$input
.attr( 'spellcheck', config
.spellcheck
? 'true' : 'false' );
10464 if ( this.label
) {
10465 this.isWaitingToBeAttached
= true;
10466 this.installParentChangeDetector();
10472 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
10473 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
10474 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
10475 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
10476 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
10478 /* Static Properties */
10480 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
10488 * An `enter` event is emitted when the user presses 'enter' inside the text box.
10496 * Handle icon mouse down events.
10499 * @param {jQuery.Event} e Mouse down event
10500 * @return {undefined/boolean} False to prevent default if event is handled
10502 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
10503 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
10510 * Handle indicator mouse down events.
10513 * @param {jQuery.Event} e Mouse down event
10514 * @return {undefined/boolean} False to prevent default if event is handled
10516 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
10517 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
10524 * Handle key press events.
10527 * @param {jQuery.Event} e Key press event
10528 * @fires enter If enter key is pressed
10530 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
10531 if ( e
.which
=== OO
.ui
.Keys
.ENTER
) {
10532 this.emit( 'enter', e
);
10537 * Handle blur events.
10540 * @param {jQuery.Event} e Blur event
10542 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
10543 this.setValidityFlag();
10547 * Handle focus events.
10550 * @param {jQuery.Event} e Focus event
10552 OO
.ui
.TextInputWidget
.prototype.onFocus = function () {
10553 if ( this.isWaitingToBeAttached
) {
10554 // If we've received focus, then we must be attached to the document, and if
10555 // isWaitingToBeAttached is still true, that means the handler never fired. Fire it now.
10556 this.onElementAttach();
10558 this.setValidityFlag( true );
10562 * Handle element attach events.
10565 * @param {jQuery.Event} e Element attach event
10567 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
10568 this.isWaitingToBeAttached
= false;
10569 // Any previously calculated size is now probably invalid if we reattached elsewhere
10570 this.valCache
= null;
10571 this.positionLabel();
10575 * Handle debounced change events.
10577 * @param {string} value
10580 OO
.ui
.TextInputWidget
.prototype.onDebouncedChange = function () {
10581 this.setValidityFlag();
10585 * Check if the input is {@link #readOnly read-only}.
10587 * @return {boolean}
10589 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
10590 return this.readOnly
;
10594 * Set the {@link #readOnly read-only} state of the input.
10596 * @param {boolean} state Make input read-only
10598 * @return {OO.ui.Widget} The widget, for chaining
10600 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
10601 this.readOnly
= !!state
;
10602 this.$input
.prop( 'readOnly', this.readOnly
);
10607 * Check if the input is {@link #required required}.
10609 * @return {boolean}
10611 OO
.ui
.TextInputWidget
.prototype.isRequired = function () {
10612 return this.required
;
10616 * Set the {@link #required required} state of the input.
10618 * @param {boolean} state Make input required
10620 * @return {OO.ui.Widget} The widget, for chaining
10622 OO
.ui
.TextInputWidget
.prototype.setRequired = function ( state
) {
10623 this.required
= !!state
;
10624 if ( this.required
) {
10626 .prop( 'required', true )
10627 .attr( 'aria-required', 'true' );
10628 if ( this.getIndicator() === null ) {
10629 this.setIndicator( 'required' );
10633 .prop( 'required', false )
10634 .removeAttr( 'aria-required' );
10635 if ( this.getIndicator() === 'required' ) {
10636 this.setIndicator( null );
10643 * Support function for making #onElementAttach work across browsers.
10645 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
10646 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
10648 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
10649 * first time that the element gets attached to the documented.
10651 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
10652 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
10653 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
10656 if ( MutationObserver
) {
10657 // The new way. If only it wasn't so ugly.
10659 if ( this.isElementAttached() ) {
10660 // Widget is attached already, do nothing. This breaks the functionality of this function when
10661 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
10662 // would require observation of the whole document, which would hurt performance of other,
10663 // more important code.
10667 // Find topmost node in the tree
10668 topmostNode
= this.$element
[ 0 ];
10669 while ( topmostNode
.parentNode
) {
10670 topmostNode
= topmostNode
.parentNode
;
10673 // We have no way to detect the $element being attached somewhere without observing the entire
10674 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
10675 // parent node of $element, and instead detect when $element is removed from it (and thus
10676 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
10677 // doesn't get attached, we end up back here and create the parent.
10679 mutationObserver
= new MutationObserver( function ( mutations
) {
10680 var i
, j
, removedNodes
;
10681 for ( i
= 0; i
< mutations
.length
; i
++ ) {
10682 removedNodes
= mutations
[ i
].removedNodes
;
10683 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
10684 if ( removedNodes
[ j
] === topmostNode
) {
10685 setTimeout( onRemove
, 0 );
10692 onRemove = function () {
10693 // If the node was attached somewhere else, report it
10694 if ( widget
.isElementAttached() ) {
10695 widget
.onElementAttach();
10697 mutationObserver
.disconnect();
10698 widget
.installParentChangeDetector();
10701 // Create a fake parent and observe it
10702 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
10703 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
10705 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
10706 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
10707 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
10715 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
10716 if ( this.getSaneType( config
) === 'number' ) {
10717 return $( '<input>' )
10718 .attr( 'step', 'any' )
10719 .attr( 'type', 'number' );
10721 return $( '<input>' ).attr( 'type', this.getSaneType( config
) );
10726 * Get sanitized value for 'type' for given config.
10728 * @param {Object} config Configuration options
10729 * @return {string|null}
10732 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
10733 var allowedTypes
= [
10740 return allowedTypes
.indexOf( config
.type
) !== -1 ? config
.type
: 'text';
10744 * Focus the input and select a specified range within the text.
10746 * @param {number} from Select from offset
10747 * @param {number} [to] Select to offset, defaults to from
10749 * @return {OO.ui.Widget} The widget, for chaining
10751 OO
.ui
.TextInputWidget
.prototype.selectRange = function ( from, to
) {
10752 var isBackwards
, start
, end
,
10753 input
= this.$input
[ 0 ];
10757 isBackwards
= to
< from;
10758 start
= isBackwards
? to
: from;
10759 end
= isBackwards
? from : to
;
10764 input
.setSelectionRange( start
, end
, isBackwards
? 'backward' : 'forward' );
10766 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
10767 // Rather than expensively check if the input is attached every time, just check
10768 // if it was the cause of an error being thrown. If not, rethrow the error.
10769 if ( this.getElementDocument().body
.contains( input
) ) {
10777 * Get an object describing the current selection range in a directional manner
10779 * @return {Object} Object containing 'from' and 'to' offsets
10781 OO
.ui
.TextInputWidget
.prototype.getRange = function () {
10782 var input
= this.$input
[ 0 ],
10783 start
= input
.selectionStart
,
10784 end
= input
.selectionEnd
,
10785 isBackwards
= input
.selectionDirection
=== 'backward';
10788 from: isBackwards
? end
: start
,
10789 to
: isBackwards
? start
: end
10794 * Get the length of the text input value.
10796 * This could differ from the length of #getValue if the
10797 * value gets filtered
10799 * @return {number} Input length
10801 OO
.ui
.TextInputWidget
.prototype.getInputLength = function () {
10802 return this.$input
[ 0 ].value
.length
;
10806 * Focus the input and select the entire text.
10809 * @return {OO.ui.Widget} The widget, for chaining
10811 OO
.ui
.TextInputWidget
.prototype.select = function () {
10812 return this.selectRange( 0, this.getInputLength() );
10816 * Focus the input and move the cursor to the start.
10819 * @return {OO.ui.Widget} The widget, for chaining
10821 OO
.ui
.TextInputWidget
.prototype.moveCursorToStart = function () {
10822 return this.selectRange( 0 );
10826 * Focus the input and move the cursor to the end.
10829 * @return {OO.ui.Widget} The widget, for chaining
10831 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
10832 return this.selectRange( this.getInputLength() );
10836 * Insert new content into the input.
10838 * @param {string} content Content to be inserted
10840 * @return {OO.ui.Widget} The widget, for chaining
10842 OO
.ui
.TextInputWidget
.prototype.insertContent = function ( content
) {
10844 range
= this.getRange(),
10845 value
= this.getValue();
10847 start
= Math
.min( range
.from, range
.to
);
10848 end
= Math
.max( range
.from, range
.to
);
10850 this.setValue( value
.slice( 0, start
) + content
+ value
.slice( end
) );
10851 this.selectRange( start
+ content
.length
);
10856 * Insert new content either side of a selection.
10858 * @param {string} pre Content to be inserted before the selection
10859 * @param {string} post Content to be inserted after the selection
10861 * @return {OO.ui.Widget} The widget, for chaining
10863 OO
.ui
.TextInputWidget
.prototype.encapsulateContent = function ( pre
, post
) {
10865 range
= this.getRange(),
10866 offset
= pre
.length
;
10868 start
= Math
.min( range
.from, range
.to
);
10869 end
= Math
.max( range
.from, range
.to
);
10871 this.selectRange( start
).insertContent( pre
);
10872 this.selectRange( offset
+ end
).insertContent( post
);
10874 this.selectRange( offset
+ start
, offset
+ end
);
10879 * Set the validation pattern.
10881 * The validation pattern is either a regular expression, a function, or the symbolic name of a
10882 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
10883 * value must contain only numbers).
10885 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
10886 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
10888 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
10889 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
10890 this.validate
= validate
;
10892 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
10897 * Sets the 'invalid' flag appropriately.
10899 * @param {boolean} [isValid] Optionally override validation result
10901 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
10903 setFlag = function ( valid
) {
10905 widget
.$input
.attr( 'aria-invalid', 'true' );
10907 widget
.$input
.removeAttr( 'aria-invalid' );
10909 widget
.setFlags( { invalid
: !valid
} );
10912 if ( isValid
!== undefined ) {
10913 setFlag( isValid
);
10915 this.getValidity().then( function () {
10924 * Get the validity of current value.
10926 * This method returns a promise that resolves if the value is valid and rejects if
10927 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
10929 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
10931 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
10934 function rejectOrResolve( valid
) {
10936 return $.Deferred().resolve().promise();
10938 return $.Deferred().reject().promise();
10942 // Check browser validity and reject if it is invalid
10944 this.$input
[ 0 ].checkValidity
!== undefined &&
10945 this.$input
[ 0 ].checkValidity() === false
10947 return rejectOrResolve( false );
10950 // Run our checks if the browser thinks the field is valid
10951 if ( this.validate
instanceof Function
) {
10952 result
= this.validate( this.getValue() );
10953 if ( result
&& typeof result
.promise
=== 'function' ) {
10954 return result
.promise().then( function ( valid
) {
10955 return rejectOrResolve( valid
);
10958 return rejectOrResolve( result
);
10961 return rejectOrResolve( this.getValue().match( this.validate
) );
10966 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
10968 * @param {string} labelPosition Label position, 'before' or 'after'
10970 * @return {OO.ui.Widget} The widget, for chaining
10972 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
10973 this.labelPosition
= labelPosition
;
10974 if ( this.label
) {
10975 // If there is no label and we only change the position, #updatePosition is a no-op,
10976 // but it takes really a lot of work to do nothing.
10977 this.updatePosition();
10983 * Update the position of the inline label.
10985 * This method is called by #setLabelPosition, and can also be called on its own if
10986 * something causes the label to be mispositioned.
10989 * @return {OO.ui.Widget} The widget, for chaining
10991 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
10992 var after
= this.labelPosition
=== 'after';
10995 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
10996 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
10998 this.valCache
= null;
10999 this.scrollWidth
= null;
11000 this.positionLabel();
11006 * Position the label by setting the correct padding on the input.
11010 * @return {OO.ui.Widget} The widget, for chaining
11012 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
11013 var after
, rtl
, property
, newCss
;
11015 if ( this.isWaitingToBeAttached
) {
11016 // #onElementAttach will be called soon, which calls this method
11021 'padding-right': '',
11025 if ( this.label
) {
11026 this.$element
.append( this.$label
);
11028 this.$label
.detach();
11029 // Clear old values if present
11030 this.$input
.css( newCss
);
11034 after
= this.labelPosition
=== 'after';
11035 rtl
= this.$element
.css( 'direction' ) === 'rtl';
11036 property
= after
=== rtl
? 'padding-left' : 'padding-right';
11038 newCss
[ property
] = this.$label
.outerWidth( true ) + ( after
? this.scrollWidth
: 0 );
11039 // We have to clear the padding on the other side, in case the element direction changed
11040 this.$input
.css( newCss
);
11046 * SearchInputWidgets are TextInputWidgets with `type="search"` assigned and feature a
11047 * {@link OO.ui.mixin.IconElement search icon} by default.
11048 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
11050 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#SearchInputWidget
11053 * @extends OO.ui.TextInputWidget
11056 * @param {Object} [config] Configuration options
11058 OO
.ui
.SearchInputWidget
= function OoUiSearchInputWidget( config
) {
11059 config
= $.extend( {
11063 // Parent constructor
11064 OO
.ui
.SearchInputWidget
.parent
.call( this, config
);
11067 this.connect( this, {
11072 this.updateSearchIndicator();
11073 this.connect( this, {
11074 disable
: 'onDisable'
11080 OO
.inheritClass( OO
.ui
.SearchInputWidget
, OO
.ui
.TextInputWidget
);
11088 OO
.ui
.SearchInputWidget
.prototype.getSaneType = function () {
11095 OO
.ui
.SearchInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
11096 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
11097 // Clear the text field
11098 this.setValue( '' );
11105 * Update the 'clear' indicator displayed on type: 'search' text
11106 * fields, hiding it when the field is already empty or when it's not
11109 OO
.ui
.SearchInputWidget
.prototype.updateSearchIndicator = function () {
11110 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
11111 this.setIndicator( null );
11113 this.setIndicator( 'clear' );
11118 * Handle change events.
11122 OO
.ui
.SearchInputWidget
.prototype.onChange = function () {
11123 this.updateSearchIndicator();
11127 * Handle disable events.
11129 * @param {boolean} disabled Element is disabled
11132 OO
.ui
.SearchInputWidget
.prototype.onDisable = function () {
11133 this.updateSearchIndicator();
11139 OO
.ui
.SearchInputWidget
.prototype.setReadOnly = function ( state
) {
11140 OO
.ui
.SearchInputWidget
.parent
.prototype.setReadOnly
.call( this, state
);
11141 this.updateSearchIndicator();
11146 * MultilineTextInputWidgets, like HTML textareas, are featuring customization options to
11147 * configure number of rows visible. In addition, these widgets can be autosized to fit user
11148 * inputs and can show {@link OO.ui.mixin.IconElement icons} and
11149 * {@link OO.ui.mixin.IndicatorElement indicators}.
11150 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
11152 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
11155 * // A MultilineTextInputWidget.
11156 * var multilineTextInput = new OO.ui.MultilineTextInputWidget( {
11157 * value: 'Text input on multiple lines'
11159 * $( 'body' ).append( multilineTextInput.$element );
11161 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#MultilineTextInputWidget
11164 * @extends OO.ui.TextInputWidget
11167 * @param {Object} [config] Configuration options
11168 * @cfg {number} [rows] Number of visible lines in textarea. If used with `autosize`,
11169 * specifies minimum number of rows to display.
11170 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
11171 * Use the #maxRows config to specify a maximum number of displayed rows.
11172 * @cfg {number} [maxRows] Maximum number of rows to display when #autosize is set to true.
11173 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
11175 OO
.ui
.MultilineTextInputWidget
= function OoUiMultilineTextInputWidget( config
) {
11176 config
= $.extend( {
11179 // Parent constructor
11180 OO
.ui
.MultilineTextInputWidget
.parent
.call( this, config
);
11183 this.autosize
= !!config
.autosize
;
11184 this.styleHeight
= null;
11185 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
11186 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
11188 // Clone for resizing
11189 if ( this.autosize
) {
11190 this.$clone
= this.$input
11192 .removeAttr( 'id' )
11193 .removeAttr( 'name' )
11194 .insertAfter( this.$input
)
11195 .attr( 'aria-hidden', 'true' )
11196 .addClass( 'oo-ui-element-hidden' );
11200 this.connect( this, {
11205 if ( config
.rows
) {
11206 this.$input
.attr( 'rows', config
.rows
);
11208 if ( this.autosize
) {
11209 this.$input
.addClass( 'oo-ui-textInputWidget-autosized' );
11210 this.isWaitingToBeAttached
= true;
11211 this.installParentChangeDetector();
11217 OO
.inheritClass( OO
.ui
.MultilineTextInputWidget
, OO
.ui
.TextInputWidget
);
11219 /* Static Methods */
11224 OO
.ui
.MultilineTextInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
11225 var state
= OO
.ui
.MultilineTextInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
11226 state
.scrollTop
= config
.$input
.scrollTop();
11235 OO
.ui
.MultilineTextInputWidget
.prototype.onElementAttach = function () {
11236 OO
.ui
.MultilineTextInputWidget
.parent
.prototype.onElementAttach
.call( this );
11241 * Handle change events.
11245 OO
.ui
.MultilineTextInputWidget
.prototype.onChange = function () {
11252 OO
.ui
.MultilineTextInputWidget
.prototype.updatePosition = function () {
11253 OO
.ui
.MultilineTextInputWidget
.parent
.prototype.updatePosition
.call( this );
11260 * Modify to emit 'enter' on Ctrl/Meta+Enter, instead of plain Enter
11262 OO
.ui
.MultilineTextInputWidget
.prototype.onKeyPress = function ( e
) {
11264 ( e
.which
=== OO
.ui
.Keys
.ENTER
&& ( e
.ctrlKey
|| e
.metaKey
) ) ||
11265 // Some platforms emit keycode 10 for ctrl+enter in a textarea
11268 this.emit( 'enter', e
);
11273 * Automatically adjust the size of the text input.
11275 * This only affects multiline inputs that are {@link #autosize autosized}.
11278 * @return {OO.ui.Widget} The widget, for chaining
11281 OO
.ui
.MultilineTextInputWidget
.prototype.adjustSize = function () {
11282 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
,
11283 idealHeight
, newHeight
, scrollWidth
, property
;
11285 if ( this.$input
.val() !== this.valCache
) {
11286 if ( this.autosize
) {
11288 .val( this.$input
.val() )
11289 .attr( 'rows', this.minRows
)
11290 // Set inline height property to 0 to measure scroll height
11291 .css( 'height', 0 );
11293 this.$clone
.removeClass( 'oo-ui-element-hidden' );
11295 this.valCache
= this.$input
.val();
11297 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
11299 // Remove inline height property to measure natural heights
11300 this.$clone
.css( 'height', '' );
11301 innerHeight
= this.$clone
.innerHeight();
11302 outerHeight
= this.$clone
.outerHeight();
11304 // Measure max rows height
11306 .attr( 'rows', this.maxRows
)
11307 .css( 'height', 'auto' )
11309 maxInnerHeight
= this.$clone
.innerHeight();
11311 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
11312 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
11313 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
11314 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
11316 this.$clone
.addClass( 'oo-ui-element-hidden' );
11318 // Only apply inline height when expansion beyond natural height is needed
11319 // Use the difference between the inner and outer height as a buffer
11320 newHeight
= idealHeight
> innerHeight
? idealHeight
+ ( outerHeight
- innerHeight
) : '';
11321 if ( newHeight
!== this.styleHeight
) {
11322 this.$input
.css( 'height', newHeight
);
11323 this.styleHeight
= newHeight
;
11324 this.emit( 'resize' );
11327 scrollWidth
= this.$input
[ 0 ].offsetWidth
- this.$input
[ 0 ].clientWidth
;
11328 if ( scrollWidth
!== this.scrollWidth
) {
11329 property
= this.$element
.css( 'direction' ) === 'rtl' ? 'left' : 'right';
11331 this.$label
.css( { right
: '', left
: '' } );
11332 this.$indicator
.css( { right
: '', left
: '' } );
11334 if ( scrollWidth
) {
11335 this.$indicator
.css( property
, scrollWidth
);
11336 if ( this.labelPosition
=== 'after' ) {
11337 this.$label
.css( property
, scrollWidth
);
11341 this.scrollWidth
= scrollWidth
;
11342 this.positionLabel();
11352 OO
.ui
.MultilineTextInputWidget
.prototype.getInputElement = function () {
11353 return $( '<textarea>' );
11357 * Check if the input automatically adjusts its size.
11359 * @return {boolean}
11361 OO
.ui
.MultilineTextInputWidget
.prototype.isAutosizing = function () {
11362 return !!this.autosize
;
11368 OO
.ui
.MultilineTextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
11369 OO
.ui
.MultilineTextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
11370 if ( state
.scrollTop
!== undefined ) {
11371 this.$input
.scrollTop( state
.scrollTop
);
11376 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
11377 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
11378 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
11380 * - by typing a value in the text input field. If the value exactly matches the value of a menu
11381 * option, that option will appear to be selected.
11382 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
11385 * After the user chooses an option, its `data` will be used as a new value for the widget.
11386 * A `label` also can be specified for each option: if given, it will be shown instead of the
11387 * `data` in the dropdown menu.
11389 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
11391 * For more information about menus and options, please see the [OOUI documentation on MediaWiki][1].
11394 * // A ComboBoxInputWidget.
11395 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11396 * value: 'Option 1',
11398 * { data: 'Option 1' },
11399 * { data: 'Option 2' },
11400 * { data: 'Option 3' }
11403 * $( document.body ).append( comboBox.$element );
11406 * // Example: A ComboBoxInputWidget with additional option labels.
11407 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11408 * value: 'Option 1',
11411 * data: 'Option 1',
11412 * label: 'Option One'
11415 * data: 'Option 2',
11416 * label: 'Option Two'
11419 * data: 'Option 3',
11420 * label: 'Option Three'
11424 * $( document.body ).append( comboBox.$element );
11426 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
11429 * @extends OO.ui.TextInputWidget
11432 * @param {Object} [config] Configuration options
11433 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
11434 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
11435 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
11436 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
11437 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
11438 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11440 OO
.ui
.ComboBoxInputWidget
= function OoUiComboBoxInputWidget( config
) {
11441 // Configuration initialization
11442 config
= $.extend( {
11443 autocomplete
: false
11446 // ComboBoxInputWidget shouldn't support `multiline`
11447 config
.multiline
= false;
11449 // See InputWidget#reusePreInfuseDOM about `config.$input`
11450 if ( config
.$input
) {
11451 config
.$input
.removeAttr( 'list' );
11454 // Parent constructor
11455 OO
.ui
.ComboBoxInputWidget
.parent
.call( this, config
);
11458 this.$overlay
= ( config
.$overlay
=== true ? OO
.ui
.getDefaultOverlay() : config
.$overlay
) || this.$element
;
11459 this.dropdownButton
= new OO
.ui
.ButtonWidget( {
11460 classes
: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ],
11461 label
: OO
.ui
.msg( 'ooui-combobox-button-label' ),
11463 invisibleLabel
: true,
11464 disabled
: this.disabled
11466 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend(
11470 $floatableContainer
: this.$element
,
11471 disabled
: this.isDisabled()
11477 this.connect( this, {
11478 change
: 'onInputChange',
11479 enter
: 'onInputEnter'
11481 this.dropdownButton
.connect( this, {
11482 click
: 'onDropdownButtonClick'
11484 this.menu
.connect( this, {
11485 choose
: 'onMenuChoose',
11486 add
: 'onMenuItemsChange',
11487 remove
: 'onMenuItemsChange',
11488 toggle
: 'onMenuToggle'
11492 this.$input
.attr( {
11494 'aria-owns': this.menu
.getElementId(),
11495 'aria-autocomplete': 'list'
11497 this.dropdownButton
.$button
.attr( {
11498 'aria-controls': this.menu
.getElementId()
11500 // Do not override options set via config.menu.items
11501 if ( config
.options
!== undefined ) {
11502 this.setOptions( config
.options
);
11504 this.$field
= $( '<div>' )
11505 .addClass( 'oo-ui-comboBoxInputWidget-field' )
11506 .append( this.$input
, this.dropdownButton
.$element
);
11508 .addClass( 'oo-ui-comboBoxInputWidget' )
11509 .append( this.$field
);
11510 this.$overlay
.append( this.menu
.$element
);
11511 this.onMenuItemsChange();
11516 OO
.inheritClass( OO
.ui
.ComboBoxInputWidget
, OO
.ui
.TextInputWidget
);
11521 * Get the combobox's menu.
11523 * @return {OO.ui.MenuSelectWidget} Menu widget
11525 OO
.ui
.ComboBoxInputWidget
.prototype.getMenu = function () {
11530 * Get the combobox's text input widget.
11532 * @return {OO.ui.TextInputWidget} Text input widget
11534 OO
.ui
.ComboBoxInputWidget
.prototype.getInput = function () {
11539 * Handle input change events.
11542 * @param {string} value New value
11544 OO
.ui
.ComboBoxInputWidget
.prototype.onInputChange = function ( value
) {
11545 var match
= this.menu
.findItemFromData( value
);
11547 this.menu
.selectItem( match
);
11548 if ( this.menu
.findHighlightedItem() ) {
11549 this.menu
.highlightItem( match
);
11552 if ( !this.isDisabled() ) {
11553 this.menu
.toggle( true );
11558 * Handle input enter events.
11562 OO
.ui
.ComboBoxInputWidget
.prototype.onInputEnter = function () {
11563 if ( !this.isDisabled() ) {
11564 this.menu
.toggle( false );
11569 * Handle button click events.
11573 OO
.ui
.ComboBoxInputWidget
.prototype.onDropdownButtonClick = function () {
11574 this.menu
.toggle();
11579 * Handle menu choose events.
11582 * @param {OO.ui.OptionWidget} item Chosen item
11584 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuChoose = function ( item
) {
11585 this.setValue( item
.getData() );
11589 * Handle menu item change events.
11593 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuItemsChange = function () {
11594 var match
= this.menu
.findItemFromData( this.getValue() );
11595 this.menu
.selectItem( match
);
11596 if ( this.menu
.findHighlightedItem() ) {
11597 this.menu
.highlightItem( match
);
11599 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu
.isEmpty() );
11603 * Handle menu toggle events.
11606 * @param {boolean} isVisible Open state of the menu
11608 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuToggle = function ( isVisible
) {
11609 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-open', isVisible
);
11613 * Update the disabled state of the controls
11617 * @return {OO.ui.ComboBoxInputWidget} The widget, for chaining
11619 OO
.ui
.ComboBoxInputWidget
.prototype.updateControlsDisabled = function () {
11620 var disabled
= this.isDisabled() || this.isReadOnly();
11621 if ( this.dropdownButton
) {
11622 this.dropdownButton
.setDisabled( disabled
);
11625 this.menu
.setDisabled( disabled
);
11633 OO
.ui
.ComboBoxInputWidget
.prototype.setDisabled = function () {
11635 OO
.ui
.ComboBoxInputWidget
.parent
.prototype.setDisabled
.apply( this, arguments
);
11636 this.updateControlsDisabled();
11643 OO
.ui
.ComboBoxInputWidget
.prototype.setReadOnly = function () {
11645 OO
.ui
.ComboBoxInputWidget
.parent
.prototype.setReadOnly
.apply( this, arguments
);
11646 this.updateControlsDisabled();
11651 * Set the options available for this input.
11653 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
11655 * @return {OO.ui.Widget} The widget, for chaining
11657 OO
.ui
.ComboBoxInputWidget
.prototype.setOptions = function ( options
) {
11660 .addItems( options
.map( function ( opt
) {
11661 return new OO
.ui
.MenuOptionWidget( {
11663 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
11671 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
11672 * which is a widget that is specified by reference before any optional configuration settings.
11674 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
11676 * - **left**: The label is placed before the field-widget and aligned with the left margin.
11677 * A left-alignment is used for forms with many fields.
11678 * - **right**: The label is placed before the field-widget and aligned to the right margin.
11679 * A right-alignment is used for long but familiar forms which users tab through,
11680 * verifying the current field with a quick glance at the label.
11681 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
11682 * that users fill out from top to bottom.
11683 * - **inline**: The label is placed after the field-widget and aligned to the left.
11684 * An inline-alignment is best used with checkboxes or radio buttons.
11686 * Help text can either be:
11688 * - accessed via a help icon that appears in the upper right corner of the rendered field layout, or
11689 * - shown as a subtle explanation below the label.
11691 * If the help text is brief, or is essential to always expose it, set `helpInline` to `true`. If it
11692 * is long or not essential, leave `helpInline` to its default, `false`.
11694 * Please see the [OOUI documentation on MediaWiki] [1] for examples and more information.
11696 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
11699 * @extends OO.ui.Layout
11700 * @mixins OO.ui.mixin.LabelElement
11701 * @mixins OO.ui.mixin.TitledElement
11704 * @param {OO.ui.Widget} fieldWidget Field widget
11705 * @param {Object} [config] Configuration options
11706 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top'
11708 * @cfg {Array} [errors] Error messages about the widget, which will be
11709 * displayed below the widget.
11710 * The array may contain strings or OO.ui.HtmlSnippet instances.
11711 * @cfg {Array} [notices] Notices about the widget, which will be displayed
11712 * below the widget.
11713 * The array may contain strings or OO.ui.HtmlSnippet instances.
11714 * These are more visible than `help` messages when `helpInline` is set, and so
11715 * might be good for transient messages.
11716 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified
11717 * and `helpInline` is `false`, a "help" icon will appear in the upper-right
11718 * corner of the rendered field; clicking it will display the text in a popup.
11719 * If `helpInline` is `true`, then a subtle description will be shown after the
11721 * @cfg {boolean} [helpInline=false] Whether or not the help should be inline,
11722 * or shown when the "help" icon is clicked.
11723 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if
11725 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11727 * @throws {Error} An error is thrown if no widget is specified
11729 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
11730 // Allow passing positional parameters inside the config object
11731 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
11732 config
= fieldWidget
;
11733 fieldWidget
= config
.fieldWidget
;
11736 // Make sure we have required constructor arguments
11737 if ( fieldWidget
=== undefined ) {
11738 throw new Error( 'Widget not found' );
11741 // Configuration initialization
11742 config
= $.extend( { align
: 'left', helpInline
: false }, config
);
11744 // Parent constructor
11745 OO
.ui
.FieldLayout
.parent
.call( this, config
);
11747 // Mixin constructors
11748 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, {
11749 $label
: $( '<label>' )
11751 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
11754 this.fieldWidget
= fieldWidget
;
11757 this.$field
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
11758 this.$messages
= $( '<ul>' );
11759 this.$header
= $( '<span>' );
11760 this.$body
= $( '<div>' );
11762 this.helpInline
= config
.helpInline
;
11765 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
11768 this.$help
= config
.help
?
11769 this.createHelpElement( config
.help
, config
.$overlay
) :
11771 if ( this.fieldWidget
.getInputId() ) {
11772 this.$label
.attr( 'for', this.fieldWidget
.getInputId() );
11773 if ( this.helpInline
) {
11774 this.$help
.attr( 'for', this.fieldWidget
.getInputId() );
11777 this.$label
.on( 'click', function () {
11778 this.fieldWidget
.simulateLabelClick();
11780 if ( this.helpInline
) {
11781 this.$help
.on( 'click', function () {
11782 this.fieldWidget
.simulateLabelClick();
11787 .addClass( 'oo-ui-fieldLayout' )
11788 .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget
.isDisabled() )
11789 .append( this.$body
);
11790 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
11791 this.$header
.addClass( 'oo-ui-fieldLayout-header' );
11792 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
11794 .addClass( 'oo-ui-fieldLayout-field' )
11795 .append( this.fieldWidget
.$element
);
11797 this.setErrors( config
.errors
|| [] );
11798 this.setNotices( config
.notices
|| [] );
11799 this.setAlignment( config
.align
);
11800 // Call this again to take into account the widget's accessKey
11801 this.updateTitle();
11806 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
11807 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
11808 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
11813 * Handle field disable events.
11816 * @param {boolean} value Field is disabled
11818 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
11819 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
11823 * Get the widget contained by the field.
11825 * @return {OO.ui.Widget} Field widget
11827 OO
.ui
.FieldLayout
.prototype.getField = function () {
11828 return this.fieldWidget
;
11832 * Return `true` if the given field widget can be used with `'inline'` alignment (see
11833 * #setAlignment). Return `false` if it can't or if this can't be determined.
11835 * @return {boolean}
11837 OO
.ui
.FieldLayout
.prototype.isFieldInline = function () {
11838 // This is very simplistic, but should be good enough.
11839 return this.getField().$element
.prop( 'tagName' ).toLowerCase() === 'span';
11844 * @param {string} kind 'error' or 'notice'
11845 * @param {string|OO.ui.HtmlSnippet} text
11848 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
11849 var $listItem
, $icon
, message
;
11850 $listItem
= $( '<li>' );
11851 if ( kind
=== 'error' ) {
11852 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
11853 $listItem
.attr( 'role', 'alert' );
11854 } else if ( kind
=== 'notice' ) {
11855 $icon
= new OO
.ui
.IconWidget( { icon
: 'notice' } ).$element
;
11859 message
= new OO
.ui
.LabelWidget( { label
: text
} );
11861 .append( $icon
, message
.$element
)
11862 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
11867 * Set the field alignment mode.
11870 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
11872 * @return {OO.ui.BookletLayout} The layout, for chaining
11874 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
11875 if ( value
!== this.align
) {
11876 // Default to 'left'
11877 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
11881 if ( value
=== 'inline' && !this.isFieldInline() ) {
11884 // Reorder elements
11886 if ( this.helpInline
) {
11887 if ( value
=== 'top' ) {
11888 this.$header
.append( this.$label
);
11889 this.$body
.append( this.$header
, this.$field
, this.$help
);
11890 } else if ( value
=== 'inline' ) {
11891 this.$header
.append( this.$label
, this.$help
);
11892 this.$body
.append( this.$field
, this.$header
);
11894 this.$header
.append( this.$label
, this.$help
);
11895 this.$body
.append( this.$header
, this.$field
);
11898 if ( value
=== 'top' ) {
11899 this.$header
.append( this.$help
, this.$label
);
11900 this.$body
.append( this.$header
, this.$field
);
11901 } else if ( value
=== 'inline' ) {
11902 this.$header
.append( this.$help
, this.$label
);
11903 this.$body
.append( this.$field
, this.$header
);
11905 this.$header
.append( this.$label
);
11906 this.$body
.append( this.$header
, this.$help
, this.$field
);
11909 // Set classes. The following classes can be used here:
11910 // * oo-ui-fieldLayout-align-left
11911 // * oo-ui-fieldLayout-align-right
11912 // * oo-ui-fieldLayout-align-top
11913 // * oo-ui-fieldLayout-align-inline
11914 if ( this.align
) {
11915 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
11917 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
11918 this.align
= value
;
11925 * Set the list of error messages.
11927 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
11928 * The array may contain strings or OO.ui.HtmlSnippet instances.
11930 * @return {OO.ui.BookletLayout} The layout, for chaining
11932 OO
.ui
.FieldLayout
.prototype.setErrors = function ( errors
) {
11933 this.errors
= errors
.slice();
11934 this.updateMessages();
11939 * Set the list of notice messages.
11941 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
11942 * The array may contain strings or OO.ui.HtmlSnippet instances.
11944 * @return {OO.ui.BookletLayout} The layout, for chaining
11946 OO
.ui
.FieldLayout
.prototype.setNotices = function ( notices
) {
11947 this.notices
= notices
.slice();
11948 this.updateMessages();
11953 * Update the rendering of error and notice messages.
11957 OO
.ui
.FieldLayout
.prototype.updateMessages = function () {
11959 this.$messages
.empty();
11961 if ( this.errors
.length
|| this.notices
.length
) {
11962 this.$body
.after( this.$messages
);
11964 this.$messages
.remove();
11968 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
11969 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
11971 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
11972 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
11977 * Include information about the widget's accessKey in our title. TitledElement calls this method.
11978 * (This is a bit of a hack.)
11981 * @param {string} title Tooltip label for 'title' attribute
11984 OO
.ui
.FieldLayout
.prototype.formatTitleWithAccessKey = function ( title
) {
11985 if ( this.fieldWidget
&& this.fieldWidget
.formatTitleWithAccessKey
) {
11986 return this.fieldWidget
.formatTitleWithAccessKey( title
);
11992 * Creates and returns the help element. Also sets the `aria-describedby`
11993 * attribute on the main element of the `fieldWidget`.
11996 * @param {string|OO.ui.HtmlSnippet} [help] Help text.
11997 * @param {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup.
11998 * @return {jQuery} The element that should become `this.$help`.
12000 OO
.ui
.FieldLayout
.prototype.createHelpElement = function ( help
, $overlay
) {
12001 var helpId
, helpWidget
;
12003 if ( this.helpInline
) {
12004 helpWidget
= new OO
.ui
.LabelWidget( {
12006 classes
: [ 'oo-ui-inline-help' ]
12009 helpId
= helpWidget
.getElementId();
12011 helpWidget
= new OO
.ui
.PopupButtonWidget( {
12012 $overlay
: $overlay
,
12016 classes
: [ 'oo-ui-fieldLayout-help' ],
12019 label
: OO
.ui
.msg( 'ooui-field-help' ),
12020 invisibleLabel
: true
12022 if ( help
instanceof OO
.ui
.HtmlSnippet
) {
12023 helpWidget
.getPopup().$body
.html( help
.toString() );
12025 helpWidget
.getPopup().$body
.text( help
);
12028 helpId
= helpWidget
.getPopup().getBodyId();
12031 // Set the 'aria-describedby' attribute on the fieldWidget
12032 // Preference given to an input or a button
12034 this.fieldWidget
.$input
||
12035 this.fieldWidget
.$button
||
12036 this.fieldWidget
.$element
12037 ).attr( 'aria-describedby', helpId
);
12039 return helpWidget
.$element
;
12043 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
12044 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
12045 * is required and is specified before any optional configuration settings.
12047 * Labels can be aligned in one of four ways:
12049 * - **left**: The label is placed before the field-widget and aligned with the left margin.
12050 * A left-alignment is used for forms with many fields.
12051 * - **right**: The label is placed before the field-widget and aligned to the right margin.
12052 * A right-alignment is used for long but familiar forms which users tab through,
12053 * verifying the current field with a quick glance at the label.
12054 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
12055 * that users fill out from top to bottom.
12056 * - **inline**: The label is placed after the field-widget and aligned to the left.
12057 * An inline-alignment is best used with checkboxes or radio buttons.
12059 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
12060 * text is specified.
12063 * // Example of an ActionFieldLayout
12064 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
12065 * new OO.ui.TextInputWidget( {
12066 * placeholder: 'Field widget'
12068 * new OO.ui.ButtonWidget( {
12072 * label: 'An ActionFieldLayout. This label is aligned top',
12074 * help: 'This is help text'
12078 * $( document.body ).append( actionFieldLayout.$element );
12081 * @extends OO.ui.FieldLayout
12084 * @param {OO.ui.Widget} fieldWidget Field widget
12085 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
12086 * @param {Object} config
12088 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
12089 // Allow passing positional parameters inside the config object
12090 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
12091 config
= fieldWidget
;
12092 fieldWidget
= config
.fieldWidget
;
12093 buttonWidget
= config
.buttonWidget
;
12096 // Parent constructor
12097 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
12100 this.buttonWidget
= buttonWidget
;
12101 this.$button
= $( '<span>' );
12102 this.$input
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
12106 .addClass( 'oo-ui-actionFieldLayout' );
12108 .addClass( 'oo-ui-actionFieldLayout-button' )
12109 .append( this.buttonWidget
.$element
);
12111 .addClass( 'oo-ui-actionFieldLayout-input' )
12112 .append( this.fieldWidget
.$element
);
12114 .append( this.$input
, this.$button
);
12119 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
12122 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
12123 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
12124 * configured with a label as well. For more information and examples,
12125 * please see the [OOUI documentation on MediaWiki][1].
12128 * // Example of a fieldset layout
12129 * var input1 = new OO.ui.TextInputWidget( {
12130 * placeholder: 'A text input field'
12133 * var input2 = new OO.ui.TextInputWidget( {
12134 * placeholder: 'A text input field'
12137 * var fieldset = new OO.ui.FieldsetLayout( {
12138 * label: 'Example of a fieldset layout'
12141 * fieldset.addItems( [
12142 * new OO.ui.FieldLayout( input1, {
12143 * label: 'Field One'
12145 * new OO.ui.FieldLayout( input2, {
12146 * label: 'Field Two'
12149 * $( document.body ).append( fieldset.$element );
12151 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
12154 * @extends OO.ui.Layout
12155 * @mixins OO.ui.mixin.IconElement
12156 * @mixins OO.ui.mixin.LabelElement
12157 * @mixins OO.ui.mixin.GroupElement
12160 * @param {Object} [config] Configuration options
12161 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
12162 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
12163 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
12164 * For important messages, you are advised to use `notices`, as they are always shown.
12165 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
12166 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
12168 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
12169 // Configuration initialization
12170 config
= config
|| {};
12172 // Parent constructor
12173 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
12175 // Mixin constructors
12176 OO
.ui
.mixin
.IconElement
.call( this, config
);
12177 OO
.ui
.mixin
.LabelElement
.call( this, config
);
12178 OO
.ui
.mixin
.GroupElement
.call( this, config
);
12181 this.$header
= $( '<legend>' );
12182 if ( config
.help
) {
12183 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
12184 $overlay
: config
.$overlay
,
12188 classes
: [ 'oo-ui-fieldsetLayout-help' ],
12191 label
: OO
.ui
.msg( 'ooui-field-help' ),
12192 invisibleLabel
: true
12194 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
12195 this.popupButtonWidget
.getPopup().$body
.html( config
.help
.toString() );
12197 this.popupButtonWidget
.getPopup().$body
.text( config
.help
);
12199 this.$help
= this.popupButtonWidget
.$element
;
12201 this.$help
= $( [] );
12206 .addClass( 'oo-ui-fieldsetLayout-header' )
12207 .append( this.$icon
, this.$label
, this.$help
);
12208 this.$group
.addClass( 'oo-ui-fieldsetLayout-group' );
12210 .addClass( 'oo-ui-fieldsetLayout' )
12211 .prepend( this.$header
, this.$group
);
12212 if ( Array
.isArray( config
.items
) ) {
12213 this.addItems( config
.items
);
12219 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
12220 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
12221 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
12222 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
12224 /* Static Properties */
12230 OO
.ui
.FieldsetLayout
.static.tagName
= 'fieldset';
12233 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
12234 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
12235 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
12236 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
12238 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
12239 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
12240 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
12241 * some fancier controls. Some controls have both regular and InputWidget variants, for example
12242 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
12243 * often have simplified APIs to match the capabilities of HTML forms.
12244 * See the [OOUI documentation on MediaWiki] [2] for more information about InputWidgets.
12246 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Forms
12247 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
12250 * // Example of a form layout that wraps a fieldset layout
12251 * var input1 = new OO.ui.TextInputWidget( {
12252 * placeholder: 'Username'
12254 * var input2 = new OO.ui.TextInputWidget( {
12255 * placeholder: 'Password',
12258 * var submit = new OO.ui.ButtonInputWidget( {
12262 * var fieldset = new OO.ui.FieldsetLayout( {
12263 * label: 'A form layout'
12265 * fieldset.addItems( [
12266 * new OO.ui.FieldLayout( input1, {
12267 * label: 'Username',
12270 * new OO.ui.FieldLayout( input2, {
12271 * label: 'Password',
12274 * new OO.ui.FieldLayout( submit )
12276 * var form = new OO.ui.FormLayout( {
12277 * items: [ fieldset ],
12278 * action: '/api/formhandler',
12281 * $( document.body ).append( form.$element );
12284 * @extends OO.ui.Layout
12285 * @mixins OO.ui.mixin.GroupElement
12288 * @param {Object} [config] Configuration options
12289 * @cfg {string} [method] HTML form `method` attribute
12290 * @cfg {string} [action] HTML form `action` attribute
12291 * @cfg {string} [enctype] HTML form `enctype` attribute
12292 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
12294 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
12297 // Configuration initialization
12298 config
= config
|| {};
12300 // Parent constructor
12301 OO
.ui
.FormLayout
.parent
.call( this, config
);
12303 // Mixin constructors
12304 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
12307 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
12309 // Make sure the action is safe
12310 action
= config
.action
;
12311 if ( action
!== undefined && !OO
.ui
.isSafeUrl( action
) ) {
12312 action
= './' + action
;
12317 .addClass( 'oo-ui-formLayout' )
12319 method
: config
.method
,
12321 enctype
: config
.enctype
12323 if ( Array
.isArray( config
.items
) ) {
12324 this.addItems( config
.items
);
12330 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
12331 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
12336 * A 'submit' event is emitted when the form is submitted.
12341 /* Static Properties */
12347 OO
.ui
.FormLayout
.static.tagName
= 'form';
12352 * Handle form submit events.
12355 * @param {jQuery.Event} e Submit event
12357 * @return {OO.ui.FormLayout} The layout, for chaining
12359 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
12360 if ( this.emit( 'submit' ) ) {
12366 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
12367 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
12370 * // Example of a panel layout
12371 * var panel = new OO.ui.PanelLayout( {
12375 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
12377 * $( document.body ).append( panel.$element );
12380 * @extends OO.ui.Layout
12383 * @param {Object} [config] Configuration options
12384 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
12385 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
12386 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
12387 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
12389 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
12390 // Configuration initialization
12391 config
= $.extend( {
12398 // Parent constructor
12399 OO
.ui
.PanelLayout
.parent
.call( this, config
);
12402 this.$element
.addClass( 'oo-ui-panelLayout' );
12403 if ( config
.scrollable
) {
12404 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
12406 if ( config
.padded
) {
12407 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
12409 if ( config
.expanded
) {
12410 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
12412 if ( config
.framed
) {
12413 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
12419 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
12424 * Focus the panel layout
12426 * The default implementation just focuses the first focusable element in the panel
12428 OO
.ui
.PanelLayout
.prototype.focus = function () {
12429 OO
.ui
.findFocusable( this.$element
).focus();
12433 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
12434 * items), with small margins between them. Convenient when you need to put a number of block-level
12435 * widgets on a single line next to each other.
12437 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
12440 * // HorizontalLayout with a text input and a label
12441 * var layout = new OO.ui.HorizontalLayout( {
12443 * new OO.ui.LabelWidget( { label: 'Label' } ),
12444 * new OO.ui.TextInputWidget( { value: 'Text' } )
12447 * $( document.body ).append( layout.$element );
12450 * @extends OO.ui.Layout
12451 * @mixins OO.ui.mixin.GroupElement
12454 * @param {Object} [config] Configuration options
12455 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
12457 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
12458 // Configuration initialization
12459 config
= config
|| {};
12461 // Parent constructor
12462 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
12464 // Mixin constructors
12465 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
12468 this.$element
.addClass( 'oo-ui-horizontalLayout' );
12469 if ( Array
.isArray( config
.items
) ) {
12470 this.addItems( config
.items
);
12476 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
12477 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);
12480 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
12481 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
12482 * (to adjust the value in increments) to allow the user to enter a number.
12485 * // A NumberInputWidget.
12486 * var numberInput = new OO.ui.NumberInputWidget( {
12487 * label: 'NumberInputWidget',
12488 * input: { value: 5 },
12492 * $( document.body ).append( numberInput.$element );
12495 * @extends OO.ui.TextInputWidget
12498 * @param {Object} [config] Configuration options
12499 * @cfg {Object} [minusButton] Configuration options to pass to the
12500 * {@link OO.ui.ButtonWidget decrementing button widget}.
12501 * @cfg {Object} [plusButton] Configuration options to pass to the
12502 * {@link OO.ui.ButtonWidget incrementing button widget}.
12503 * @cfg {number} [min=-Infinity] Minimum allowed value
12504 * @cfg {number} [max=Infinity] Maximum allowed value
12505 * @cfg {number|null} [step] If specified, the field only accepts values that are multiples of this.
12506 * @cfg {number} [buttonStep=step||1] Delta when using the buttons or up/down arrow keys.
12507 * Defaults to `step` if specified, otherwise `1`.
12508 * @cfg {number} [pageStep=10*buttonStep] Delta when using the page-up/page-down keys.
12509 * Defaults to 10 times `buttonStep`.
12510 * @cfg {boolean} [showButtons=true] Whether to show the plus and minus buttons.
12512 OO
.ui
.NumberInputWidget
= function OoUiNumberInputWidget( config
) {
12513 var $field
= $( '<div>' )
12514 .addClass( 'oo-ui-numberInputWidget-field' );
12516 // Configuration initialization
12517 config
= $.extend( {
12523 // For backward compatibility
12524 $.extend( config
, config
.input
);
12527 // Parent constructor
12528 OO
.ui
.NumberInputWidget
.parent
.call( this, $.extend( config
, {
12532 if ( config
.showButtons
) {
12533 this.minusButton
= new OO
.ui
.ButtonWidget( $.extend(
12535 disabled
: this.isDisabled(),
12537 classes
: [ 'oo-ui-numberInputWidget-minusButton' ],
12542 this.minusButton
.$element
.attr( 'aria-hidden', 'true' );
12543 this.plusButton
= new OO
.ui
.ButtonWidget( $.extend(
12545 disabled
: this.isDisabled(),
12547 classes
: [ 'oo-ui-numberInputWidget-plusButton' ],
12552 this.plusButton
.$element
.attr( 'aria-hidden', 'true' );
12557 keydown
: this.onKeyDown
.bind( this ),
12558 'wheel mousewheel DOMMouseScroll': this.onWheel
.bind( this )
12560 if ( config
.showButtons
) {
12561 this.plusButton
.connect( this, {
12562 click
: [ 'onButtonClick', +1 ]
12564 this.minusButton
.connect( this, {
12565 click
: [ 'onButtonClick', -1 ]
12570 $field
.append( this.$input
);
12571 if ( config
.showButtons
) {
12573 .prepend( this.minusButton
.$element
)
12574 .append( this.plusButton
.$element
);
12578 if ( config
.allowInteger
|| config
.isInteger
) {
12579 // Backward compatibility
12582 this.setRange( config
.min
, config
.max
);
12583 this.setStep( config
.buttonStep
, config
.pageStep
, config
.step
);
12584 // Set the validation method after we set step and range
12585 // so that it doesn't immediately call setValidityFlag
12586 this.setValidation( this.validateNumber
.bind( this ) );
12589 .addClass( 'oo-ui-numberInputWidget' )
12590 .toggleClass( 'oo-ui-numberInputWidget-buttoned', config
.showButtons
)
12596 OO
.inheritClass( OO
.ui
.NumberInputWidget
, OO
.ui
.TextInputWidget
);
12600 // Backward compatibility
12601 OO
.ui
.NumberInputWidget
.prototype.setAllowInteger = function ( flag
) {
12602 this.setStep( flag
? 1 : null );
12604 // Backward compatibility
12605 OO
.ui
.NumberInputWidget
.prototype.setIsInteger
= OO
.ui
.NumberInputWidget
.prototype.setAllowInteger
;
12607 // Backward compatibility
12608 OO
.ui
.NumberInputWidget
.prototype.getAllowInteger = function () {
12609 return this.step
=== 1;
12611 // Backward compatibility
12612 OO
.ui
.NumberInputWidget
.prototype.getIsInteger
= OO
.ui
.NumberInputWidget
.prototype.getAllowInteger
;
12615 * Set the range of allowed values
12617 * @param {number} min Minimum allowed value
12618 * @param {number} max Maximum allowed value
12620 OO
.ui
.NumberInputWidget
.prototype.setRange = function ( min
, max
) {
12622 throw new Error( 'Minimum (' + min
+ ') must not be greater than maximum (' + max
+ ')' );
12626 this.$input
.attr( 'min', this.min
);
12627 this.$input
.attr( 'max', this.max
);
12628 this.setValidityFlag();
12632 * Get the current range
12634 * @return {number[]} Minimum and maximum values
12636 OO
.ui
.NumberInputWidget
.prototype.getRange = function () {
12637 return [ this.min
, this.max
];
12641 * Set the stepping deltas
12643 * @param {number} [buttonStep=step||1] Delta when using the buttons or up/down arrow keys.
12644 * Defaults to `step` if specified, otherwise `1`.
12645 * @param {number} [pageStep=10*buttonStep] Delta when using the page-up/page-down keys.
12646 * Defaults to 10 times `buttonStep`.
12647 * @param {number|null} [step] If specified, the field only accepts values that are multiples of this.
12649 OO
.ui
.NumberInputWidget
.prototype.setStep = function ( buttonStep
, pageStep
, step
) {
12650 if ( buttonStep
=== undefined ) {
12651 buttonStep
= step
|| 1;
12653 if ( pageStep
=== undefined ) {
12654 pageStep
= 10 * buttonStep
;
12656 if ( step
!== null && step
<= 0 ) {
12657 throw new Error( 'Step value, if given, must be positive' );
12659 if ( buttonStep
<= 0 ) {
12660 throw new Error( 'Button step value must be positive' );
12662 if ( pageStep
<= 0 ) {
12663 throw new Error( 'Page step value must be positive' );
12666 this.buttonStep
= buttonStep
;
12667 this.pageStep
= pageStep
;
12668 this.$input
.attr( 'step', this.step
|| 'any' );
12669 this.setValidityFlag();
12675 OO
.ui
.NumberInputWidget
.prototype.setValue = function ( value
) {
12676 if ( value
=== '' ) {
12677 // Some browsers allow a value in the input even if there isn't one reported by $input.val()
12678 // so here we make sure an 'empty' value is actually displayed as such.
12679 this.$input
.val( '' );
12681 return OO
.ui
.NumberInputWidget
.parent
.prototype.setValue
.call( this, value
);
12685 * Get the current stepping values
12687 * @return {number[]} Button step, page step, and validity step
12689 OO
.ui
.NumberInputWidget
.prototype.getStep = function () {
12690 return [ this.buttonStep
, this.pageStep
, this.step
];
12694 * Get the current value of the widget as a number
12696 * @return {number} May be NaN, or an invalid number
12698 OO
.ui
.NumberInputWidget
.prototype.getNumericValue = function () {
12699 return +this.getValue();
12703 * Adjust the value of the widget
12705 * @param {number} delta Adjustment amount
12707 OO
.ui
.NumberInputWidget
.prototype.adjustValue = function ( delta
) {
12708 var n
, v
= this.getNumericValue();
12711 if ( isNaN( delta
) || !isFinite( delta
) ) {
12712 throw new Error( 'Delta must be a finite number' );
12715 if ( isNaN( v
) ) {
12719 n
= Math
.max( Math
.min( n
, this.max
), this.min
);
12721 n
= Math
.round( n
/ this.step
) * this.step
;
12726 this.setValue( n
);
12733 * @param {string} value Field value
12734 * @return {boolean}
12736 OO
.ui
.NumberInputWidget
.prototype.validateNumber = function ( value
) {
12738 if ( value
=== '' ) {
12739 return !this.isRequired();
12742 if ( isNaN( n
) || !isFinite( n
) ) {
12746 if ( this.step
&& Math
.floor( n
/ this.step
) !== n
/ this.step
) {
12750 if ( n
< this.min
|| n
> this.max
) {
12758 * Handle mouse click events.
12761 * @param {number} dir +1 or -1
12763 OO
.ui
.NumberInputWidget
.prototype.onButtonClick = function ( dir
) {
12764 this.adjustValue( dir
* this.buttonStep
);
12768 * Handle mouse wheel events.
12771 * @param {jQuery.Event} event
12772 * @return {undefined/boolean} False to prevent default if event is handled
12774 OO
.ui
.NumberInputWidget
.prototype.onWheel = function ( event
) {
12777 if ( !this.isDisabled() && this.$input
.is( ':focus' ) ) {
12778 // Standard 'wheel' event
12779 if ( event
.originalEvent
.deltaMode
!== undefined ) {
12780 this.sawWheelEvent
= true;
12782 if ( event
.originalEvent
.deltaY
) {
12783 delta
= -event
.originalEvent
.deltaY
;
12784 } else if ( event
.originalEvent
.deltaX
) {
12785 delta
= event
.originalEvent
.deltaX
;
12788 // Non-standard events
12789 if ( !this.sawWheelEvent
) {
12790 if ( event
.originalEvent
.wheelDeltaX
) {
12791 delta
= -event
.originalEvent
.wheelDeltaX
;
12792 } else if ( event
.originalEvent
.wheelDeltaY
) {
12793 delta
= event
.originalEvent
.wheelDeltaY
;
12794 } else if ( event
.originalEvent
.wheelDelta
) {
12795 delta
= event
.originalEvent
.wheelDelta
;
12796 } else if ( event
.originalEvent
.detail
) {
12797 delta
= -event
.originalEvent
.detail
;
12802 delta
= delta
< 0 ? -1 : 1;
12803 this.adjustValue( delta
* this.buttonStep
);
12811 * Handle key down events.
12814 * @param {jQuery.Event} e Key down event
12815 * @return {undefined/boolean} False to prevent default if event is handled
12817 OO
.ui
.NumberInputWidget
.prototype.onKeyDown = function ( e
) {
12818 if ( !this.isDisabled() ) {
12819 switch ( e
.which
) {
12820 case OO
.ui
.Keys
.UP
:
12821 this.adjustValue( this.buttonStep
);
12823 case OO
.ui
.Keys
.DOWN
:
12824 this.adjustValue( -this.buttonStep
);
12826 case OO
.ui
.Keys
.PAGEUP
:
12827 this.adjustValue( this.pageStep
);
12829 case OO
.ui
.Keys
.PAGEDOWN
:
12830 this.adjustValue( -this.pageStep
);
12839 OO
.ui
.NumberInputWidget
.prototype.setDisabled = function ( disabled
) {
12841 OO
.ui
.NumberInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
12843 if ( this.minusButton
) {
12844 this.minusButton
.setDisabled( this.isDisabled() );
12846 if ( this.plusButton
) {
12847 this.plusButton
.setDisabled( this.isDisabled() );
12855 //# sourceMappingURL=oojs-ui-core.js.map.json