3 * https://www.mediawiki.org/wiki/OOUI
5 * Copyright 2011–2018 OOUI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: 2018-11-08T22:38: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 the file selection widget's select file button
381 'ooui-selectfile-button-select': 'Select a file',
382 // Label for the file selection widget if file selection is not supported
383 'ooui-selectfile-not-supported': 'File selection is not supported',
384 // Label for the file selection widget when no file is currently selected
385 'ooui-selectfile-placeholder': 'No file is selected',
386 // Label for the file selection widget's drop target
387 'ooui-selectfile-dragdrop-placeholder': 'Drop file here',
388 // Label for the help icon attached to a form field
389 'ooui-field-help': 'Help'
393 * Get a localized message.
395 * After the message key, message parameters may optionally be passed. In the default implementation,
396 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
397 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
398 * they support unnamed, ordered message parameters.
400 * In environments that provide a localization system, this function should be overridden to
401 * return the message translated in the user's language. The default implementation always returns
402 * English messages. An example of doing this with [jQuery.i18n](https://github.com/wikimedia/jquery.i18n)
406 * var i, iLen, button,
407 * messagePath = 'oojs-ui/dist/i18n/',
408 * languages = [ $.i18n().locale, 'ur', 'en' ],
411 * for ( i = 0, iLen = languages.length; i < iLen; i++ ) {
412 * languageMap[ languages[ i ] ] = messagePath + languages[ i ].toLowerCase() + '.json';
415 * $.i18n().load( languageMap ).done( function() {
416 * // Replace the built-in `msg` only once we've loaded the internationalization.
417 * // OOUI uses `OO.ui.deferMsg` for all initially-loaded messages. So long as
418 * // you put off creating any widgets until this promise is complete, no English
419 * // will be displayed.
420 * OO.ui.msg = $.i18n;
422 * // A button displaying "OK" in the default locale
423 * button = new OO.ui.ButtonWidget( {
424 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
427 * $( 'body' ).append( button.$element );
429 * // A button displaying "OK" in Urdu
430 * $.i18n().locale = 'ur';
431 * button = new OO.ui.ButtonWidget( {
432 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
435 * $( 'body' ).append( button.$element );
438 * @param {string} key Message key
439 * @param {...Mixed} [params] Message parameters
440 * @return {string} Translated message with parameters substituted
442 OO
.ui
.msg = function ( key
) {
443 var message
= messages
[ key
],
444 params
= Array
.prototype.slice
.call( arguments
, 1 );
445 if ( typeof message
=== 'string' ) {
446 // Perform $1 substitution
447 message
= message
.replace( /\$(\d+)/g, function ( unused
, n
) {
448 var i
= parseInt( n
, 10 );
449 return params
[ i
- 1 ] !== undefined ? params
[ i
- 1 ] : '$' + n
;
452 // Return placeholder if message not found
453 message
= '[' + key
+ ']';
460 * Package a message and arguments for deferred resolution.
462 * Use this when you are statically specifying a message and the message may not yet be present.
464 * @param {string} key Message key
465 * @param {...Mixed} [params] Message parameters
466 * @return {Function} Function that returns the resolved message when executed
468 OO
.ui
.deferMsg = function () {
469 var args
= arguments
;
471 return OO
.ui
.msg
.apply( OO
.ui
, args
);
478 * If the message is a function it will be executed, otherwise it will pass through directly.
480 * @param {Function|string} msg Deferred message, or message text
481 * @return {string} Resolved message
483 OO
.ui
.resolveMsg = function ( msg
) {
484 if ( $.isFunction( msg
) ) {
491 * @param {string} url
494 OO
.ui
.isSafeUrl = function ( url
) {
495 // Keep this function in sync with php/Tag.php
496 var i
, protocolWhitelist
;
498 function stringStartsWith( haystack
, needle
) {
499 return haystack
.substr( 0, needle
.length
) === needle
;
502 protocolWhitelist
= [
503 'bitcoin', 'ftp', 'ftps', 'geo', 'git', 'gopher', 'http', 'https', 'irc', 'ircs',
504 'magnet', 'mailto', 'mms', 'news', 'nntp', 'redis', 'sftp', 'sip', 'sips', 'sms', 'ssh',
505 'svn', 'tel', 'telnet', 'urn', 'worldwind', 'xmpp'
512 for ( i
= 0; i
< protocolWhitelist
.length
; i
++ ) {
513 if ( stringStartsWith( url
, protocolWhitelist
[ i
] + ':' ) ) {
518 // This matches '//' too
519 if ( stringStartsWith( url
, '/' ) || stringStartsWith( url
, './' ) ) {
522 if ( stringStartsWith( url
, '?' ) || stringStartsWith( url
, '#' ) ) {
530 * Check if the user has a 'mobile' device.
532 * For our purposes this means the user is primarily using an
533 * on-screen keyboard, touch input instead of a mouse and may
534 * have a physically small display.
536 * It is left up to implementors to decide how to compute this
537 * so the default implementation always returns false.
539 * @return {boolean} User is on a mobile device
541 OO
.ui
.isMobile = function () {
546 * Get the additional spacing that should be taken into account when displaying elements that are
547 * clipped to the viewport, e.g. dropdown menus and popups. This is meant to be overridden to avoid
548 * such menus overlapping any fixed headers/toolbars/navigation used by the site.
550 * @return {Object} Object with the properties 'top', 'right', 'bottom', 'left', each representing
551 * the extra spacing from that edge of viewport (in pixels)
553 OO
.ui
.getViewportSpacing = function () {
563 * Get the default overlay, which is used by various widgets when they are passed `$overlay: true`.
564 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
566 * @return {jQuery} Default overlay node
568 OO
.ui
.getDefaultOverlay = function () {
569 if ( !OO
.ui
.$defaultOverlay
) {
570 OO
.ui
.$defaultOverlay
= $( '<div>' ).addClass( 'oo-ui-defaultOverlay' );
571 $( 'body' ).append( OO
.ui
.$defaultOverlay
);
573 return OO
.ui
.$defaultOverlay
;
581 * Namespace for OOUI mixins.
583 * Mixins are named according to the type of object they are intended to
584 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
585 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
586 * is intended to be mixed in to an instance of OO.ui.Widget.
594 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
595 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
596 * connected to them and can't be interacted with.
602 * @param {Object} [config] Configuration options
603 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
604 * to the top level (e.g., the outermost div) of the element. See the [OOUI documentation on MediaWiki][2]
606 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches#cssExample
607 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
608 * @cfg {string} [text] Text to insert
609 * @cfg {Array} [content] An array of content elements to append (after #text).
610 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
611 * Instances of OO.ui.Element will have their $element appended.
612 * @cfg {jQuery} [$content] Content elements to append (after #text).
613 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
614 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
615 * Data can also be specified with the #setData method.
617 OO
.ui
.Element
= function OoUiElement( config
) {
618 if ( OO
.ui
.isDemo
) {
619 this.initialConfig
= config
;
621 // Configuration initialization
622 config
= config
|| {};
626 this.elementId
= null;
628 this.data
= config
.data
;
629 this.$element
= config
.$element
||
630 $( document
.createElement( this.getTagName() ) );
631 this.elementGroup
= null;
634 if ( Array
.isArray( config
.classes
) ) {
635 this.$element
.addClass( config
.classes
);
638 this.setElementId( config
.id
);
641 this.$element
.text( config
.text
);
643 if ( config
.content
) {
644 // The `content` property treats plain strings as text; use an
645 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
646 // appropriate $element appended.
647 this.$element
.append( config
.content
.map( function ( v
) {
648 if ( typeof v
=== 'string' ) {
649 // Escape string so it is properly represented in HTML.
650 return document
.createTextNode( v
);
651 } else if ( v
instanceof OO
.ui
.HtmlSnippet
) {
654 } else if ( v
instanceof OO
.ui
.Element
) {
660 if ( config
.$content
) {
661 // The `$content` property treats plain strings as HTML.
662 this.$element
.append( config
.$content
);
668 OO
.initClass( OO
.ui
.Element
);
670 /* Static Properties */
673 * The name of the HTML tag used by the element.
675 * The static value may be ignored if the #getTagName method is overridden.
681 OO
.ui
.Element
.static.tagName
= 'div';
686 * Reconstitute a JavaScript object corresponding to a widget created
687 * by the PHP implementation.
689 * @param {string|HTMLElement|jQuery} idOrNode
690 * A DOM id (if a string) or node for the widget to infuse.
691 * @param {Object} [config] Configuration options
692 * @return {OO.ui.Element}
693 * The `OO.ui.Element` corresponding to this (infusable) document node.
694 * For `Tag` objects emitted on the HTML side (used occasionally for content)
695 * the value returned is a newly-created Element wrapping around the existing
698 OO
.ui
.Element
.static.infuse = function ( idOrNode
, config
) {
699 var obj
= OO
.ui
.Element
.static.unsafeInfuse( idOrNode
, config
, false );
700 // Verify that the type matches up.
701 // FIXME: uncomment after T89721 is fixed, see T90929.
703 if ( !( obj instanceof this['class'] ) ) {
704 throw new Error( 'Infusion type mismatch!' );
711 * Implementation helper for `infuse`; skips the type check and has an
712 * extra property so that only the top-level invocation touches the DOM.
715 * @param {string|HTMLElement|jQuery} idOrNode
716 * @param {Object} [config] Configuration options
717 * @param {jQuery.Promise} [domPromise] A promise that will be resolved
718 * when the top-level widget of this infusion is inserted into DOM,
719 * replacing the original node; only used internally.
720 * @return {OO.ui.Element}
722 OO
.ui
.Element
.static.unsafeInfuse = function ( idOrNode
, config
, domPromise
) {
723 // look for a cached result of a previous infusion.
724 var id
, $elem
, error
, data
, cls
, parts
, parent
, obj
, top
, state
, infusedChildren
;
725 if ( typeof idOrNode
=== 'string' ) {
727 $elem
= $( document
.getElementById( id
) );
729 $elem
= $( idOrNode
);
730 id
= $elem
.attr( 'id' );
732 if ( !$elem
.length
) {
733 if ( typeof idOrNode
=== 'string' ) {
734 error
= 'Widget not found: ' + idOrNode
;
735 } else if ( idOrNode
&& idOrNode
.selector
) {
736 error
= 'Widget not found: ' + idOrNode
.selector
;
738 error
= 'Widget not found';
740 throw new Error( error
);
742 if ( $elem
[ 0 ].oouiInfused
) {
743 $elem
= $elem
[ 0 ].oouiInfused
;
745 data
= $elem
.data( 'ooui-infused' );
748 if ( data
=== true ) {
749 throw new Error( 'Circular dependency! ' + id
);
752 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
753 state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
754 // restore dynamic state after the new element is re-inserted into DOM under infused parent
755 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
756 infusedChildren
= $elem
.data( 'ooui-infused-children' );
757 if ( infusedChildren
&& infusedChildren
.length
) {
758 infusedChildren
.forEach( function ( data
) {
759 var state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
760 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
766 data
= $elem
.attr( 'data-ooui' );
768 throw new Error( 'No infusion data found: ' + id
);
771 data
= JSON
.parse( data
);
775 if ( !( data
&& data
._
) ) {
776 throw new Error( 'No valid infusion data found: ' + id
);
778 if ( data
._
=== 'Tag' ) {
779 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
780 return new OO
.ui
.Element( $.extend( {}, config
, { $element
: $elem
} ) );
782 parts
= data
._
.split( '.' );
783 cls
= OO
.getProp
.apply( OO
, [ window
].concat( parts
) );
784 if ( cls
=== undefined ) {
785 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
788 // Verify that we're creating an OO.ui.Element instance
791 while ( parent
!== undefined ) {
792 if ( parent
=== OO
.ui
.Element
) {
797 parent
= parent
.parent
;
800 if ( parent
!== OO
.ui
.Element
) {
801 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
806 domPromise
= top
.promise();
808 $elem
.data( 'ooui-infused', true ); // prevent loops
809 data
.id
= id
; // implicit
810 infusedChildren
= [];
811 data
= OO
.copy( data
, null, function deserialize( value
) {
813 if ( OO
.isPlainObject( value
) ) {
815 infused
= OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, config
, domPromise
);
816 infusedChildren
.push( infused
);
817 // Flatten the structure
818 infusedChildren
.push
.apply( infusedChildren
, infused
.$element
.data( 'ooui-infused-children' ) || [] );
819 infused
.$element
.removeData( 'ooui-infused-children' );
822 if ( value
.html
!== undefined ) {
823 return new OO
.ui
.HtmlSnippet( value
.html
);
827 // allow widgets to reuse parts of the DOM
828 data
= cls
.static.reusePreInfuseDOM( $elem
[ 0 ], data
);
829 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
830 state
= cls
.static.gatherPreInfuseState( $elem
[ 0 ], data
);
832 // eslint-disable-next-line new-cap
833 obj
= new cls( $.extend( {}, config
, data
) );
834 // If anyone is holding a reference to the old DOM element,
835 // let's allow them to OO.ui.infuse() it and do what they expect, see T105828.
836 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
837 $elem
[ 0 ].oouiInfused
= obj
.$element
;
838 // now replace old DOM with this new DOM.
840 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
841 // so only mutate the DOM if we need to.
842 if ( $elem
[ 0 ] !== obj
.$element
[ 0 ] ) {
843 $elem
.replaceWith( obj
.$element
);
847 obj
.$element
.data( 'ooui-infused', obj
);
848 obj
.$element
.data( 'ooui-infused-children', infusedChildren
);
849 // set the 'data-ooui' attribute so we can identify infused widgets
850 obj
.$element
.attr( 'data-ooui', '' );
851 // restore dynamic state after the new element is inserted into DOM
852 domPromise
.done( obj
.restorePreInfuseState
.bind( obj
, state
) );
857 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
859 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
860 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
861 * constructor, which will be given the enhanced config.
864 * @param {HTMLElement} node
865 * @param {Object} config
868 OO
.ui
.Element
.static.reusePreInfuseDOM = function ( node
, config
) {
873 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of an HTML DOM node
874 * (and its children) that represent an Element of the same class and the given configuration,
875 * generated by the PHP implementation.
877 * This method is called just before `node` is detached from the DOM. The return value of this
878 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
879 * is inserted into DOM to replace `node`.
882 * @param {HTMLElement} node
883 * @param {Object} config
886 OO
.ui
.Element
.static.gatherPreInfuseState = function () {
891 * Get a jQuery function within a specific document.
894 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
895 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
897 * @return {Function} Bound jQuery function
899 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
900 function wrapper( selector
) {
901 return $( selector
, wrapper
.context
);
904 wrapper
.context
= this.getDocument( context
);
907 wrapper
.$iframe
= $iframe
;
914 * Get the document of an element.
917 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
918 * @return {HTMLDocument|null} Document object
920 OO
.ui
.Element
.static.getDocument = function ( obj
) {
921 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
922 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
923 // Empty jQuery selections might have a context
930 ( obj
.nodeType
=== Node
.DOCUMENT_NODE
&& obj
) ||
935 * Get the window of an element or document.
938 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
939 * @return {Window} Window object
941 OO
.ui
.Element
.static.getWindow = function ( obj
) {
942 var doc
= this.getDocument( obj
);
943 return doc
.defaultView
;
947 * Get the direction of an element or document.
950 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
951 * @return {string} Text direction, either 'ltr' or 'rtl'
953 OO
.ui
.Element
.static.getDir = function ( obj
) {
956 if ( obj
instanceof jQuery
) {
959 isDoc
= obj
.nodeType
=== Node
.DOCUMENT_NODE
;
960 isWin
= obj
.document
!== undefined;
961 if ( isDoc
|| isWin
) {
967 return $( obj
).css( 'direction' );
971 * Get the offset between two frames.
973 * TODO: Make this function not use recursion.
976 * @param {Window} from Window of the child frame
977 * @param {Window} [to=window] Window of the parent frame
978 * @param {Object} [offset] Offset to start with, used internally
979 * @return {Object} Offset object, containing left and top properties
981 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
982 var i
, len
, frames
, frame
, rect
;
988 offset
= { top
: 0, left
: 0 };
990 if ( from.parent
=== from ) {
994 // Get iframe element
995 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
996 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
997 if ( frames
[ i
].contentWindow
=== from ) {
1003 // Recursively accumulate offset values
1005 rect
= frame
.getBoundingClientRect();
1006 offset
.left
+= rect
.left
;
1007 offset
.top
+= rect
.top
;
1008 if ( from !== to
) {
1009 this.getFrameOffset( from.parent
, offset
);
1016 * Get the offset between two elements.
1018 * The two elements may be in a different frame, but in that case the frame $element is in must
1019 * be contained in the frame $anchor is in.
1022 * @param {jQuery} $element Element whose position to get
1023 * @param {jQuery} $anchor Element to get $element's position relative to
1024 * @return {Object} Translated position coordinates, containing top and left properties
1026 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
1027 var iframe
, iframePos
,
1028 pos
= $element
.offset(),
1029 anchorPos
= $anchor
.offset(),
1030 elementDocument
= this.getDocument( $element
),
1031 anchorDocument
= this.getDocument( $anchor
);
1033 // If $element isn't in the same document as $anchor, traverse up
1034 while ( elementDocument
!== anchorDocument
) {
1035 iframe
= elementDocument
.defaultView
.frameElement
;
1037 throw new Error( '$element frame is not contained in $anchor frame' );
1039 iframePos
= $( iframe
).offset();
1040 pos
.left
+= iframePos
.left
;
1041 pos
.top
+= iframePos
.top
;
1042 elementDocument
= iframe
.ownerDocument
;
1044 pos
.left
-= anchorPos
.left
;
1045 pos
.top
-= anchorPos
.top
;
1050 * Get element border sizes.
1053 * @param {HTMLElement} el Element to measure
1054 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1056 OO
.ui
.Element
.static.getBorders = function ( el
) {
1057 var doc
= el
.ownerDocument
,
1058 win
= doc
.defaultView
,
1059 style
= win
.getComputedStyle( el
, null ),
1061 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
1062 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
1063 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
1064 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
1075 * Get dimensions of an element or window.
1078 * @param {HTMLElement|Window} el Element to measure
1079 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1081 OO
.ui
.Element
.static.getDimensions = function ( el
) {
1083 doc
= el
.ownerDocument
|| el
.document
,
1084 win
= doc
.defaultView
;
1086 if ( win
=== el
|| el
=== doc
.documentElement
) {
1089 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
1091 top
: $win
.scrollTop(),
1092 left
: $win
.scrollLeft()
1094 scrollbar
: { right
: 0, bottom
: 0 },
1098 bottom
: $win
.innerHeight(),
1099 right
: $win
.innerWidth()
1105 borders
: this.getBorders( el
),
1107 top
: $el
.scrollTop(),
1108 left
: $el
.scrollLeft()
1111 right
: $el
.innerWidth() - el
.clientWidth
,
1112 bottom
: $el
.innerHeight() - el
.clientHeight
1114 rect
: el
.getBoundingClientRect()
1120 * Get the number of pixels that an element's content is scrolled to the left.
1122 * Adapted from <https://github.com/othree/jquery.rtl-scroll-type>.
1123 * Original code copyright 2012 Wei-Ko Kao, licensed under the MIT License.
1125 * This function smooths out browser inconsistencies (nicely described in the README at
1126 * <https://github.com/othree/jquery.rtl-scroll-type>) and produces a result consistent
1127 * with Firefox's 'scrollLeft', which seems the sanest.
1131 * @param {HTMLElement|Window} el Element to measure
1132 * @return {number} Scroll position from the left.
1133 * If the element's direction is LTR, this is a positive number between `0` (initial scroll position)
1134 * and `el.scrollWidth - el.clientWidth` (furthest possible scroll position).
1135 * If the element's direction is RTL, this is a negative number between `0` (initial scroll position)
1136 * and `-el.scrollWidth + el.clientWidth` (furthest possible scroll position).
1138 OO
.ui
.Element
.static.getScrollLeft
= ( function () {
1139 var rtlScrollType
= null;
1142 var $definer
= $( '<div dir="rtl" style="font-size: 14px; width: 1px; height: 1px; position: absolute; top: -1000px; overflow: scroll">A</div>' ),
1143 definer
= $definer
[ 0 ];
1145 $definer
.appendTo( 'body' );
1146 if ( definer
.scrollLeft
> 0 ) {
1148 rtlScrollType
= 'default';
1150 definer
.scrollLeft
= 1;
1151 if ( definer
.scrollLeft
=== 0 ) {
1152 // Firefox, old Opera
1153 rtlScrollType
= 'negative';
1155 // Internet Explorer, Edge
1156 rtlScrollType
= 'reverse';
1162 return function getScrollLeft( el
) {
1163 var isRoot
= el
.window
=== el
||
1164 el
=== el
.ownerDocument
.body
||
1165 el
=== el
.ownerDocument
.documentElement
,
1166 scrollLeft
= isRoot
? $( window
).scrollLeft() : el
.scrollLeft
,
1167 // All browsers use the correct scroll type ('negative') on the root, so don't
1168 // do any fixups when looking at the root element
1169 direction
= isRoot
? 'ltr' : $( el
).css( 'direction' );
1171 if ( direction
=== 'rtl' ) {
1172 if ( rtlScrollType
=== null ) {
1175 if ( rtlScrollType
=== 'reverse' ) {
1176 scrollLeft
= -scrollLeft
;
1177 } else if ( rtlScrollType
=== 'default' ) {
1178 scrollLeft
= scrollLeft
- el
.scrollWidth
+ el
.clientWidth
;
1187 * Get the root scrollable element of given element's document.
1189 * On Blink-based browsers (Chrome etc.), `document.documentElement` can't be used to get or set
1190 * the scrollTop property; instead we have to use `document.body`. Changing and testing the value
1191 * lets us use 'body' or 'documentElement' based on what is working.
1193 * https://code.google.com/p/chromium/issues/detail?id=303131
1196 * @param {HTMLElement} el Element to find root scrollable parent for
1197 * @return {HTMLElement} Scrollable parent, `document.body` or `document.documentElement`
1198 * depending on browser
1200 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1201 var scrollTop
, body
;
1203 if ( OO
.ui
.scrollableElement
=== undefined ) {
1204 body
= el
.ownerDocument
.body
;
1205 scrollTop
= body
.scrollTop
;
1208 // In some browsers (observed in Chrome 56 on Linux Mint 18.1),
1209 // body.scrollTop doesn't become exactly 1, but a fractional value like 0.76
1210 if ( Math
.round( body
.scrollTop
) === 1 ) {
1211 body
.scrollTop
= scrollTop
;
1212 OO
.ui
.scrollableElement
= 'body';
1214 OO
.ui
.scrollableElement
= 'documentElement';
1218 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1222 * Get closest scrollable container.
1224 * Traverses up until either a scrollable element or the root is reached, in which case the root
1225 * scrollable element will be returned (see #getRootScrollableElement).
1228 * @param {HTMLElement} el Element to find scrollable container for
1229 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1230 * @return {HTMLElement} Closest scrollable container
1232 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1234 // Browsers do not correctly return the computed value of 'overflow' when 'overflow-x' and
1235 // 'overflow-y' have different values, so we need to check the separate properties.
1236 props
= [ 'overflow-x', 'overflow-y' ],
1237 $parent
= $( el
).parent();
1239 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1240 props
= [ 'overflow-' + dimension
];
1243 // Special case for the document root (which doesn't really have any scrollable container, since
1244 // it is the ultimate scrollable container, but this is probably saner than null or exception)
1245 if ( $( el
).is( 'html, body' ) ) {
1246 return this.getRootScrollableElement( el
);
1249 while ( $parent
.length
) {
1250 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1251 return $parent
[ 0 ];
1255 val
= $parent
.css( props
[ i
] );
1256 // We assume that elements with 'overflow' (in any direction) set to 'hidden' will never be
1257 // scrolled in that direction, but they can actually be scrolled programatically. The user can
1258 // unintentionally perform a scroll in such case even if the application doesn't scroll
1259 // programatically, e.g. when jumping to an anchor, or when using built-in find functionality.
1260 // This could cause funny issues...
1261 if ( val
=== 'auto' || val
=== 'scroll' ) {
1262 return $parent
[ 0 ];
1265 $parent
= $parent
.parent();
1267 // The element is unattached... return something mostly sane
1268 return this.getRootScrollableElement( el
);
1272 * Scroll element into view.
1275 * @param {HTMLElement} el Element to scroll into view
1276 * @param {Object} [config] Configuration options
1277 * @param {string} [config.duration='fast'] jQuery animation duration value
1278 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1279 * to scroll in both directions
1280 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1282 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1283 var position
, animations
, container
, $container
, elementDimensions
, containerDimensions
, $window
,
1284 deferred
= $.Deferred();
1286 // Configuration initialization
1287 config
= config
|| {};
1290 container
= this.getClosestScrollableContainer( el
, config
.direction
);
1291 $container
= $( container
);
1292 elementDimensions
= this.getDimensions( el
);
1293 containerDimensions
= this.getDimensions( container
);
1294 $window
= $( this.getWindow( el
) );
1296 // Compute the element's position relative to the container
1297 if ( $container
.is( 'html, body' ) ) {
1298 // If the scrollable container is the root, this is easy
1300 top
: elementDimensions
.rect
.top
,
1301 bottom
: $window
.innerHeight() - elementDimensions
.rect
.bottom
,
1302 left
: elementDimensions
.rect
.left
,
1303 right
: $window
.innerWidth() - elementDimensions
.rect
.right
1306 // Otherwise, we have to subtract el's coordinates from container's coordinates
1308 top
: elementDimensions
.rect
.top
- ( containerDimensions
.rect
.top
+ containerDimensions
.borders
.top
),
1309 bottom
: containerDimensions
.rect
.bottom
- containerDimensions
.borders
.bottom
- containerDimensions
.scrollbar
.bottom
- elementDimensions
.rect
.bottom
,
1310 left
: elementDimensions
.rect
.left
- ( containerDimensions
.rect
.left
+ containerDimensions
.borders
.left
),
1311 right
: containerDimensions
.rect
.right
- containerDimensions
.borders
.right
- containerDimensions
.scrollbar
.right
- elementDimensions
.rect
.right
1315 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1316 if ( position
.top
< 0 ) {
1317 animations
.scrollTop
= containerDimensions
.scroll
.top
+ position
.top
;
1318 } else if ( position
.top
> 0 && position
.bottom
< 0 ) {
1319 animations
.scrollTop
= containerDimensions
.scroll
.top
+ Math
.min( position
.top
, -position
.bottom
);
1322 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1323 if ( position
.left
< 0 ) {
1324 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ position
.left
;
1325 } else if ( position
.left
> 0 && position
.right
< 0 ) {
1326 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ Math
.min( position
.left
, -position
.right
);
1329 if ( !$.isEmptyObject( animations
) ) {
1330 $container
.stop( true ).animate( animations
, config
.duration
=== undefined ? 'fast' : config
.duration
);
1331 $container
.queue( function ( next
) {
1338 return deferred
.promise();
1342 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1343 * and reserve space for them, because it probably doesn't.
1345 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1346 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1347 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1348 * and then reattach (or show) them back.
1351 * @param {HTMLElement} el Element to reconsider the scrollbars on
1353 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1354 var i
, len
, scrollLeft
, scrollTop
, nodes
= [];
1355 // Save scroll position
1356 scrollLeft
= el
.scrollLeft
;
1357 scrollTop
= el
.scrollTop
;
1358 // Detach all children
1359 while ( el
.firstChild
) {
1360 nodes
.push( el
.firstChild
);
1361 el
.removeChild( el
.firstChild
);
1364 void el
.offsetHeight
;
1365 // Reattach all children
1366 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1367 el
.appendChild( nodes
[ i
] );
1369 // Restore scroll position (no-op if scrollbars disappeared)
1370 el
.scrollLeft
= scrollLeft
;
1371 el
.scrollTop
= scrollTop
;
1377 * Toggle visibility of an element.
1379 * @param {boolean} [show] Make element visible, omit to toggle visibility
1382 * @return {OO.ui.Element} The element, for chaining
1384 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1385 show
= show
=== undefined ? !this.visible
: !!show
;
1387 if ( show
!== this.isVisible() ) {
1388 this.visible
= show
;
1389 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1390 this.emit( 'toggle', show
);
1397 * Check if element is visible.
1399 * @return {boolean} element is visible
1401 OO
.ui
.Element
.prototype.isVisible = function () {
1402 return this.visible
;
1408 * @return {Mixed} Element data
1410 OO
.ui
.Element
.prototype.getData = function () {
1417 * @param {Mixed} data Element data
1419 * @return {OO.ui.Element} The element, for chaining
1421 OO
.ui
.Element
.prototype.setData = function ( data
) {
1427 * Set the element has an 'id' attribute.
1429 * @param {string} id
1431 * @return {OO.ui.Element} The element, for chaining
1433 OO
.ui
.Element
.prototype.setElementId = function ( id
) {
1434 this.elementId
= id
;
1435 this.$element
.attr( 'id', id
);
1440 * Ensure that the element has an 'id' attribute, setting it to an unique value if it's missing,
1441 * and return its value.
1445 OO
.ui
.Element
.prototype.getElementId = function () {
1446 if ( this.elementId
=== null ) {
1447 this.setElementId( OO
.ui
.generateElementId() );
1449 return this.elementId
;
1453 * Check if element supports one or more methods.
1455 * @param {string|string[]} methods Method or list of methods to check
1456 * @return {boolean} All methods are supported
1458 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1462 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1463 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1464 if ( $.isFunction( this[ methods
[ i
] ] ) ) {
1469 return methods
.length
=== support
;
1473 * Update the theme-provided classes.
1475 * @localdoc This is called in element mixins and widget classes any time state changes.
1476 * Updating is debounced, minimizing overhead of changing multiple attributes and
1477 * guaranteeing that theme updates do not occur within an element's constructor
1479 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1480 OO
.ui
.theme
.queueUpdateElementClasses( this );
1484 * Get the HTML tag name.
1486 * Override this method to base the result on instance information.
1488 * @return {string} HTML tag name
1490 OO
.ui
.Element
.prototype.getTagName = function () {
1491 return this.constructor.static.tagName
;
1495 * Check if the element is attached to the DOM
1497 * @return {boolean} The element is attached to the DOM
1499 OO
.ui
.Element
.prototype.isElementAttached = function () {
1500 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1504 * Get the DOM document.
1506 * @return {HTMLDocument} Document object
1508 OO
.ui
.Element
.prototype.getElementDocument = function () {
1509 // Don't cache this in other ways either because subclasses could can change this.$element
1510 return OO
.ui
.Element
.static.getDocument( this.$element
);
1514 * Get the DOM window.
1516 * @return {Window} Window object
1518 OO
.ui
.Element
.prototype.getElementWindow = function () {
1519 return OO
.ui
.Element
.static.getWindow( this.$element
);
1523 * Get closest scrollable container.
1525 * @return {HTMLElement} Closest scrollable container
1527 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1528 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1532 * Get group element is in.
1534 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1536 OO
.ui
.Element
.prototype.getElementGroup = function () {
1537 return this.elementGroup
;
1541 * Set group element is in.
1543 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1545 * @return {OO.ui.Element} The element, for chaining
1547 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1548 this.elementGroup
= group
;
1553 * Scroll element into view.
1555 * @param {Object} [config] Configuration options
1556 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1558 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1560 !this.isElementAttached() ||
1561 !this.isVisible() ||
1562 ( this.getElementGroup() && !this.getElementGroup().isVisible() )
1564 return $.Deferred().resolve();
1566 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1570 * Restore the pre-infusion dynamic state for this widget.
1572 * This method is called after #$element has been inserted into DOM. The parameter is the return
1573 * value of #gatherPreInfuseState.
1576 * @param {Object} state
1578 OO
.ui
.Element
.prototype.restorePreInfuseState = function () {
1582 * Wraps an HTML snippet for use with configuration values which default
1583 * to strings. This bypasses the default html-escaping done to string
1589 * @param {string} [content] HTML content
1591 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
1593 this.content
= content
;
1598 OO
.initClass( OO
.ui
.HtmlSnippet
);
1605 * @return {string} Unchanged HTML snippet.
1607 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
1608 return this.content
;
1612 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1613 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1614 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1615 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1616 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1620 * @extends OO.ui.Element
1621 * @mixins OO.EventEmitter
1624 * @param {Object} [config] Configuration options
1626 OO
.ui
.Layout
= function OoUiLayout( config
) {
1627 // Configuration initialization
1628 config
= config
|| {};
1630 // Parent constructor
1631 OO
.ui
.Layout
.parent
.call( this, config
);
1633 // Mixin constructors
1634 OO
.EventEmitter
.call( this );
1637 this.$element
.addClass( 'oo-ui-layout' );
1642 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1643 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1648 * Reset scroll offsets
1651 * @return {OO.ui.Layout} The layout, for chaining
1653 OO
.ui
.Layout
.prototype.resetScroll = function () {
1654 this.$element
[ 0 ].scrollTop
= 0;
1655 // TODO: Reset scrollLeft in an RTL-aware manner, see OO.ui.Element.static.getScrollLeft.
1661 * Widgets are compositions of one or more OOUI elements that users can both view
1662 * and interact with. All widgets can be configured and modified via a standard API,
1663 * and their state can change dynamically according to a model.
1667 * @extends OO.ui.Element
1668 * @mixins OO.EventEmitter
1671 * @param {Object} [config] Configuration options
1672 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1673 * appearance reflects this state.
1675 OO
.ui
.Widget
= function OoUiWidget( config
) {
1676 // Initialize config
1677 config
= $.extend( { disabled
: false }, config
);
1679 // Parent constructor
1680 OO
.ui
.Widget
.parent
.call( this, config
);
1682 // Mixin constructors
1683 OO
.EventEmitter
.call( this );
1686 this.disabled
= null;
1687 this.wasDisabled
= null;
1690 this.$element
.addClass( 'oo-ui-widget' );
1691 this.setDisabled( !!config
.disabled
);
1696 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1697 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1704 * A 'disable' event is emitted when the disabled state of the widget changes
1705 * (i.e. on disable **and** enable).
1707 * @param {boolean} disabled Widget is disabled
1713 * A 'toggle' event is emitted when the visibility of the widget changes.
1715 * @param {boolean} visible Widget is visible
1721 * Check if the widget is disabled.
1723 * @return {boolean} Widget is disabled
1725 OO
.ui
.Widget
.prototype.isDisabled = function () {
1726 return this.disabled
;
1730 * Set the 'disabled' state of the widget.
1732 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1734 * @param {boolean} disabled Disable widget
1736 * @return {OO.ui.Widget} The widget, for chaining
1738 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
1741 this.disabled
= !!disabled
;
1742 isDisabled
= this.isDisabled();
1743 if ( isDisabled
!== this.wasDisabled
) {
1744 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
1745 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
1746 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
1747 this.emit( 'disable', isDisabled
);
1748 this.updateThemeClasses();
1750 this.wasDisabled
= isDisabled
;
1756 * Update the disabled state, in case of changes in parent widget.
1759 * @return {OO.ui.Widget} The widget, for chaining
1761 OO
.ui
.Widget
.prototype.updateDisabled = function () {
1762 this.setDisabled( this.disabled
);
1767 * Get an ID of a labelable node which is part of this widget, if any, to be used for `<label for>`
1770 * If this function returns null, the widget should have a meaningful #simulateLabelClick method
1773 * @return {string|null} The ID of the labelable element
1775 OO
.ui
.Widget
.prototype.getInputId = function () {
1780 * Simulate the behavior of clicking on a label (a HTML `<label>` element) bound to this input.
1781 * HTML only allows `<label>` to act on specific "labelable" elements; complex widgets might need to
1782 * override this method to provide intuitive, accessible behavior.
1784 * By default, this does nothing. OO.ui.mixin.TabIndexedElement overrides it for focusable widgets.
1785 * Individual widgets may override it too.
1787 * This method is called by OO.ui.LabelWidget and OO.ui.FieldLayout. It should not be called
1790 OO
.ui
.Widget
.prototype.simulateLabelClick = function () {
1801 OO
.ui
.Theme
= function OoUiTheme() {
1802 this.elementClassesQueue
= [];
1803 this.debouncedUpdateQueuedElementClasses
= OO
.ui
.debounce( this.updateQueuedElementClasses
);
1808 OO
.initClass( OO
.ui
.Theme
);
1813 * Get a list of classes to be applied to a widget.
1815 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
1816 * otherwise state transitions will not work properly.
1818 * @param {OO.ui.Element} element Element for which to get classes
1819 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1821 OO
.ui
.Theme
.prototype.getElementClasses = function () {
1822 return { on
: [], off
: [] };
1826 * Update CSS classes provided by the theme.
1828 * For elements with theme logic hooks, this should be called any time there's a state change.
1830 * @param {OO.ui.Element} element Element for which to update classes
1832 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
1833 var $elements
= $( [] ),
1834 classes
= this.getElementClasses( element
);
1836 if ( element
.$icon
) {
1837 $elements
= $elements
.add( element
.$icon
);
1839 if ( element
.$indicator
) {
1840 $elements
= $elements
.add( element
.$indicator
);
1844 .removeClass( classes
.off
)
1845 .addClass( classes
.on
);
1851 OO
.ui
.Theme
.prototype.updateQueuedElementClasses = function () {
1853 for ( i
= 0; i
< this.elementClassesQueue
.length
; i
++ ) {
1854 this.updateElementClasses( this.elementClassesQueue
[ i
] );
1857 this.elementClassesQueue
= [];
1861 * Queue #updateElementClasses to be called for this element.
1863 * @localdoc QUnit tests override this method to directly call #queueUpdateElementClasses,
1864 * to make them synchronous.
1866 * @param {OO.ui.Element} element Element for which to update classes
1868 OO
.ui
.Theme
.prototype.queueUpdateElementClasses = function ( element
) {
1869 // Keep items in the queue unique. Use lastIndexOf to start checking from the end because that's
1870 // the most common case (this method is often called repeatedly for the same element).
1871 if ( this.elementClassesQueue
.lastIndexOf( element
) !== -1 ) {
1874 this.elementClassesQueue
.push( element
);
1875 this.debouncedUpdateQueuedElementClasses();
1879 * Get the transition duration in milliseconds for dialogs opening/closing
1881 * The dialog should be fully rendered this many milliseconds after the
1882 * ready process has executed.
1884 * @return {number} Transition duration in milliseconds
1886 OO
.ui
.Theme
.prototype.getDialogTransitionDuration = function () {
1891 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
1892 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
1893 * order in which users will navigate through the focusable elements via the "tab" key.
1896 * // TabIndexedElement is mixed into the ButtonWidget class
1897 * // to provide a tabIndex property.
1898 * var button1 = new OO.ui.ButtonWidget( {
1902 * var button2 = new OO.ui.ButtonWidget( {
1906 * var button3 = new OO.ui.ButtonWidget( {
1910 * var button4 = new OO.ui.ButtonWidget( {
1914 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
1920 * @param {Object} [config] Configuration options
1921 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
1922 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
1923 * functionality will be applied to it instead.
1924 * @cfg {string|number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
1925 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
1926 * to remove the element from the tab-navigation flow.
1928 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
1929 // Configuration initialization
1930 config
= $.extend( { tabIndex
: 0 }, config
);
1933 this.$tabIndexed
= null;
1934 this.tabIndex
= null;
1937 this.connect( this, { disable
: 'onTabIndexedElementDisable' } );
1940 this.setTabIndex( config
.tabIndex
);
1941 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
1946 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
1951 * Set the element that should use the tabindex functionality.
1953 * This method is used to retarget a tabindex mixin so that its functionality applies
1954 * to the specified element. If an element is currently using the functionality, the mixin’s
1955 * effect on that element is removed before the new element is set up.
1957 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
1959 * @return {OO.ui.Element} The element, for chaining
1961 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
1962 var tabIndex
= this.tabIndex
;
1963 // Remove attributes from old $tabIndexed
1964 this.setTabIndex( null );
1965 // Force update of new $tabIndexed
1966 this.$tabIndexed
= $tabIndexed
;
1967 this.tabIndex
= tabIndex
;
1968 return this.updateTabIndex();
1972 * Set the value of the tabindex.
1974 * @param {string|number|null} tabIndex Tabindex value, or `null` for no tabindex
1976 * @return {OO.ui.Element} The element, for chaining
1978 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
1979 tabIndex
= /^-?\d+$/.test( tabIndex
) ? Number( tabIndex
) : null;
1981 if ( this.tabIndex
!== tabIndex
) {
1982 this.tabIndex
= tabIndex
;
1983 this.updateTabIndex();
1990 * Update the `tabindex` attribute, in case of changes to tab index or
1995 * @return {OO.ui.Element} The element, for chaining
1997 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
1998 if ( this.$tabIndexed
) {
1999 if ( this.tabIndex
!== null ) {
2000 // Do not index over disabled elements
2001 this.$tabIndexed
.attr( {
2002 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
2003 // Support: ChromeVox and NVDA
2004 // These do not seem to inherit aria-disabled from parent elements
2005 'aria-disabled': this.isDisabled().toString()
2008 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
2015 * Handle disable events.
2018 * @param {boolean} disabled Element is disabled
2020 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
2021 this.updateTabIndex();
2025 * Get the value of the tabindex.
2027 * @return {number|null} Tabindex value
2029 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
2030 return this.tabIndex
;
2034 * Get an ID of a focusable element of this widget, if any, to be used for `<label for>` value.
2036 * If the element already has an ID then that is returned, otherwise unique ID is
2037 * generated, set on the element, and returned.
2039 * @return {string|null} The ID of the focusable element
2041 OO
.ui
.mixin
.TabIndexedElement
.prototype.getInputId = function () {
2044 if ( !this.$tabIndexed
) {
2047 if ( !this.isLabelableNode( this.$tabIndexed
) ) {
2051 id
= this.$tabIndexed
.attr( 'id' );
2052 if ( id
=== undefined ) {
2053 id
= OO
.ui
.generateElementId();
2054 this.$tabIndexed
.attr( 'id', id
);
2061 * Whether the node is 'labelable' according to the HTML spec
2062 * (i.e., whether it can be interacted with through a `<label for="…">`).
2063 * See: <https://html.spec.whatwg.org/multipage/forms.html#category-label>.
2066 * @param {jQuery} $node
2069 OO
.ui
.mixin
.TabIndexedElement
.prototype.isLabelableNode = function ( $node
) {
2071 labelableTags
= [ 'button', 'meter', 'output', 'progress', 'select', 'textarea' ],
2072 tagName
= $node
.prop( 'tagName' ).toLowerCase();
2074 if ( tagName
=== 'input' && $node
.attr( 'type' ) !== 'hidden' ) {
2077 if ( labelableTags
.indexOf( tagName
) !== -1 ) {
2084 * Focus this element.
2087 * @return {OO.ui.Element} The element, for chaining
2089 OO
.ui
.mixin
.TabIndexedElement
.prototype.focus = function () {
2090 if ( !this.isDisabled() ) {
2091 this.$tabIndexed
.focus();
2097 * Blur this element.
2100 * @return {OO.ui.Element} The element, for chaining
2102 OO
.ui
.mixin
.TabIndexedElement
.prototype.blur = function () {
2103 this.$tabIndexed
.blur();
2108 * @inheritdoc OO.ui.Widget
2110 OO
.ui
.mixin
.TabIndexedElement
.prototype.simulateLabelClick = function () {
2115 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
2116 * interface element that can be configured with access keys for accessibility.
2117 * See the [OOUI documentation on MediaWiki] [1] for examples.
2119 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches#Buttons
2125 * @param {Object} [config] Configuration options
2126 * @cfg {jQuery} [$button] The button element created by the class.
2127 * If this configuration is omitted, the button element will use a generated `<a>`.
2128 * @cfg {boolean} [framed=true] Render the button with a frame
2130 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
2131 // Configuration initialization
2132 config
= config
|| {};
2135 this.$button
= null;
2137 this.active
= config
.active
!== undefined && config
.active
;
2138 this.onDocumentMouseUpHandler
= this.onDocumentMouseUp
.bind( this );
2139 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
2140 this.onDocumentKeyUpHandler
= this.onDocumentKeyUp
.bind( this );
2141 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
2142 this.onClickHandler
= this.onClick
.bind( this );
2143 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
2146 this.$element
.addClass( 'oo-ui-buttonElement' );
2147 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
2148 this.setButtonElement( config
.$button
|| $( '<a>' ) );
2153 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
2155 /* Static Properties */
2158 * Cancel mouse down events.
2160 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
2161 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
2162 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
2167 * @property {boolean}
2169 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
2174 * A 'click' event is emitted when the button element is clicked.
2182 * Set the button element.
2184 * This method is used to retarget a button mixin so that its functionality applies to
2185 * the specified button element instead of the one created by the class. If a button element
2186 * is already set, the method will remove the mixin’s effect on that element.
2188 * @param {jQuery} $button Element to use as button
2190 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
2191 if ( this.$button
) {
2193 .removeClass( 'oo-ui-buttonElement-button' )
2194 .removeAttr( 'role accesskey' )
2196 mousedown
: this.onMouseDownHandler
,
2197 keydown
: this.onKeyDownHandler
,
2198 click
: this.onClickHandler
,
2199 keypress
: this.onKeyPressHandler
2203 this.$button
= $button
2204 .addClass( 'oo-ui-buttonElement-button' )
2206 mousedown
: this.onMouseDownHandler
,
2207 keydown
: this.onKeyDownHandler
,
2208 click
: this.onClickHandler
,
2209 keypress
: this.onKeyPressHandler
2212 // Add `role="button"` on `<a>` elements, where it's needed
2213 // `toUpperCase()` is added for XHTML documents
2214 if ( this.$button
.prop( 'tagName' ).toUpperCase() === 'A' ) {
2215 this.$button
.attr( 'role', 'button' );
2220 * Handles mouse down events.
2223 * @param {jQuery.Event} e Mouse down event
2224 * @return {undefined/boolean} False to prevent default if event is handled
2226 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
2227 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
2230 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
2231 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
2232 // reliably remove the pressed class
2233 this.getElementDocument().addEventListener( 'mouseup', this.onDocumentMouseUpHandler
, true );
2234 // Prevent change of focus unless specifically configured otherwise
2235 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
2241 * Handles document mouse up events.
2244 * @param {MouseEvent} e Mouse up event
2246 OO
.ui
.mixin
.ButtonElement
.prototype.onDocumentMouseUp = function ( e
) {
2247 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
2250 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
2251 // Stop listening for mouseup, since we only needed this once
2252 this.getElementDocument().removeEventListener( 'mouseup', this.onDocumentMouseUpHandler
, true );
2255 // Deprecated alias since 0.28.3
2256 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp = function () {
2257 OO
.ui
.warnDeprecation( 'onMouseUp is deprecated, use onDocumentMouseUp instead' );
2258 this.onDocumentMouseUp
.apply( this, arguments
);
2262 * Handles mouse click events.
2265 * @param {jQuery.Event} e Mouse click event
2267 * @return {undefined/boolean} False to prevent default if event is handled
2269 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
2270 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
2271 if ( this.emit( 'click' ) ) {
2278 * Handles key down events.
2281 * @param {jQuery.Event} e Key down event
2283 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
2284 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2287 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
2288 // Run the keyup handler no matter where the key is when the button is let go, so we can
2289 // reliably remove the pressed class
2290 this.getElementDocument().addEventListener( 'keyup', this.onDocumentKeyUpHandler
, true );
2294 * Handles document key up events.
2297 * @param {KeyboardEvent} e Key up event
2299 OO
.ui
.mixin
.ButtonElement
.prototype.onDocumentKeyUp = function ( e
) {
2300 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2303 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
2304 // Stop listening for keyup, since we only needed this once
2305 this.getElementDocument().removeEventListener( 'keyup', this.onDocumentKeyUpHandler
, true );
2308 // Deprecated alias since 0.28.3
2309 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyUp = function () {
2310 OO
.ui
.warnDeprecation( 'onKeyUp is deprecated, use onDocumentKeyUp instead' );
2311 this.onDocumentKeyUp
.apply( this, arguments
);
2315 * Handles key press events.
2318 * @param {jQuery.Event} e Key press event
2320 * @return {undefined/boolean} False to prevent default if event is handled
2322 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
2323 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
2324 if ( this.emit( 'click' ) ) {
2331 * Check if button has a frame.
2333 * @return {boolean} Button is framed
2335 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
2340 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
2342 * @param {boolean} [framed] Make button framed, omit to toggle
2344 * @return {OO.ui.Element} The element, for chaining
2346 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
2347 framed
= framed
=== undefined ? !this.framed
: !!framed
;
2348 if ( framed
!== this.framed
) {
2349 this.framed
= framed
;
2351 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
2352 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
2353 this.updateThemeClasses();
2360 * Set the button's active state.
2362 * The active state can be set on:
2364 * - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected
2365 * - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on
2366 * - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page
2369 * @param {boolean} value Make button active
2371 * @return {OO.ui.Element} The element, for chaining
2373 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
2374 this.active
= !!value
;
2375 this.$element
.toggleClass( 'oo-ui-buttonElement-active', this.active
);
2376 this.updateThemeClasses();
2381 * Check if the button is active
2384 * @return {boolean} The button is active
2386 OO
.ui
.mixin
.ButtonElement
.prototype.isActive = function () {
2391 * Any OOUI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
2392 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
2393 * items from the group is done through the interface the class provides.
2394 * For more information, please see the [OOUI documentation on MediaWiki] [1].
2396 * [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Groups
2399 * @mixins OO.EmitterList
2403 * @param {Object} [config] Configuration options
2404 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
2405 * is omitted, the group element will use a generated `<div>`.
2407 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
2408 // Configuration initialization
2409 config
= config
|| {};
2411 // Mixin constructors
2412 OO
.EmitterList
.call( this, config
);
2418 this.setGroupElement( config
.$group
|| $( '<div>' ) );
2423 OO
.mixinClass( OO
.ui
.mixin
.GroupElement
, OO
.EmitterList
);
2430 * A change event is emitted when the set of selected items changes.
2432 * @param {OO.ui.Element[]} items Items currently in the group
2438 * Set the group element.
2440 * If an element is already set, items will be moved to the new element.
2442 * @param {jQuery} $group Element to use as group
2444 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
2447 this.$group
= $group
;
2448 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2449 this.$group
.append( this.items
[ i
].$element
);
2454 * Find an item by its data.
2456 * Only the first item with matching data will be returned. To return all matching items,
2457 * use the #findItemsFromData method.
2459 * @param {Object} data Item data to search for
2460 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2462 OO
.ui
.mixin
.GroupElement
.prototype.findItemFromData = function ( data
) {
2464 hash
= OO
.getHash( data
);
2466 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2467 item
= this.items
[ i
];
2468 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2477 * Find items by their data.
2479 * All items with matching data will be returned. To return only the first match, use the #findItemFromData method instead.
2481 * @param {Object} data Item data to search for
2482 * @return {OO.ui.Element[]} Items with equivalent data
2484 OO
.ui
.mixin
.GroupElement
.prototype.findItemsFromData = function ( data
) {
2486 hash
= OO
.getHash( data
),
2489 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2490 item
= this.items
[ i
];
2491 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2500 * Add items to the group.
2502 * Items will be added to the end of the group array unless the optional `index` parameter specifies
2503 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
2505 * @param {OO.ui.Element[]} items An array of items to add to the group
2506 * @param {number} [index] Index of the insertion point
2508 * @return {OO.ui.Element} The element, for chaining
2510 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
2512 OO
.EmitterList
.prototype.addItems
.call( this, items
, index
);
2514 this.emit( 'change', this.getItems() );
2521 OO
.ui
.mixin
.GroupElement
.prototype.moveItem = function ( items
, newIndex
) {
2522 // insertItemElements expects this.items to not have been modified yet, so call before the mixin
2523 this.insertItemElements( items
, newIndex
);
2526 newIndex
= OO
.EmitterList
.prototype.moveItem
.call( this, items
, newIndex
);
2534 OO
.ui
.mixin
.GroupElement
.prototype.insertItem = function ( item
, index
) {
2535 item
.setElementGroup( this );
2536 this.insertItemElements( item
, index
);
2539 index
= OO
.EmitterList
.prototype.insertItem
.call( this, item
, index
);
2545 * Insert elements into the group
2548 * @param {OO.ui.Element} itemWidget Item to insert
2549 * @param {number} index Insertion index
2551 OO
.ui
.mixin
.GroupElement
.prototype.insertItemElements = function ( itemWidget
, index
) {
2552 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
2553 this.$group
.append( itemWidget
.$element
);
2554 } else if ( index
=== 0 ) {
2555 this.$group
.prepend( itemWidget
.$element
);
2557 this.items
[ index
].$element
.before( itemWidget
.$element
);
2562 * Remove the specified items from a group.
2564 * Removed items are detached (not removed) from the DOM so that they may be reused.
2565 * To remove all items from a group, you may wish to use the #clearItems method instead.
2567 * @param {OO.ui.Element[]} items An array of items to remove
2569 * @return {OO.ui.Element} The element, for chaining
2571 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
2572 var i
, len
, item
, index
;
2574 // Remove specific items elements
2575 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
2577 index
= this.items
.indexOf( item
);
2578 if ( index
!== -1 ) {
2579 item
.setElementGroup( null );
2580 item
.$element
.detach();
2585 OO
.EmitterList
.prototype.removeItems
.call( this, items
);
2587 this.emit( 'change', this.getItems() );
2592 * Clear all items from the group.
2594 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2595 * To remove only a subset of items from a group, use the #removeItems method.
2598 * @return {OO.ui.Element} The element, for chaining
2600 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
2603 // Remove all item elements
2604 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2605 this.items
[ i
].setElementGroup( null );
2606 this.items
[ i
].$element
.detach();
2610 OO
.EmitterList
.prototype.clearItems
.call( this );
2612 this.emit( 'change', this.getItems() );
2617 * LabelElement is often mixed into other classes to generate a label, which
2618 * helps identify the function of an interface element.
2619 * See the [OOUI documentation on MediaWiki] [1] for more information.
2621 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
2627 * @param {Object} [config] Configuration options
2628 * @cfg {jQuery} [$label] The label element created by the class. If this
2629 * configuration is omitted, the label element will use a generated `<span>`.
2630 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
2631 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
2632 * in the future. See the [OOUI documentation on MediaWiki] [2] for examples.
2633 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
2634 * @cfg {boolean} [invisibleLabel] Whether the label should be visually hidden (but still accessible
2635 * to screen-readers).
2637 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
2638 // Configuration initialization
2639 config
= config
|| {};
2644 this.invisibleLabel
= null;
2647 this.setLabel( config
.label
|| this.constructor.static.label
);
2648 this.setLabelElement( config
.$label
|| $( '<span>' ) );
2649 this.setInvisibleLabel( config
.invisibleLabel
);
2654 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
2659 * @event labelChange
2660 * @param {string} value
2663 /* Static Properties */
2666 * The label text. The label can be specified as a plaintext string, a function that will
2667 * produce a string in the future, or `null` for no label. The static value will
2668 * be overridden if a label is specified with the #label config option.
2672 * @property {string|Function|null}
2674 OO
.ui
.mixin
.LabelElement
.static.label
= null;
2676 /* Static methods */
2679 * Highlight the first occurrence of the query in the given text
2681 * @param {string} text Text
2682 * @param {string} query Query to find
2683 * @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
2684 * @return {jQuery} Text with the first match of the query
2685 * sub-string wrapped in highlighted span
2687 OO
.ui
.mixin
.LabelElement
.static.highlightQuery = function ( text
, query
, compare
) {
2690 $result
= $( '<span>' );
2694 qLen
= query
.length
;
2695 for ( i
= 0; offset
=== -1 && i
<= tLen
- qLen
; i
++ ) {
2696 if ( compare( query
, text
.slice( i
, i
+ qLen
) ) === 0 ) {
2701 offset
= text
.toLowerCase().indexOf( query
.toLowerCase() );
2704 if ( !query
.length
|| offset
=== -1 ) {
2705 $result
.text( text
);
2708 document
.createTextNode( text
.slice( 0, offset
) ),
2710 .addClass( 'oo-ui-labelElement-label-highlight' )
2711 .text( text
.slice( offset
, offset
+ query
.length
) ),
2712 document
.createTextNode( text
.slice( offset
+ query
.length
) )
2715 return $result
.contents();
2721 * Set the label element.
2723 * If an element is already set, it will be cleaned up before setting up the new element.
2725 * @param {jQuery} $label Element to use as label
2727 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
2728 if ( this.$label
) {
2729 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
2732 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
2733 this.setLabelContent( this.label
);
2739 * An empty string will result in the label being hidden. A string containing only whitespace will
2740 * be converted to a single ` `.
2742 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
2743 * text; or null for no label
2745 * @return {OO.ui.Element} The element, for chaining
2747 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
2748 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
2749 label
= ( ( typeof label
=== 'string' || label
instanceof jQuery
) && label
.length
) || ( label
instanceof OO
.ui
.HtmlSnippet
&& label
.toString().length
) ? label
: null;
2751 if ( this.label
!== label
) {
2752 if ( this.$label
) {
2753 this.setLabelContent( label
);
2756 this.emit( 'labelChange' );
2759 this.$element
.toggleClass( 'oo-ui-labelElement', !!this.label
&& !this.invisibleLabel
);
2765 * Set whether the label should be visually hidden (but still accessible to screen-readers).
2767 * @param {boolean} invisibleLabel
2769 * @return {OO.ui.Element} The element, for chaining
2771 OO
.ui
.mixin
.LabelElement
.prototype.setInvisibleLabel = function ( invisibleLabel
) {
2772 invisibleLabel
= !!invisibleLabel
;
2774 if ( this.invisibleLabel
!== invisibleLabel
) {
2775 this.invisibleLabel
= invisibleLabel
;
2776 this.emit( 'labelChange' );
2779 this.$label
.toggleClass( 'oo-ui-labelElement-invisible', this.invisibleLabel
);
2780 // Pretend that there is no label, a lot of CSS has been written with this assumption
2781 this.$element
.toggleClass( 'oo-ui-labelElement', !!this.label
&& !this.invisibleLabel
);
2787 * Set the label as plain text with a highlighted query
2789 * @param {string} text Text label to set
2790 * @param {string} query Substring of text to highlight
2791 * @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
2793 * @return {OO.ui.Element} The element, for chaining
2795 OO
.ui
.mixin
.LabelElement
.prototype.setHighlightedQuery = function ( text
, query
, compare
) {
2796 return this.setLabel( this.constructor.static.highlightQuery( text
, query
, compare
) );
2802 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
2803 * text; or null for no label
2805 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
2810 * Set the content of the label.
2812 * Do not call this method until after the label element has been set by #setLabelElement.
2815 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
2816 * text; or null for no label
2818 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
2819 if ( typeof label
=== 'string' ) {
2820 if ( label
.match( /^\s*$/ ) ) {
2821 // Convert whitespace only string to a single non-breaking space
2822 this.$label
.html( ' ' );
2824 this.$label
.text( label
);
2826 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
2827 this.$label
.html( label
.toString() );
2828 } else if ( label
instanceof jQuery
) {
2829 this.$label
.empty().append( label
);
2831 this.$label
.empty();
2836 * IconElement is often mixed into other classes to generate an icon.
2837 * Icons are graphics, about the size of normal text. They are used to aid the user
2838 * in locating a control or to convey information in a space-efficient way. See the
2839 * [OOUI documentation on MediaWiki] [1] for a list of icons
2840 * included in the library.
2842 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
2848 * @param {Object} [config] Configuration options
2849 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2850 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2851 * the icon element be set to an existing icon instead of the one generated by this class, set a
2852 * value using a jQuery selection. For example:
2854 * // Use a <div> tag instead of a <span>
2856 * // Use an existing icon element instead of the one generated by the class
2857 * $icon: this.$element
2858 * // Use an icon element from a child widget
2859 * $icon: this.childwidget.$element
2860 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
2861 * symbolic names. A map is used for i18n purposes and contains a `default` icon
2862 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
2863 * by the user's language.
2865 * Example of an i18n map:
2867 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2868 * See the [OOUI documentation on MediaWiki] [2] for a list of icons included in the library.
2869 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
2870 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
2871 * text. The icon title is displayed when users move the mouse over the icon.
2873 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
2874 // Configuration initialization
2875 config
= config
|| {};
2880 this.iconTitle
= null;
2883 this.setIcon( config
.icon
|| this.constructor.static.icon
);
2884 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
2885 this.setIconElement( config
.$icon
|| $( '<span>' ) );
2890 OO
.initClass( OO
.ui
.mixin
.IconElement
);
2892 /* Static Properties */
2895 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
2896 * for i18n purposes and contains a `default` icon name and additional names keyed by
2897 * language code. The `default` name is used when no icon is keyed by the user's language.
2899 * Example of an i18n map:
2901 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2903 * Note: the static property will be overridden if the #icon configuration is used.
2907 * @property {Object|string}
2909 OO
.ui
.mixin
.IconElement
.static.icon
= null;
2912 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2913 * function that returns title text, or `null` for no title.
2915 * The static property will be overridden if the #iconTitle configuration is used.
2919 * @property {string|Function|null}
2921 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
2926 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2927 * applies to the specified icon element instead of the one created by the class. If an icon
2928 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2929 * and mixin methods will no longer affect the element.
2931 * @param {jQuery} $icon Element to use as icon
2933 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
2936 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
2937 .removeAttr( 'title' );
2941 .addClass( 'oo-ui-iconElement-icon' )
2942 .toggleClass( 'oo-ui-iconElement-noIcon', !this.icon
)
2943 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
2944 if ( this.iconTitle
!== null ) {
2945 this.$icon
.attr( 'title', this.iconTitle
);
2948 this.updateThemeClasses();
2952 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
2953 * The icon parameter can also be set to a map of icon names. See the #icon config setting
2956 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
2957 * by language code, or `null` to remove the icon.
2959 * @return {OO.ui.Element} The element, for chaining
2961 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
2962 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
2963 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
2965 if ( this.icon
!== icon
) {
2967 if ( this.icon
!== null ) {
2968 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
2970 if ( icon
!== null ) {
2971 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
2977 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
2979 this.$icon
.toggleClass( 'oo-ui-iconElement-noIcon', !this.icon
);
2981 this.updateThemeClasses();
2987 * Set the icon title. Use `null` to remove the title.
2989 * @param {string|Function|null} iconTitle A text string used as the icon title,
2990 * a function that returns title text, or `null` for no title.
2992 * @return {OO.ui.Element} The element, for chaining
2994 OO
.ui
.mixin
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
2996 ( typeof iconTitle
=== 'function' || ( typeof iconTitle
=== 'string' && iconTitle
.length
) ) ?
2997 OO
.ui
.resolveMsg( iconTitle
) : null;
2999 if ( this.iconTitle
!== iconTitle
) {
3000 this.iconTitle
= iconTitle
;
3002 if ( this.iconTitle
!== null ) {
3003 this.$icon
.attr( 'title', iconTitle
);
3005 this.$icon
.removeAttr( 'title' );
3014 * Get the symbolic name of the icon.
3016 * @return {string} Icon name
3018 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
3023 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
3025 * @return {string} Icon title text
3027 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
3028 return this.iconTitle
;
3032 * IndicatorElement is often mixed into other classes to generate an indicator.
3033 * Indicators are small graphics that are generally used in two ways:
3035 * - To draw attention to the status of an item. For example, an indicator might be
3036 * used to show that an item in a list has errors that need to be resolved.
3037 * - To clarify the function of a control that acts in an exceptional way (a button
3038 * that opens a menu instead of performing an action directly, for example).
3040 * For a list of indicators included in the library, please see the
3041 * [OOUI documentation on MediaWiki] [1].
3043 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3049 * @param {Object} [config] Configuration options
3050 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
3051 * configuration is omitted, the indicator element will use a generated `<span>`.
3052 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3053 * See the [OOUI documentation on MediaWiki][2] for a list of indicators included
3055 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3056 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
3057 * or a function that returns title text. The indicator title is displayed when users move
3058 * the mouse over the indicator.
3060 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
3061 // Configuration initialization
3062 config
= config
|| {};
3065 this.$indicator
= null;
3066 this.indicator
= null;
3067 this.indicatorTitle
= null;
3070 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
3071 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
3072 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
3077 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
3079 /* Static Properties */
3082 * Symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3083 * The static property will be overridden if the #indicator configuration is used.
3087 * @property {string|null}
3089 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
3092 * A text string used as the indicator title, a function that returns title text, or `null`
3093 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
3097 * @property {string|Function|null}
3099 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
3104 * Set the indicator element.
3106 * If an element is already set, it will be cleaned up before setting up the new element.
3108 * @param {jQuery} $indicator Element to use as indicator
3110 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
3111 if ( this.$indicator
) {
3113 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
3114 .removeAttr( 'title' );
3117 this.$indicator
= $indicator
3118 .addClass( 'oo-ui-indicatorElement-indicator' )
3119 .toggleClass( 'oo-ui-indicatorElement-noIndicator', !this.indicator
)
3120 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
3121 if ( this.indicatorTitle
!== null ) {
3122 this.$indicator
.attr( 'title', this.indicatorTitle
);
3125 this.updateThemeClasses();
3129 * Set the indicator by its symbolic name: ‘clear’, ‘down’, ‘required’, ‘search’, ‘up’. Use `null` to remove the indicator.
3131 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
3133 * @return {OO.ui.Element} The element, for chaining
3135 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
3136 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
3138 if ( this.indicator
!== indicator
) {
3139 if ( this.$indicator
) {
3140 if ( this.indicator
!== null ) {
3141 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
3143 if ( indicator
!== null ) {
3144 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
3147 this.indicator
= indicator
;
3150 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
3151 if ( this.$indicator
) {
3152 this.$indicator
.toggleClass( 'oo-ui-indicatorElement-noIndicator', !this.indicator
);
3154 this.updateThemeClasses();
3160 * Set the indicator title.
3162 * The title is displayed when a user moves the mouse over the indicator.
3164 * @param {string|Function|null} indicatorTitle Indicator title text, a function that returns text, or
3165 * `null` for no indicator title
3167 * @return {OO.ui.Element} The element, for chaining
3169 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
3171 ( typeof indicatorTitle
=== 'function' || ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ) ?
3172 OO
.ui
.resolveMsg( indicatorTitle
) : null;
3174 if ( this.indicatorTitle
!== indicatorTitle
) {
3175 this.indicatorTitle
= indicatorTitle
;
3176 if ( this.$indicator
) {
3177 if ( this.indicatorTitle
!== null ) {
3178 this.$indicator
.attr( 'title', indicatorTitle
);
3180 this.$indicator
.removeAttr( 'title' );
3189 * Get the symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3191 * @return {string} Symbolic name of indicator
3193 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
3194 return this.indicator
;
3198 * Get the indicator title.
3200 * The title is displayed when a user moves the mouse over the indicator.
3202 * @return {string} Indicator title text
3204 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
3205 return this.indicatorTitle
;
3209 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
3210 * additional functionality to an element created by another class. The class provides
3211 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
3212 * which are used to customize the look and feel of a widget to better describe its
3213 * importance and functionality.
3215 * The library currently contains the following styling flags for general use:
3217 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
3218 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
3220 * The flags affect the appearance of the buttons:
3223 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
3224 * var button1 = new OO.ui.ButtonWidget( {
3225 * label: 'Progressive',
3226 * flags: 'progressive'
3228 * var button2 = new OO.ui.ButtonWidget( {
3229 * label: 'Destructive',
3230 * flags: 'destructive'
3232 * $( 'body' ).append( button1.$element, button2.$element );
3234 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
3235 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
3237 * [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
3243 * @param {Object} [config] Configuration options
3244 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'progressive' or 'primary') to apply.
3245 * Please see the [OOUI documentation on MediaWiki] [2] for more information about available flags.
3246 * [2]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
3247 * @cfg {jQuery} [$flagged] The flagged element. By default,
3248 * the flagged functionality is applied to the element created by the class ($element).
3249 * If a different element is specified, the flagged functionality will be applied to it instead.
3251 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
3252 // Configuration initialization
3253 config
= config
|| {};
3257 this.$flagged
= null;
3260 this.setFlags( config
.flags
);
3261 this.setFlaggedElement( config
.$flagged
|| this.$element
);
3268 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
3269 * parameter contains the name of each modified flag and indicates whether it was
3272 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
3273 * that the flag was added, `false` that the flag was removed.
3279 * Set the flagged element.
3281 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
3282 * If an element is already set, the method will remove the mixin’s effect on that element.
3284 * @param {jQuery} $flagged Element that should be flagged
3286 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
3287 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
3288 return 'oo-ui-flaggedElement-' + flag
;
3291 if ( this.$flagged
) {
3292 this.$flagged
.removeClass( classNames
);
3295 this.$flagged
= $flagged
.addClass( classNames
);
3299 * Check if the specified flag is set.
3301 * @param {string} flag Name of flag
3302 * @return {boolean} The flag is set
3304 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
3305 // This may be called before the constructor, thus before this.flags is set
3306 return this.flags
&& ( flag
in this.flags
);
3310 * Get the names of all flags set.
3312 * @return {string[]} Flag names
3314 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
3315 // This may be called before the constructor, thus before this.flags is set
3316 return Object
.keys( this.flags
|| {} );
3323 * @return {OO.ui.Element} The element, for chaining
3326 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
3327 var flag
, className
,
3330 classPrefix
= 'oo-ui-flaggedElement-';
3332 for ( flag
in this.flags
) {
3333 className
= classPrefix
+ flag
;
3334 changes
[ flag
] = false;
3335 delete this.flags
[ flag
];
3336 remove
.push( className
);
3339 if ( this.$flagged
) {
3340 this.$flagged
.removeClass( remove
);
3343 this.updateThemeClasses();
3344 this.emit( 'flag', changes
);
3350 * Add one or more flags.
3352 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
3353 * or an object keyed by flag name with a boolean value that indicates whether the flag should
3354 * be added (`true`) or removed (`false`).
3356 * @return {OO.ui.Element} The element, for chaining
3359 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
3360 var i
, len
, flag
, className
,
3364 classPrefix
= 'oo-ui-flaggedElement-';
3366 if ( typeof flags
=== 'string' ) {
3367 className
= classPrefix
+ flags
;
3369 if ( !this.flags
[ flags
] ) {
3370 this.flags
[ flags
] = true;
3371 add
.push( className
);
3373 } else if ( Array
.isArray( flags
) ) {
3374 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
3376 className
= classPrefix
+ flag
;
3378 if ( !this.flags
[ flag
] ) {
3379 changes
[ flag
] = true;
3380 this.flags
[ flag
] = true;
3381 add
.push( className
);
3384 } else if ( OO
.isPlainObject( flags
) ) {
3385 for ( flag
in flags
) {
3386 className
= classPrefix
+ flag
;
3387 if ( flags
[ flag
] ) {
3389 if ( !this.flags
[ flag
] ) {
3390 changes
[ flag
] = true;
3391 this.flags
[ flag
] = true;
3392 add
.push( className
);
3396 if ( this.flags
[ flag
] ) {
3397 changes
[ flag
] = false;
3398 delete this.flags
[ flag
];
3399 remove
.push( className
);
3405 if ( this.$flagged
) {
3408 .removeClass( remove
);
3411 this.updateThemeClasses();
3412 this.emit( 'flag', changes
);
3418 * TitledElement is mixed into other classes to provide a `title` attribute.
3419 * Titles are rendered by the browser and are made visible when the user moves
3420 * the mouse over the element. Titles are not visible on touch devices.
3423 * // TitledElement provides a 'title' attribute to the
3424 * // ButtonWidget class
3425 * var button = new OO.ui.ButtonWidget( {
3426 * label: 'Button with Title',
3427 * title: 'I am a button'
3429 * $( 'body' ).append( button.$element );
3435 * @param {Object} [config] Configuration options
3436 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
3437 * If this config is omitted, the title functionality is applied to $element, the
3438 * element created by the class.
3439 * @cfg {string|Function} [title] The title text or a function that returns text. If
3440 * this config is omitted, the value of the {@link #static-title static title} property is used.
3442 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
3443 // Configuration initialization
3444 config
= config
|| {};
3447 this.$titled
= null;
3451 this.setTitle( config
.title
!== undefined ? config
.title
: this.constructor.static.title
);
3452 this.setTitledElement( config
.$titled
|| this.$element
);
3457 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
3459 /* Static Properties */
3462 * The title text, a function that returns text, or `null` for no title. The value of the static property
3463 * is overridden if the #title config option is used.
3467 * @property {string|Function|null}
3469 OO
.ui
.mixin
.TitledElement
.static.title
= null;
3474 * Set the titled element.
3476 * This method is used to retarget a TitledElement mixin so that its functionality applies to the specified element.
3477 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
3479 * @param {jQuery} $titled Element that should use the 'titled' functionality
3481 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
3482 if ( this.$titled
) {
3483 this.$titled
.removeAttr( 'title' );
3486 this.$titled
= $titled
;
3495 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
3497 * @return {OO.ui.Element} The element, for chaining
3499 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
3500 title
= typeof title
=== 'function' ? OO
.ui
.resolveMsg( title
) : title
;
3501 title
= ( typeof title
=== 'string' && title
.length
) ? title
: null;
3503 if ( this.title
!== title
) {
3512 * Update the title attribute, in case of changes to title or accessKey.
3516 * @return {OO.ui.Element} The element, for chaining
3518 OO
.ui
.mixin
.TitledElement
.prototype.updateTitle = function () {
3519 var title
= this.getTitle();
3520 if ( this.$titled
) {
3521 if ( title
!== null ) {
3522 // Only if this is an AccessKeyedElement
3523 if ( this.formatTitleWithAccessKey
) {
3524 title
= this.formatTitleWithAccessKey( title
);
3526 this.$titled
.attr( 'title', title
);
3528 this.$titled
.removeAttr( 'title' );
3537 * @return {string} Title string
3539 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
3544 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
3545 * Accesskeys allow an user to go to a specific element by using
3546 * a shortcut combination of a browser specific keys + the key
3550 * // AccessKeyedElement provides an 'accesskey' attribute to the
3551 * // ButtonWidget class
3552 * var button = new OO.ui.ButtonWidget( {
3553 * label: 'Button with Accesskey',
3556 * $( 'body' ).append( button.$element );
3562 * @param {Object} [config] Configuration options
3563 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3564 * If this config is omitted, the accesskey functionality is applied to $element, the
3565 * element created by the class.
3566 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3567 * this config is omitted, no accesskey will be added.
3569 OO
.ui
.mixin
.AccessKeyedElement
= function OoUiMixinAccessKeyedElement( config
) {
3570 // Configuration initialization
3571 config
= config
|| {};
3574 this.$accessKeyed
= null;
3575 this.accessKey
= null;
3578 this.setAccessKey( config
.accessKey
|| null );
3579 this.setAccessKeyedElement( config
.$accessKeyed
|| this.$element
);
3581 // If this is also a TitledElement and it initialized before we did, we may have
3582 // to update the title with the access key
3583 if ( this.updateTitle
) {
3590 OO
.initClass( OO
.ui
.mixin
.AccessKeyedElement
);
3592 /* Static Properties */
3595 * The access key, a function that returns a key, or `null` for no accesskey.
3599 * @property {string|Function|null}
3601 OO
.ui
.mixin
.AccessKeyedElement
.static.accessKey
= null;
3606 * Set the accesskeyed element.
3608 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
3609 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
3611 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyed' functionality
3613 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKeyedElement = function ( $accessKeyed
) {
3614 if ( this.$accessKeyed
) {
3615 this.$accessKeyed
.removeAttr( 'accesskey' );
3618 this.$accessKeyed
= $accessKeyed
;
3619 if ( this.accessKey
) {
3620 this.$accessKeyed
.attr( 'accesskey', this.accessKey
);
3627 * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no accesskey
3629 * @return {OO.ui.Element} The element, for chaining
3631 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKey = function ( accessKey
) {
3632 accessKey
= typeof accessKey
=== 'string' ? OO
.ui
.resolveMsg( accessKey
) : null;
3634 if ( this.accessKey
!== accessKey
) {
3635 if ( this.$accessKeyed
) {
3636 if ( accessKey
!== null ) {
3637 this.$accessKeyed
.attr( 'accesskey', accessKey
);
3639 this.$accessKeyed
.removeAttr( 'accesskey' );
3642 this.accessKey
= accessKey
;
3644 // Only if this is a TitledElement
3645 if ( this.updateTitle
) {
3656 * @return {string} accessKey string
3658 OO
.ui
.mixin
.AccessKeyedElement
.prototype.getAccessKey = function () {
3659 return this.accessKey
;
3663 * Add information about the access key to the element's tooltip label.
3664 * (This is only public for hacky usage in FieldLayout.)
3666 * @param {string} title Tooltip label for `title` attribute
3669 OO
.ui
.mixin
.AccessKeyedElement
.prototype.formatTitleWithAccessKey = function ( title
) {
3672 if ( !this.$accessKeyed
) {
3673 // Not initialized yet; the constructor will call updateTitle() which will rerun this function
3676 // Use jquery.accessKeyLabel if available to show modifiers, otherwise just display the single key
3677 if ( $.fn
.updateTooltipAccessKeys
&& $.fn
.updateTooltipAccessKeys
.getAccessKeyLabel
) {
3678 accessKey
= $.fn
.updateTooltipAccessKeys
.getAccessKeyLabel( this.$accessKeyed
[ 0 ] );
3680 accessKey
= this.getAccessKey();
3683 title
+= ' [' + accessKey
+ ']';
3689 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3690 * feels, and functionality can be customized via the class’s configuration options
3691 * and methods. Please see the [OOUI documentation on MediaWiki] [1] for more information
3694 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches
3697 * // A button widget
3698 * var button = new OO.ui.ButtonWidget( {
3699 * label: 'Button with Icon',
3703 * $( 'body' ).append( button.$element );
3705 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3708 * @extends OO.ui.Widget
3709 * @mixins OO.ui.mixin.ButtonElement
3710 * @mixins OO.ui.mixin.IconElement
3711 * @mixins OO.ui.mixin.IndicatorElement
3712 * @mixins OO.ui.mixin.LabelElement
3713 * @mixins OO.ui.mixin.TitledElement
3714 * @mixins OO.ui.mixin.FlaggedElement
3715 * @mixins OO.ui.mixin.TabIndexedElement
3716 * @mixins OO.ui.mixin.AccessKeyedElement
3719 * @param {Object} [config] Configuration options
3720 * @cfg {boolean} [active=false] Whether button should be shown as active
3721 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3722 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3723 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3725 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
3726 // Configuration initialization
3727 config
= config
|| {};
3729 // Parent constructor
3730 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
3732 // Mixin constructors
3733 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
3734 OO
.ui
.mixin
.IconElement
.call( this, config
);
3735 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
3736 OO
.ui
.mixin
.LabelElement
.call( this, config
);
3737 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
3738 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
3739 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
3740 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$button
} ) );
3745 this.noFollow
= false;
3748 this.connect( this, { disable
: 'onDisable' } );
3751 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
3753 .addClass( 'oo-ui-buttonWidget' )
3754 .append( this.$button
);
3755 this.setActive( config
.active
);
3756 this.setHref( config
.href
);
3757 this.setTarget( config
.target
);
3758 this.setNoFollow( config
.noFollow
);
3763 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
3764 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
3765 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
3766 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
3767 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
3768 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
3769 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
3770 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
3771 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
3773 /* Static Properties */
3779 OO
.ui
.ButtonWidget
.static.cancelButtonMouseDownEvents
= false;
3785 OO
.ui
.ButtonWidget
.static.tagName
= 'span';
3790 * Get hyperlink location.
3792 * @return {string} Hyperlink location
3794 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
3799 * Get hyperlink target.
3801 * @return {string} Hyperlink target
3803 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
3808 * Get search engine traversal hint.
3810 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3812 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
3813 return this.noFollow
;
3817 * Set hyperlink location.
3819 * @param {string|null} href Hyperlink location, null to remove
3821 * @return {OO.ui.Widget} The widget, for chaining
3823 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
3824 href
= typeof href
=== 'string' ? href
: null;
3825 if ( href
!== null && !OO
.ui
.isSafeUrl( href
) ) {
3829 if ( href
!== this.href
) {
3838 * Update the `href` attribute, in case of changes to href or
3843 * @return {OO.ui.Widget} The widget, for chaining
3845 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
3846 if ( this.href
!== null && !this.isDisabled() ) {
3847 this.$button
.attr( 'href', this.href
);
3849 this.$button
.removeAttr( 'href' );
3856 * Handle disable events.
3859 * @param {boolean} disabled Element is disabled
3861 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
3866 * Set hyperlink target.
3868 * @param {string|null} target Hyperlink target, null to remove
3869 * @return {OO.ui.Widget} The widget, for chaining
3871 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
3872 target
= typeof target
=== 'string' ? target
: null;
3874 if ( target
!== this.target
) {
3875 this.target
= target
;
3876 if ( target
!== null ) {
3877 this.$button
.attr( 'target', target
);
3879 this.$button
.removeAttr( 'target' );
3887 * Set search engine traversal hint.
3889 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3890 * @return {OO.ui.Widget} The widget, for chaining
3892 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
3893 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
3895 if ( noFollow
!== this.noFollow
) {
3896 this.noFollow
= noFollow
;
3898 this.$button
.attr( 'rel', 'nofollow' );
3900 this.$button
.removeAttr( 'rel' );
3907 // Override method visibility hints from ButtonElement
3918 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3919 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3920 * removed, and cleared from the group.
3923 * // Example: A ButtonGroupWidget with two buttons
3924 * var button1 = new OO.ui.PopupButtonWidget( {
3925 * label: 'Select a category',
3928 * $content: $( '<p>List of categories...</p>' ),
3933 * var button2 = new OO.ui.ButtonWidget( {
3936 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
3937 * items: [button1, button2]
3939 * $( 'body' ).append( buttonGroup.$element );
3942 * @extends OO.ui.Widget
3943 * @mixins OO.ui.mixin.GroupElement
3946 * @param {Object} [config] Configuration options
3947 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
3949 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
3950 // Configuration initialization
3951 config
= config
|| {};
3953 // Parent constructor
3954 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
3956 // Mixin constructors
3957 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
3960 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
3961 if ( Array
.isArray( config
.items
) ) {
3962 this.addItems( config
.items
);
3968 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
3969 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
3971 /* Static Properties */
3977 OO
.ui
.ButtonGroupWidget
.static.tagName
= 'span';
3985 * @return {OO.ui.Widget} The widget, for chaining
3987 OO
.ui
.ButtonGroupWidget
.prototype.focus = function () {
3988 if ( !this.isDisabled() ) {
3989 if ( this.items
[ 0 ] ) {
3990 this.items
[ 0 ].focus();
3999 OO
.ui
.ButtonGroupWidget
.prototype.simulateLabelClick = function () {
4004 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
4005 * which creates a label that identifies the icon’s function. See the [OOUI documentation on MediaWiki] [1]
4006 * for a list of icons included in the library.
4009 * // An icon widget with a label
4010 * var myIcon = new OO.ui.IconWidget( {
4014 * // Create a label.
4015 * var iconLabel = new OO.ui.LabelWidget( {
4018 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
4020 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
4023 * @extends OO.ui.Widget
4024 * @mixins OO.ui.mixin.IconElement
4025 * @mixins OO.ui.mixin.TitledElement
4026 * @mixins OO.ui.mixin.LabelElement
4027 * @mixins OO.ui.mixin.FlaggedElement
4030 * @param {Object} [config] Configuration options
4032 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
4033 // Configuration initialization
4034 config
= config
|| {};
4036 // Parent constructor
4037 OO
.ui
.IconWidget
.parent
.call( this, config
);
4039 // Mixin constructors
4040 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
4041 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
4042 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
, invisibleLabel
: true } ) );
4043 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
4046 this.$element
.addClass( 'oo-ui-iconWidget' );
4047 // Remove class added by LabelElement initialization. It causes unexpected CSS to apply when
4048 // nested in other widgets, because this widget used to not mix in LabelElement.
4049 this.$element
.removeClass( 'oo-ui-labelElement-label' );
4054 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
4055 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
4056 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
4057 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.LabelElement
);
4058 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
4060 /* Static Properties */
4066 OO
.ui
.IconWidget
.static.tagName
= 'span';
4069 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
4070 * attention to the status of an item or to clarify the function within a control. For a list of
4071 * indicators included in the library, please see the [OOUI documentation on MediaWiki][1].
4074 * // Example of an indicator widget
4075 * var indicator1 = new OO.ui.IndicatorWidget( {
4076 * indicator: 'required'
4079 * // Create a fieldset layout to add a label
4080 * var fieldset = new OO.ui.FieldsetLayout();
4081 * fieldset.addItems( [
4082 * new OO.ui.FieldLayout( indicator1, { label: 'A required indicator:' } )
4084 * $( 'body' ).append( fieldset.$element );
4086 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
4089 * @extends OO.ui.Widget
4090 * @mixins OO.ui.mixin.IndicatorElement
4091 * @mixins OO.ui.mixin.TitledElement
4092 * @mixins OO.ui.mixin.LabelElement
4095 * @param {Object} [config] Configuration options
4097 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
4098 // Configuration initialization
4099 config
= config
|| {};
4101 // Parent constructor
4102 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
4104 // Mixin constructors
4105 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
4106 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
4107 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
, invisibleLabel
: true } ) );
4110 this.$element
.addClass( 'oo-ui-indicatorWidget' );
4111 // Remove class added by LabelElement initialization. It causes unexpected CSS to apply when
4112 // nested in other widgets, because this widget used to not mix in LabelElement.
4113 this.$element
.removeClass( 'oo-ui-labelElement-label' );
4118 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
4119 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
4120 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
4121 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.LabelElement
);
4123 /* Static Properties */
4129 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
4132 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
4133 * be configured with a `label` option that is set to a string, a label node, or a function:
4135 * - String: a plaintext string
4136 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
4137 * label that includes a link or special styling, such as a gray color or additional graphical elements.
4138 * - Function: a function that will produce a string in the future. Functions are used
4139 * in cases where the value of the label is not currently defined.
4141 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
4142 * will come into focus when the label is clicked.
4145 * // Examples of LabelWidgets
4146 * var label1 = new OO.ui.LabelWidget( {
4147 * label: 'plaintext label'
4149 * var label2 = new OO.ui.LabelWidget( {
4150 * label: $( '<a href="default.html">jQuery label</a>' )
4152 * // Create a fieldset layout with fields for each example
4153 * var fieldset = new OO.ui.FieldsetLayout();
4154 * fieldset.addItems( [
4155 * new OO.ui.FieldLayout( label1 ),
4156 * new OO.ui.FieldLayout( label2 )
4158 * $( 'body' ).append( fieldset.$element );
4161 * @extends OO.ui.Widget
4162 * @mixins OO.ui.mixin.LabelElement
4163 * @mixins OO.ui.mixin.TitledElement
4166 * @param {Object} [config] Configuration options
4167 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
4168 * Clicking the label will focus the specified input field.
4170 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
4171 // Configuration initialization
4172 config
= config
|| {};
4174 // Parent constructor
4175 OO
.ui
.LabelWidget
.parent
.call( this, config
);
4177 // Mixin constructors
4178 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
4179 OO
.ui
.mixin
.TitledElement
.call( this, config
);
4182 this.input
= config
.input
;
4186 if ( this.input
.getInputId() ) {
4187 this.$element
.attr( 'for', this.input
.getInputId() );
4189 this.$label
.on( 'click', function () {
4190 this.input
.simulateLabelClick();
4194 this.$element
.addClass( 'oo-ui-labelWidget' );
4199 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
4200 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
4201 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
4203 /* Static Properties */
4209 OO
.ui
.LabelWidget
.static.tagName
= 'label';
4212 * PendingElement is a mixin that is used to create elements that notify users that something is happening
4213 * and that they should wait before proceeding. The pending state is visually represented with a pending
4214 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
4215 * field of a {@link OO.ui.TextInputWidget text input widget}.
4217 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
4218 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
4219 * in process dialogs.
4222 * function MessageDialog( config ) {
4223 * MessageDialog.parent.call( this, config );
4225 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
4227 * MessageDialog.static.name = 'myMessageDialog';
4228 * MessageDialog.static.actions = [
4229 * { action: 'save', label: 'Done', flags: 'primary' },
4230 * { label: 'Cancel', flags: 'safe' }
4233 * MessageDialog.prototype.initialize = function () {
4234 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
4235 * this.content = new OO.ui.PanelLayout( { padded: true } );
4236 * 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>' );
4237 * this.$body.append( this.content.$element );
4239 * MessageDialog.prototype.getBodyHeight = function () {
4242 * MessageDialog.prototype.getActionProcess = function ( action ) {
4243 * var dialog = this;
4244 * if ( action === 'save' ) {
4245 * dialog.getActions().get({actions: 'save'})[0].pushPending();
4246 * return new OO.ui.Process()
4248 * .next( function () {
4249 * dialog.getActions().get({actions: 'save'})[0].popPending();
4252 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
4255 * var windowManager = new OO.ui.WindowManager();
4256 * $( 'body' ).append( windowManager.$element );
4258 * var dialog = new MessageDialog();
4259 * windowManager.addWindows( [ dialog ] );
4260 * windowManager.openWindow( dialog );
4266 * @param {Object} [config] Configuration options
4267 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
4269 OO
.ui
.mixin
.PendingElement
= function OoUiMixinPendingElement( config
) {
4270 // Configuration initialization
4271 config
= config
|| {};
4275 this.$pending
= null;
4278 this.setPendingElement( config
.$pending
|| this.$element
);
4283 OO
.initClass( OO
.ui
.mixin
.PendingElement
);
4288 * Set the pending element (and clean up any existing one).
4290 * @param {jQuery} $pending The element to set to pending.
4292 OO
.ui
.mixin
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
4293 if ( this.$pending
) {
4294 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
4297 this.$pending
= $pending
;
4298 if ( this.pending
> 0 ) {
4299 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
4304 * Check if an element is pending.
4306 * @return {boolean} Element is pending
4308 OO
.ui
.mixin
.PendingElement
.prototype.isPending = function () {
4309 return !!this.pending
;
4313 * Increase the pending counter. The pending state will remain active until the counter is zero
4314 * (i.e., the number of calls to #pushPending and #popPending is the same).
4317 * @return {OO.ui.Element} The element, for chaining
4319 OO
.ui
.mixin
.PendingElement
.prototype.pushPending = function () {
4320 if ( this.pending
=== 0 ) {
4321 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
4322 this.updateThemeClasses();
4330 * Decrease the pending counter. The pending state will remain active until the counter is zero
4331 * (i.e., the number of calls to #pushPending and #popPending is the same).
4334 * @return {OO.ui.Element} The element, for chaining
4336 OO
.ui
.mixin
.PendingElement
.prototype.popPending = function () {
4337 if ( this.pending
=== 1 ) {
4338 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
4339 this.updateThemeClasses();
4341 this.pending
= Math
.max( 0, this.pending
- 1 );
4347 * Element that will stick adjacent to a specified container, even when it is inserted elsewhere
4348 * in the document (for example, in an OO.ui.Window's $overlay).
4350 * The elements's position is automatically calculated and maintained when window is resized or the
4351 * page is scrolled. If you reposition the container manually, you have to call #position to make
4352 * sure the element is still placed correctly.
4354 * As positioning is only possible when both the element and the container are attached to the DOM
4355 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
4356 * the #toggle method to display a floating popup, for example.
4362 * @param {Object} [config] Configuration options
4363 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
4364 * @cfg {jQuery} [$floatableContainer] Node to position adjacent to
4365 * @cfg {string} [verticalPosition='below'] Where to position $floatable vertically:
4366 * 'below': Directly below $floatableContainer, aligning f's top edge with fC's bottom edge
4367 * 'above': Directly above $floatableContainer, aligning f's bottom edge with fC's top edge
4368 * 'top': Align the top edge with $floatableContainer's top edge
4369 * 'bottom': Align the bottom edge with $floatableContainer's bottom edge
4370 * 'center': Vertically align the center with $floatableContainer's center
4371 * @cfg {string} [horizontalPosition='start'] Where to position $floatable horizontally:
4372 * 'before': Directly before $floatableContainer, aligning f's end edge with fC's start edge
4373 * 'after': Directly after $floatableContainer, aligning f's start edge with fC's end edge
4374 * 'start': Align the start (left in LTR, right in RTL) edge with $floatableContainer's start edge
4375 * 'end': Align the end (right in LTR, left in RTL) edge with $floatableContainer's end edge
4376 * 'center': Horizontally align the center with $floatableContainer's center
4377 * @cfg {boolean} [hideWhenOutOfView=true] Whether to hide the floatable element if the container
4380 OO
.ui
.mixin
.FloatableElement
= function OoUiMixinFloatableElement( config
) {
4381 // Configuration initialization
4382 config
= config
|| {};
4385 this.$floatable
= null;
4386 this.$floatableContainer
= null;
4387 this.$floatableWindow
= null;
4388 this.$floatableClosestScrollable
= null;
4389 this.floatableOutOfView
= false;
4390 this.onFloatableScrollHandler
= this.position
.bind( this );
4391 this.onFloatableWindowResizeHandler
= this.position
.bind( this );
4394 this.setFloatableContainer( config
.$floatableContainer
);
4395 this.setFloatableElement( config
.$floatable
|| this.$element
);
4396 this.setVerticalPosition( config
.verticalPosition
|| 'below' );
4397 this.setHorizontalPosition( config
.horizontalPosition
|| 'start' );
4398 this.hideWhenOutOfView
= config
.hideWhenOutOfView
=== undefined ? true : !!config
.hideWhenOutOfView
;
4404 * Set floatable element.
4406 * If an element is already set, it will be cleaned up before setting up the new element.
4408 * @param {jQuery} $floatable Element to make floatable
4410 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableElement = function ( $floatable
) {
4411 if ( this.$floatable
) {
4412 this.$floatable
.removeClass( 'oo-ui-floatableElement-floatable' );
4413 this.$floatable
.css( { left
: '', top
: '' } );
4416 this.$floatable
= $floatable
.addClass( 'oo-ui-floatableElement-floatable' );
4421 * Set floatable container.
4423 * The element will be positioned relative to the specified container.
4425 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
4427 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableContainer = function ( $floatableContainer
) {
4428 this.$floatableContainer
= $floatableContainer
;
4429 if ( this.$floatable
) {
4435 * Change how the element is positioned vertically.
4437 * @param {string} position 'below', 'above', 'top', 'bottom' or 'center'
4439 OO
.ui
.mixin
.FloatableElement
.prototype.setVerticalPosition = function ( position
) {
4440 if ( [ 'below', 'above', 'top', 'bottom', 'center' ].indexOf( position
) === -1 ) {
4441 throw new Error( 'Invalid value for vertical position: ' + position
);
4443 if ( this.verticalPosition
!== position
) {
4444 this.verticalPosition
= position
;
4445 if ( this.$floatable
) {
4452 * Change how the element is positioned horizontally.
4454 * @param {string} position 'before', 'after', 'start', 'end' or 'center'
4456 OO
.ui
.mixin
.FloatableElement
.prototype.setHorizontalPosition = function ( position
) {
4457 if ( [ 'before', 'after', 'start', 'end', 'center' ].indexOf( position
) === -1 ) {
4458 throw new Error( 'Invalid value for horizontal position: ' + position
);
4460 if ( this.horizontalPosition
!== position
) {
4461 this.horizontalPosition
= position
;
4462 if ( this.$floatable
) {
4469 * Toggle positioning.
4471 * Do not turn positioning on until after the element is attached to the DOM and visible.
4473 * @param {boolean} [positioning] Enable positioning, omit to toggle
4475 * @return {OO.ui.Element} The element, for chaining
4477 OO
.ui
.mixin
.FloatableElement
.prototype.togglePositioning = function ( positioning
) {
4478 var closestScrollableOfContainer
;
4480 if ( !this.$floatable
|| !this.$floatableContainer
) {
4484 positioning
= positioning
=== undefined ? !this.positioning
: !!positioning
;
4486 if ( positioning
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4487 OO
.ui
.warnDeprecation( 'FloatableElement#togglePositioning: Before calling this method, the element must be attached to the DOM.' );
4488 this.warnedUnattached
= true;
4491 if ( this.positioning
!== positioning
) {
4492 this.positioning
= positioning
;
4494 closestScrollableOfContainer
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatableContainer
[ 0 ] );
4495 // If the scrollable is the root, we have to listen to scroll events
4496 // on the window because of browser inconsistencies.
4497 if ( $( closestScrollableOfContainer
).is( 'html, body' ) ) {
4498 closestScrollableOfContainer
= OO
.ui
.Element
.static.getWindow( closestScrollableOfContainer
);
4501 if ( positioning
) {
4502 this.$floatableWindow
= $( this.getElementWindow() );
4503 this.$floatableWindow
.on( 'resize', this.onFloatableWindowResizeHandler
);
4505 this.$floatableClosestScrollable
= $( closestScrollableOfContainer
);
4506 this.$floatableClosestScrollable
.on( 'scroll', this.onFloatableScrollHandler
);
4508 // Initial position after visible
4511 if ( this.$floatableWindow
) {
4512 this.$floatableWindow
.off( 'resize', this.onFloatableWindowResizeHandler
);
4513 this.$floatableWindow
= null;
4516 if ( this.$floatableClosestScrollable
) {
4517 this.$floatableClosestScrollable
.off( 'scroll', this.onFloatableScrollHandler
);
4518 this.$floatableClosestScrollable
= null;
4521 this.$floatable
.css( { left
: '', right
: '', top
: '' } );
4529 * Check whether the bottom edge of the given element is within the viewport of the given container.
4532 * @param {jQuery} $element
4533 * @param {jQuery} $container
4536 OO
.ui
.mixin
.FloatableElement
.prototype.isElementInViewport = function ( $element
, $container
) {
4537 var elemRect
, contRect
, topEdgeInBounds
, bottomEdgeInBounds
, leftEdgeInBounds
, rightEdgeInBounds
,
4538 startEdgeInBounds
, endEdgeInBounds
, viewportSpacing
,
4539 direction
= $element
.css( 'direction' );
4541 elemRect
= $element
[ 0 ].getBoundingClientRect();
4542 if ( $container
[ 0 ] === window
) {
4543 viewportSpacing
= OO
.ui
.getViewportSpacing();
4547 right
: document
.documentElement
.clientWidth
,
4548 bottom
: document
.documentElement
.clientHeight
4550 contRect
.top
+= viewportSpacing
.top
;
4551 contRect
.left
+= viewportSpacing
.left
;
4552 contRect
.right
-= viewportSpacing
.right
;
4553 contRect
.bottom
-= viewportSpacing
.bottom
;
4555 contRect
= $container
[ 0 ].getBoundingClientRect();
4558 topEdgeInBounds
= elemRect
.top
>= contRect
.top
&& elemRect
.top
<= contRect
.bottom
;
4559 bottomEdgeInBounds
= elemRect
.bottom
>= contRect
.top
&& elemRect
.bottom
<= contRect
.bottom
;
4560 leftEdgeInBounds
= elemRect
.left
>= contRect
.left
&& elemRect
.left
<= contRect
.right
;
4561 rightEdgeInBounds
= elemRect
.right
>= contRect
.left
&& elemRect
.right
<= contRect
.right
;
4562 if ( direction
=== 'rtl' ) {
4563 startEdgeInBounds
= rightEdgeInBounds
;
4564 endEdgeInBounds
= leftEdgeInBounds
;
4566 startEdgeInBounds
= leftEdgeInBounds
;
4567 endEdgeInBounds
= rightEdgeInBounds
;
4570 if ( this.verticalPosition
=== 'below' && !bottomEdgeInBounds
) {
4573 if ( this.verticalPosition
=== 'above' && !topEdgeInBounds
) {
4576 if ( this.horizontalPosition
=== 'before' && !startEdgeInBounds
) {
4579 if ( this.horizontalPosition
=== 'after' && !endEdgeInBounds
) {
4583 // The other positioning values are all about being inside the container,
4584 // so in those cases all we care about is that any part of the container is visible.
4585 return elemRect
.top
<= contRect
.bottom
&& elemRect
.bottom
>= contRect
.top
&&
4586 elemRect
.left
<= contRect
.right
&& elemRect
.right
>= contRect
.left
;
4590 * Check if the floatable is hidden to the user because it was offscreen.
4592 * @return {boolean} Floatable is out of view
4594 OO
.ui
.mixin
.FloatableElement
.prototype.isFloatableOutOfView = function () {
4595 return this.floatableOutOfView
;
4599 * Position the floatable below its container.
4601 * This should only be done when both of them are attached to the DOM and visible.
4604 * @return {OO.ui.Element} The element, for chaining
4606 OO
.ui
.mixin
.FloatableElement
.prototype.position = function () {
4607 if ( !this.positioning
) {
4612 // To continue, some things need to be true:
4613 // The element must actually be in the DOM
4614 this.isElementAttached() && (
4615 // The closest scrollable is the current window
4616 this.$floatableClosestScrollable
[ 0 ] === this.getElementWindow() ||
4617 // OR is an element in the element's DOM
4618 $.contains( this.getElementDocument(), this.$floatableClosestScrollable
[ 0 ] )
4621 // Abort early if important parts of the widget are no longer attached to the DOM
4625 this.floatableOutOfView
= this.hideWhenOutOfView
&& !this.isElementInViewport( this.$floatableContainer
, this.$floatableClosestScrollable
);
4626 if ( this.floatableOutOfView
) {
4627 this.$floatable
.addClass( 'oo-ui-element-hidden' );
4630 this.$floatable
.removeClass( 'oo-ui-element-hidden' );
4633 this.$floatable
.css( this.computePosition() );
4635 // We updated the position, so re-evaluate the clipping state.
4636 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
4637 // will not notice the need to update itself.)
4638 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
4639 // it not listen to the right events in the right places?
4648 * Compute how #$floatable should be positioned based on the position of #$floatableContainer
4649 * and the positioning settings. This is a helper for #position that shouldn't be called directly,
4650 * but may be overridden by subclasses if they want to change or add to the positioning logic.
4652 * @return {Object} New position to apply with .css(). Keys are 'top', 'left', 'bottom' and 'right'.
4654 OO
.ui
.mixin
.FloatableElement
.prototype.computePosition = function () {
4655 var isBody
, scrollableX
, scrollableY
, containerPos
,
4656 horizScrollbarHeight
, vertScrollbarWidth
, scrollTop
, scrollLeft
,
4657 newPos
= { top
: '', left
: '', bottom
: '', right
: '' },
4658 direction
= this.$floatableContainer
.css( 'direction' ),
4659 $offsetParent
= this.$floatable
.offsetParent();
4661 if ( $offsetParent
.is( 'html' ) ) {
4662 // The innerHeight/Width and clientHeight/Width calculations don't work well on the
4663 // <html> element, but they do work on the <body>
4664 $offsetParent
= $( $offsetParent
[ 0 ].ownerDocument
.body
);
4666 isBody
= $offsetParent
.is( 'body' );
4667 scrollableX
= $offsetParent
.css( 'overflow-x' ) === 'scroll' || $offsetParent
.css( 'overflow-x' ) === 'auto';
4668 scrollableY
= $offsetParent
.css( 'overflow-y' ) === 'scroll' || $offsetParent
.css( 'overflow-y' ) === 'auto';
4670 vertScrollbarWidth
= $offsetParent
.innerWidth() - $offsetParent
.prop( 'clientWidth' );
4671 horizScrollbarHeight
= $offsetParent
.innerHeight() - $offsetParent
.prop( 'clientHeight' );
4672 // We don't need to compute and add scrollTop and scrollLeft if the scrollable container is the body,
4673 // or if it isn't scrollable
4674 scrollTop
= scrollableY
&& !isBody
? $offsetParent
.scrollTop() : 0;
4675 scrollLeft
= scrollableX
&& !isBody
? OO
.ui
.Element
.static.getScrollLeft( $offsetParent
[ 0 ] ) : 0;
4677 // Avoid passing the <body> to getRelativePosition(), because it won't return what we expect
4678 // if the <body> has a margin
4679 containerPos
= isBody
?
4680 this.$floatableContainer
.offset() :
4681 OO
.ui
.Element
.static.getRelativePosition( this.$floatableContainer
, $offsetParent
);
4682 containerPos
.bottom
= containerPos
.top
+ this.$floatableContainer
.outerHeight();
4683 containerPos
.right
= containerPos
.left
+ this.$floatableContainer
.outerWidth();
4684 containerPos
.start
= direction
=== 'rtl' ? containerPos
.right
: containerPos
.left
;
4685 containerPos
.end
= direction
=== 'rtl' ? containerPos
.left
: containerPos
.right
;
4687 if ( this.verticalPosition
=== 'below' ) {
4688 newPos
.top
= containerPos
.bottom
;
4689 } else if ( this.verticalPosition
=== 'above' ) {
4690 newPos
.bottom
= $offsetParent
.outerHeight() - containerPos
.top
;
4691 } else if ( this.verticalPosition
=== 'top' ) {
4692 newPos
.top
= containerPos
.top
;
4693 } else if ( this.verticalPosition
=== 'bottom' ) {
4694 newPos
.bottom
= $offsetParent
.outerHeight() - containerPos
.bottom
;
4695 } else if ( this.verticalPosition
=== 'center' ) {
4696 newPos
.top
= containerPos
.top
+
4697 ( this.$floatableContainer
.height() - this.$floatable
.height() ) / 2;
4700 if ( this.horizontalPosition
=== 'before' ) {
4701 newPos
.end
= containerPos
.start
;
4702 } else if ( this.horizontalPosition
=== 'after' ) {
4703 newPos
.start
= containerPos
.end
;
4704 } else if ( this.horizontalPosition
=== 'start' ) {
4705 newPos
.start
= containerPos
.start
;
4706 } else if ( this.horizontalPosition
=== 'end' ) {
4707 newPos
.end
= containerPos
.end
;
4708 } else if ( this.horizontalPosition
=== 'center' ) {
4709 newPos
.left
= containerPos
.left
+
4710 ( this.$floatableContainer
.width() - this.$floatable
.width() ) / 2;
4713 if ( newPos
.start
!== undefined ) {
4714 if ( direction
=== 'rtl' ) {
4715 newPos
.right
= ( isBody
? $( $offsetParent
[ 0 ].ownerDocument
.documentElement
) : $offsetParent
).outerWidth() - newPos
.start
;
4717 newPos
.left
= newPos
.start
;
4719 delete newPos
.start
;
4721 if ( newPos
.end
!== undefined ) {
4722 if ( direction
=== 'rtl' ) {
4723 newPos
.left
= newPos
.end
;
4725 newPos
.right
= ( isBody
? $( $offsetParent
[ 0 ].ownerDocument
.documentElement
) : $offsetParent
).outerWidth() - newPos
.end
;
4730 // Account for scroll position
4731 if ( newPos
.top
!== '' ) {
4732 newPos
.top
+= scrollTop
;
4734 if ( newPos
.bottom
!== '' ) {
4735 newPos
.bottom
-= scrollTop
;
4737 if ( newPos
.left
!== '' ) {
4738 newPos
.left
+= scrollLeft
;
4740 if ( newPos
.right
!== '' ) {
4741 newPos
.right
-= scrollLeft
;
4744 // Account for scrollbar gutter
4745 if ( newPos
.bottom
!== '' ) {
4746 newPos
.bottom
-= horizScrollbarHeight
;
4748 if ( direction
=== 'rtl' ) {
4749 if ( newPos
.left
!== '' ) {
4750 newPos
.left
-= vertScrollbarWidth
;
4753 if ( newPos
.right
!== '' ) {
4754 newPos
.right
-= vertScrollbarWidth
;
4762 * Element that can be automatically clipped to visible boundaries.
4764 * Whenever the element's natural height changes, you have to call
4765 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
4766 * clipping correctly.
4768 * The dimensions of #$clippableContainer will be compared to the boundaries of the
4769 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
4770 * then #$clippable will be given a fixed reduced height and/or width and will be made
4771 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
4772 * but you can build a static footer by setting #$clippableContainer to an element that contains
4773 * #$clippable and the footer.
4779 * @param {Object} [config] Configuration options
4780 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
4781 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
4782 * omit to use #$clippable
4784 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
4785 // Configuration initialization
4786 config
= config
|| {};
4789 this.$clippable
= null;
4790 this.$clippableContainer
= null;
4791 this.clipping
= false;
4792 this.clippedHorizontally
= false;
4793 this.clippedVertically
= false;
4794 this.$clippableScrollableContainer
= null;
4795 this.$clippableScroller
= null;
4796 this.$clippableWindow
= null;
4797 this.idealWidth
= null;
4798 this.idealHeight
= null;
4799 this.onClippableScrollHandler
= this.clip
.bind( this );
4800 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
4803 if ( config
.$clippableContainer
) {
4804 this.setClippableContainer( config
.$clippableContainer
);
4806 this.setClippableElement( config
.$clippable
|| this.$element
);
4812 * Set clippable element.
4814 * If an element is already set, it will be cleaned up before setting up the new element.
4816 * @param {jQuery} $clippable Element to make clippable
4818 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
4819 if ( this.$clippable
) {
4820 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
4821 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
4822 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4825 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
4830 * Set clippable container.
4832 * This is the container that will be measured when deciding whether to clip. When clipping,
4833 * #$clippable will be resized in order to keep the clippable container fully visible.
4835 * If the clippable container is unset, #$clippable will be used.
4837 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
4839 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableContainer = function ( $clippableContainer
) {
4840 this.$clippableContainer
= $clippableContainer
;
4841 if ( this.$clippable
) {
4849 * Do not turn clipping on until after the element is attached to the DOM and visible.
4851 * @param {boolean} [clipping] Enable clipping, omit to toggle
4853 * @return {OO.ui.Element} The element, for chaining
4855 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
4856 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
4858 if ( clipping
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4859 OO
.ui
.warnDeprecation( 'ClippableElement#toggleClipping: Before calling this method, the element must be attached to the DOM.' );
4860 this.warnedUnattached
= true;
4863 if ( this.clipping
!== clipping
) {
4864 this.clipping
= clipping
;
4866 this.$clippableScrollableContainer
= $( this.getClosestScrollableElementContainer() );
4867 // If the clippable container is the root, we have to listen to scroll events and check
4868 // jQuery.scrollTop on the window because of browser inconsistencies
4869 this.$clippableScroller
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
4870 $( OO
.ui
.Element
.static.getWindow( this.$clippableScrollableContainer
) ) :
4871 this.$clippableScrollableContainer
;
4872 this.$clippableScroller
.on( 'scroll', this.onClippableScrollHandler
);
4873 this.$clippableWindow
= $( this.getElementWindow() )
4874 .on( 'resize', this.onClippableWindowResizeHandler
);
4875 // Initial clip after visible
4878 this.$clippable
.css( {
4886 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4888 this.$clippableScrollableContainer
= null;
4889 this.$clippableScroller
.off( 'scroll', this.onClippableScrollHandler
);
4890 this.$clippableScroller
= null;
4891 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
4892 this.$clippableWindow
= null;
4900 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4902 * @return {boolean} Element will be clipped to the visible area
4904 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
4905 return this.clipping
;
4909 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
4911 * @return {boolean} Part of the element is being clipped
4913 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
4914 return this.clippedHorizontally
|| this.clippedVertically
;
4918 * Check if the right of the element is being clipped by the nearest scrollable container.
4920 * @return {boolean} Part of the element is being clipped
4922 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
4923 return this.clippedHorizontally
;
4927 * Check if the bottom of the element is being clipped by the nearest scrollable container.
4929 * @return {boolean} Part of the element is being clipped
4931 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
4932 return this.clippedVertically
;
4936 * Set the ideal size. These are the dimensions #$clippable will have when it's not being clipped.
4938 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
4939 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
4941 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
4942 this.idealWidth
= width
;
4943 this.idealHeight
= height
;
4945 if ( !this.clipping
) {
4946 // Update dimensions
4947 this.$clippable
.css( { width
: width
, height
: height
} );
4949 // While clipping, idealWidth and idealHeight are not considered
4953 * Return the side of the clippable on which it is "anchored" (aligned to something else).
4954 * ClippableElement will clip the opposite side when reducing element's width.
4956 * Classes that mix in ClippableElement should override this to return 'right' if their
4957 * clippable is absolutely positioned and using 'right: Npx' (and not using 'left').
4958 * If your class also mixes in FloatableElement, this is handled automatically.
4960 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
4961 * always in pixels, even if they were unset or set to 'auto'.)
4963 * When in doubt, 'left' (or 'right' in RTL) is a sane fallback.
4965 * @return {string} 'left' or 'right'
4967 OO
.ui
.mixin
.ClippableElement
.prototype.getHorizontalAnchorEdge = function () {
4968 if ( this.computePosition
&& this.positioning
&& this.computePosition().right
!== '' ) {
4975 * Return the side of the clippable on which it is "anchored" (aligned to something else).
4976 * ClippableElement will clip the opposite side when reducing element's width.
4978 * Classes that mix in ClippableElement should override this to return 'bottom' if their
4979 * clippable is absolutely positioned and using 'bottom: Npx' (and not using 'top').
4980 * If your class also mixes in FloatableElement, this is handled automatically.
4982 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
4983 * always in pixels, even if they were unset or set to 'auto'.)
4985 * When in doubt, 'top' is a sane fallback.
4987 * @return {string} 'top' or 'bottom'
4989 OO
.ui
.mixin
.ClippableElement
.prototype.getVerticalAnchorEdge = function () {
4990 if ( this.computePosition
&& this.positioning
&& this.computePosition().bottom
!== '' ) {
4997 * Clip element to visible boundaries and allow scrolling when needed. You should call this method
4998 * when the element's natural height changes.
5000 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
5001 * overlapped by, the visible area of the nearest scrollable container.
5003 * Because calling clip() when the natural height changes isn't always possible, we also set
5004 * max-height when the element isn't being clipped. This means that if the element tries to grow
5005 * beyond the edge, something reasonable will happen before clip() is called.
5008 * @return {OO.ui.Element} The element, for chaining
5010 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
5011 var extraHeight
, extraWidth
, viewportSpacing
,
5012 desiredWidth
, desiredHeight
, allotedWidth
, allotedHeight
,
5013 naturalWidth
, naturalHeight
, clipWidth
, clipHeight
,
5014 $item
, itemRect
, $viewport
, viewportRect
, availableRect
,
5015 direction
, vertScrollbarWidth
, horizScrollbarHeight
,
5016 // Extra tolerance so that the sloppy code below doesn't result in results that are off
5017 // by one or two pixels. (And also so that we have space to display drop shadows.)
5018 // Chosen by fair dice roll.
5021 if ( !this.clipping
) {
5022 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
5026 function rectIntersection( a
, b
) {
5028 out
.top
= Math
.max( a
.top
, b
.top
);
5029 out
.left
= Math
.max( a
.left
, b
.left
);
5030 out
.bottom
= Math
.min( a
.bottom
, b
.bottom
);
5031 out
.right
= Math
.min( a
.right
, b
.right
);
5035 viewportSpacing
= OO
.ui
.getViewportSpacing();
5037 if ( this.$clippableScrollableContainer
.is( 'html, body' ) ) {
5038 $viewport
= $( this.$clippableScrollableContainer
[ 0 ].ownerDocument
.body
);
5039 // Dimensions of the browser window, rather than the element!
5043 right
: document
.documentElement
.clientWidth
,
5044 bottom
: document
.documentElement
.clientHeight
5046 viewportRect
.top
+= viewportSpacing
.top
;
5047 viewportRect
.left
+= viewportSpacing
.left
;
5048 viewportRect
.right
-= viewportSpacing
.right
;
5049 viewportRect
.bottom
-= viewportSpacing
.bottom
;
5051 $viewport
= this.$clippableScrollableContainer
;
5052 viewportRect
= $viewport
[ 0 ].getBoundingClientRect();
5053 // Convert into a plain object
5054 viewportRect
= $.extend( {}, viewportRect
);
5057 // Account for scrollbar gutter
5058 direction
= $viewport
.css( 'direction' );
5059 vertScrollbarWidth
= $viewport
.innerWidth() - $viewport
.prop( 'clientWidth' );
5060 horizScrollbarHeight
= $viewport
.innerHeight() - $viewport
.prop( 'clientHeight' );
5061 viewportRect
.bottom
-= horizScrollbarHeight
;
5062 if ( direction
=== 'rtl' ) {
5063 viewportRect
.left
+= vertScrollbarWidth
;
5065 viewportRect
.right
-= vertScrollbarWidth
;
5068 // Add arbitrary tolerance
5069 viewportRect
.top
+= buffer
;
5070 viewportRect
.left
+= buffer
;
5071 viewportRect
.right
-= buffer
;
5072 viewportRect
.bottom
-= buffer
;
5074 $item
= this.$clippableContainer
|| this.$clippable
;
5076 extraHeight
= $item
.outerHeight() - this.$clippable
.outerHeight();
5077 extraWidth
= $item
.outerWidth() - this.$clippable
.outerWidth();
5079 itemRect
= $item
[ 0 ].getBoundingClientRect();
5080 // Convert into a plain object
5081 itemRect
= $.extend( {}, itemRect
);
5083 // Item might already be clipped, so we can't just use its dimensions (in case we might need to
5084 // make it larger than before). Extend the rectangle to the maximum size we are allowed to take.
5085 if ( this.getHorizontalAnchorEdge() === 'right' ) {
5086 itemRect
.left
= viewportRect
.left
;
5088 itemRect
.right
= viewportRect
.right
;
5090 if ( this.getVerticalAnchorEdge() === 'bottom' ) {
5091 itemRect
.top
= viewportRect
.top
;
5093 itemRect
.bottom
= viewportRect
.bottom
;
5096 availableRect
= rectIntersection( viewportRect
, itemRect
);
5098 desiredWidth
= Math
.max( 0, availableRect
.right
- availableRect
.left
);
5099 desiredHeight
= Math
.max( 0, availableRect
.bottom
- availableRect
.top
);
5100 // It should never be desirable to exceed the dimensions of the browser viewport... right?
5101 desiredWidth
= Math
.min( desiredWidth
,
5102 document
.documentElement
.clientWidth
- viewportSpacing
.left
- viewportSpacing
.right
);
5103 desiredHeight
= Math
.min( desiredHeight
,
5104 document
.documentElement
.clientHeight
- viewportSpacing
.top
- viewportSpacing
.right
);
5105 allotedWidth
= Math
.ceil( desiredWidth
- extraWidth
);
5106 allotedHeight
= Math
.ceil( desiredHeight
- extraHeight
);
5107 naturalWidth
= this.$clippable
.prop( 'scrollWidth' );
5108 naturalHeight
= this.$clippable
.prop( 'scrollHeight' );
5109 clipWidth
= allotedWidth
< naturalWidth
;
5110 clipHeight
= allotedHeight
< naturalHeight
;
5113 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. See T157672.
5114 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
5115 this.$clippable
.css( 'overflowX', 'scroll' );
5116 void this.$clippable
[ 0 ].offsetHeight
; // Force reflow
5117 this.$clippable
.css( {
5118 width
: Math
.max( 0, allotedWidth
),
5122 this.$clippable
.css( {
5124 width
: this.idealWidth
|| '',
5125 maxWidth
: Math
.max( 0, allotedWidth
)
5129 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. See T157672.
5130 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
5131 this.$clippable
.css( 'overflowY', 'scroll' );
5132 void this.$clippable
[ 0 ].offsetHeight
; // Force reflow
5133 this.$clippable
.css( {
5134 height
: Math
.max( 0, allotedHeight
),
5138 this.$clippable
.css( {
5140 height
: this.idealHeight
|| '',
5141 maxHeight
: Math
.max( 0, allotedHeight
)
5145 // If we stopped clipping in at least one of the dimensions
5146 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
5147 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
5150 this.clippedHorizontally
= clipWidth
;
5151 this.clippedVertically
= clipHeight
;
5157 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
5158 * By default, each popup has an anchor that points toward its origin.
5159 * Please see the [OOUI documentation on MediaWiki.org] [1] for more information and examples.
5161 * Unlike most widgets, PopupWidget is initially hidden and must be shown by calling #toggle.
5164 * // A popup widget.
5165 * var popup = new OO.ui.PopupWidget( {
5166 * $content: $( '<p>Hi there!</p>' ),
5171 * $( 'body' ).append( popup.$element );
5172 * // To display the popup, toggle the visibility to 'true'.
5173 * popup.toggle( true );
5175 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups
5178 * @extends OO.ui.Widget
5179 * @mixins OO.ui.mixin.LabelElement
5180 * @mixins OO.ui.mixin.ClippableElement
5181 * @mixins OO.ui.mixin.FloatableElement
5184 * @param {Object} [config] Configuration options
5185 * @cfg {number|null} [width=320] Width of popup in pixels. Pass `null` to use automatic width.
5186 * @cfg {number|null} [height=null] Height of popup in pixels. Pass `null` to use automatic height.
5187 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
5188 * @cfg {string} [position='below'] Where to position the popup relative to $floatableContainer
5189 * 'above': Put popup above $floatableContainer; anchor points down to the horizontal center
5190 * of $floatableContainer
5191 * 'below': Put popup below $floatableContainer; anchor points up to the horizontal center
5192 * of $floatableContainer
5193 * 'before': Put popup to the left (LTR) / right (RTL) of $floatableContainer; anchor points
5194 * endwards (right/left) to the vertical center of $floatableContainer
5195 * 'after': Put popup to the right (LTR) / left (RTL) of $floatableContainer; anchor points
5196 * startwards (left/right) to the vertical center of $floatableContainer
5197 * @cfg {string} [align='center'] How to align the popup to $floatableContainer
5198 * 'forwards': If position is above/below, move the popup as far endwards (right in LTR, left in RTL)
5199 * as possible while still keeping the anchor within the popup;
5200 * if position is before/after, move the popup as far downwards as possible.
5201 * 'backwards': If position is above/below, move the popup as far startwards (left in LTR, right in RTL)
5202 * as possible while still keeping the anchor within the popup;
5203 * if position in before/after, move the popup as far upwards as possible.
5204 * 'center': Horizontally (if position is above/below) or vertically (before/after) align the center
5205 * of the popup with the center of $floatableContainer.
5206 * 'force-left': Alias for 'forwards' in LTR and 'backwards' in RTL
5207 * 'force-right': Alias for 'backwards' in RTL and 'forwards' in LTR
5208 * @cfg {boolean} [autoFlip=true] Whether to automatically switch the popup's position between
5209 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5210 * desired direction to display the popup without clipping
5211 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
5212 * See the [OOUI docs on MediaWiki][3] for an example.
5213 * [3]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#containerExample
5214 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
5215 * @cfg {jQuery} [$content] Content to append to the popup's body
5216 * @cfg {jQuery} [$footer] Content to append to the popup's footer
5217 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
5218 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
5219 * This config option is only relevant if #autoClose is set to `true`. See the [OOUI documentation on MediaWiki][2]
5221 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#autocloseExample
5222 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
5224 * @cfg {boolean} [padded=false] Add padding to the popup's body
5226 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
5227 // Configuration initialization
5228 config
= config
|| {};
5230 // Parent constructor
5231 OO
.ui
.PopupWidget
.parent
.call( this, config
);
5233 // Properties (must be set before ClippableElement constructor call)
5234 this.$body
= $( '<div>' );
5235 this.$popup
= $( '<div>' );
5237 // Mixin constructors
5238 OO
.ui
.mixin
.LabelElement
.call( this, config
);
5239 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, {
5240 $clippable
: this.$body
,
5241 $clippableContainer
: this.$popup
5243 OO
.ui
.mixin
.FloatableElement
.call( this, config
);
5246 this.$anchor
= $( '<div>' );
5247 // If undefined, will be computed lazily in computePosition()
5248 this.$container
= config
.$container
;
5249 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
5250 this.autoClose
= !!config
.autoClose
;
5251 this.transitionTimeout
= null;
5252 this.anchored
= false;
5253 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
5254 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
5257 this.setSize( config
.width
, config
.height
);
5258 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
5259 this.setAlignment( config
.align
|| 'center' );
5260 this.setPosition( config
.position
|| 'below' );
5261 this.setAutoFlip( config
.autoFlip
=== undefined || config
.autoFlip
);
5262 this.setAutoCloseIgnore( config
.$autoCloseIgnore
);
5263 this.$body
.addClass( 'oo-ui-popupWidget-body' );
5264 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
5266 .addClass( 'oo-ui-popupWidget-popup' )
5267 .append( this.$body
);
5269 .addClass( 'oo-ui-popupWidget' )
5270 .append( this.$popup
, this.$anchor
);
5271 // Move content, which was added to #$element by OO.ui.Widget, to the body
5272 // FIXME This is gross, we should use '$body' or something for the config
5273 if ( config
.$content
instanceof jQuery
) {
5274 this.$body
.append( config
.$content
);
5277 if ( config
.padded
) {
5278 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
5281 if ( config
.head
) {
5282 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
5283 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
5284 this.$head
= $( '<div>' )
5285 .addClass( 'oo-ui-popupWidget-head' )
5286 .append( this.$label
, this.closeButton
.$element
);
5287 this.$popup
.prepend( this.$head
);
5290 if ( config
.$footer
) {
5291 this.$footer
= $( '<div>' )
5292 .addClass( 'oo-ui-popupWidget-footer' )
5293 .append( config
.$footer
);
5294 this.$popup
.append( this.$footer
);
5297 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
5298 // that reference properties not initialized at that time of parent class construction
5299 // TODO: Find a better way to handle post-constructor setup
5300 this.visible
= false;
5301 this.$element
.addClass( 'oo-ui-element-hidden' );
5306 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
5307 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
5308 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
5309 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.FloatableElement
);
5316 * The popup is ready: it is visible and has been positioned and clipped.
5322 * Handles document mouse down events.
5325 * @param {MouseEvent} e Mouse down event
5327 OO
.ui
.PopupWidget
.prototype.onDocumentMouseDown = function ( e
) {
5330 !OO
.ui
.contains( this.$element
.add( this.$autoCloseIgnore
).get(), e
.target
, true )
5332 this.toggle( false );
5336 // Deprecated alias since 0.28.3
5337 OO
.ui
.PopupWidget
.prototype.onMouseDown = function () {
5338 OO
.ui
.warnDeprecation( 'onMouseDown is deprecated, use onDocumentMouseDown instead' );
5339 this.onDocumentMouseDown
.apply( this, arguments
);
5343 * Bind document mouse down listener.
5347 OO
.ui
.PopupWidget
.prototype.bindDocumentMouseDownListener = function () {
5348 // Capture clicks outside popup
5349 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
5350 // We add 'click' event because iOS safari needs to respond to this event.
5351 // We can't use 'touchstart' (as is usually the equivalent to 'mousedown') because
5352 // then it will trigger when scrolling. While iOS Safari has some reported behavior
5353 // of occasionally not emitting 'click' properly, that event seems to be the standard
5354 // that it should be emitting, so we add it to this and will operate the event handler
5355 // on whichever of these events was triggered first
5356 this.getElementDocument().addEventListener( 'click', this.onDocumentMouseDownHandler
, true );
5359 // Deprecated alias since 0.28.3
5360 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
5361 OO
.ui
.warnDeprecation( 'bindMouseDownListener is deprecated, use bindDocumentMouseDownListener instead' );
5362 this.bindDocumentMouseDownListener
.apply( this, arguments
);
5366 * Handles close button click events.
5370 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
5371 if ( this.isVisible() ) {
5372 this.toggle( false );
5377 * Unbind document mouse down listener.
5381 OO
.ui
.PopupWidget
.prototype.unbindDocumentMouseDownListener = function () {
5382 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
5383 this.getElementDocument().removeEventListener( 'click', this.onDocumentMouseDownHandler
, true );
5386 // Deprecated alias since 0.28.3
5387 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
5388 OO
.ui
.warnDeprecation( 'unbindMouseDownListener is deprecated, use unbindDocumentMouseDownListener instead' );
5389 this.unbindDocumentMouseDownListener
.apply( this, arguments
);
5393 * Handles document key down events.
5396 * @param {KeyboardEvent} e Key down event
5398 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
5400 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
5403 this.toggle( false );
5405 e
.stopPropagation();
5410 * Bind document key down listener.
5414 OO
.ui
.PopupWidget
.prototype.bindDocumentKeyDownListener = function () {
5415 this.getElementDocument().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
5418 // Deprecated alias since 0.28.3
5419 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
5420 OO
.ui
.warnDeprecation( 'bindKeyDownListener is deprecated, use bindDocumentKeyDownListener instead' );
5421 this.bindDocumentKeyDownListener
.apply( this, arguments
);
5425 * Unbind document key down listener.
5429 OO
.ui
.PopupWidget
.prototype.unbindDocumentKeyDownListener = function () {
5430 this.getElementDocument().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
5433 // Deprecated alias since 0.28.3
5434 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
5435 OO
.ui
.warnDeprecation( 'unbindKeyDownListener is deprecated, use unbindDocumentKeyDownListener instead' );
5436 this.unbindDocumentKeyDownListener
.apply( this, arguments
);
5440 * Show, hide, or toggle the visibility of the anchor.
5442 * @param {boolean} [show] Show anchor, omit to toggle
5444 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
5445 show
= show
=== undefined ? !this.anchored
: !!show
;
5447 if ( this.anchored
!== show
) {
5449 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
5450 this.$element
.addClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5452 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
5453 this.$element
.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5455 this.anchored
= show
;
5460 * Change which edge the anchor appears on.
5462 * @param {string} edge 'top', 'bottom', 'start' or 'end'
5464 OO
.ui
.PopupWidget
.prototype.setAnchorEdge = function ( edge
) {
5465 if ( [ 'top', 'bottom', 'start', 'end' ].indexOf( edge
) === -1 ) {
5466 throw new Error( 'Invalid value for edge: ' + edge
);
5468 if ( this.anchorEdge
!== null ) {
5469 this.$element
.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5471 this.anchorEdge
= edge
;
5472 if ( this.anchored
) {
5473 this.$element
.addClass( 'oo-ui-popupWidget-anchored-' + edge
);
5478 * Check if the anchor is visible.
5480 * @return {boolean} Anchor is visible
5482 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
5483 return this.anchored
;
5487 * Toggle visibility of the popup. The popup is initially hidden and must be shown by calling
5488 * `.toggle( true )` after its #$element is attached to the DOM.
5490 * Do not show the popup while it is not attached to the DOM. The calculations required to display
5491 * it in the right place and with the right dimensions only work correctly while it is attached.
5492 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
5493 * strictly enforced, so currently it only generates a warning in the browser console.
5498 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
5499 var change
, normalHeight
, oppositeHeight
, normalWidth
, oppositeWidth
;
5500 show
= show
=== undefined ? !this.isVisible() : !!show
;
5502 change
= show
!== this.isVisible();
5504 if ( show
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
5505 OO
.ui
.warnDeprecation( 'PopupWidget#toggle: Before calling this method, the popup must be attached to the DOM.' );
5506 this.warnedUnattached
= true;
5508 if ( show
&& !this.$floatableContainer
&& this.isElementAttached() ) {
5509 // Fall back to the parent node if the floatableContainer is not set
5510 this.setFloatableContainer( this.$element
.parent() );
5513 if ( change
&& show
&& this.autoFlip
) {
5514 // Reset auto-flipping before showing the popup again. It's possible we no longer need to flip
5515 // (e.g. if the user scrolled).
5516 this.isAutoFlipped
= false;
5520 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
5523 this.togglePositioning( show
&& !!this.$floatableContainer
);
5526 if ( this.autoClose
) {
5527 this.bindDocumentMouseDownListener();
5528 this.bindDocumentKeyDownListener();
5530 this.updateDimensions();
5531 this.toggleClipping( true );
5533 if ( this.autoFlip
) {
5534 if ( this.popupPosition
=== 'above' || this.popupPosition
=== 'below' ) {
5535 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5536 // If opening the popup in the normal direction causes it to be clipped, open
5537 // in the opposite one instead
5538 normalHeight
= this.$element
.height();
5539 this.isAutoFlipped
= !this.isAutoFlipped
;
5541 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5542 // If that also causes it to be clipped, open in whichever direction
5543 // we have more space
5544 oppositeHeight
= this.$element
.height();
5545 if ( oppositeHeight
< normalHeight
) {
5546 this.isAutoFlipped
= !this.isAutoFlipped
;
5552 if ( this.popupPosition
=== 'before' || this.popupPosition
=== 'after' ) {
5553 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5554 // If opening the popup in the normal direction causes it to be clipped, open
5555 // in the opposite one instead
5556 normalWidth
= this.$element
.width();
5557 this.isAutoFlipped
= !this.isAutoFlipped
;
5558 // Due to T180173 horizontally clipped PopupWidgets have messed up dimensions,
5559 // which causes positioning to be off. Toggle clipping back and fort to work around.
5560 this.toggleClipping( false );
5562 this.toggleClipping( true );
5563 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5564 // If that also causes it to be clipped, open in whichever direction
5565 // we have more space
5566 oppositeWidth
= this.$element
.width();
5567 if ( oppositeWidth
< normalWidth
) {
5568 this.isAutoFlipped
= !this.isAutoFlipped
;
5569 // Due to T180173 horizontally clipped PopupWidgets have messed up dimensions,
5570 // which causes positioning to be off. Toggle clipping back and fort to work around.
5571 this.toggleClipping( false );
5573 this.toggleClipping( true );
5580 this.emit( 'ready' );
5582 this.toggleClipping( false );
5583 if ( this.autoClose
) {
5584 this.unbindDocumentMouseDownListener();
5585 this.unbindDocumentKeyDownListener();
5594 * Set the size of the popup.
5596 * Changing the size may also change the popup's position depending on the alignment.
5598 * @param {number|null} [width=320] Width in pixels. Pass `null` to use automatic width.
5599 * @param {number|null} [height=null] Height in pixels. Pass `null` to use automatic height.
5600 * @param {boolean} [transition=false] Use a smooth transition
5603 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
5604 this.width
= width
!== undefined ? width
: 320;
5605 this.height
= height
!== undefined ? height
: null;
5606 if ( this.isVisible() ) {
5607 this.updateDimensions( transition
);
5612 * Update the size and position.
5614 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
5615 * be called automatically.
5617 * @param {boolean} [transition=false] Use a smooth transition
5620 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
5623 // Prevent transition from being interrupted
5624 clearTimeout( this.transitionTimeout
);
5626 // Enable transition
5627 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
5633 // Prevent transitioning after transition is complete
5634 this.transitionTimeout
= setTimeout( function () {
5635 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
5638 // Prevent transitioning immediately
5639 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
5646 OO
.ui
.PopupWidget
.prototype.computePosition = function () {
5647 var direction
, align
, vertical
, start
, end
, near
, far
, sizeProp
, popupSize
, anchorSize
, anchorPos
,
5648 anchorOffset
, anchorMargin
, parentPosition
, positionProp
, positionAdjustment
, floatablePos
,
5649 offsetParentPos
, containerPos
, popupPosition
, viewportSpacing
,
5651 anchorCss
= { left
: '', right
: '', top
: '', bottom
: '' },
5652 popupPositionOppositeMap
= {
5660 'force-left': 'backwards',
5661 'force-right': 'forwards'
5664 'force-left': 'forwards',
5665 'force-right': 'backwards'
5677 backwards
: this.anchored
? 'before' : 'end'
5685 if ( !this.$container
) {
5686 // Lazy-initialize $container if not specified in constructor
5687 this.$container
= $( this.getClosestScrollableElementContainer() );
5689 direction
= this.$container
.css( 'direction' );
5691 // Set height and width before we do anything else, since it might cause our measurements
5692 // to change (e.g. due to scrollbars appearing or disappearing), and it also affects centering
5694 width
: this.width
!== null ? this.width
: 'auto',
5695 height
: this.height
!== null ? this.height
: 'auto'
5698 align
= alignMap
[ direction
][ this.align
] || this.align
;
5699 popupPosition
= this.popupPosition
;
5700 if ( this.isAutoFlipped
) {
5701 popupPosition
= popupPositionOppositeMap
[ popupPosition
];
5704 // If the popup is positioned before or after, then the anchor positioning is vertical, otherwise horizontal
5705 vertical
= popupPosition
=== 'before' || popupPosition
=== 'after';
5706 start
= vertical
? 'top' : ( direction
=== 'rtl' ? 'right' : 'left' );
5707 end
= vertical
? 'bottom' : ( direction
=== 'rtl' ? 'left' : 'right' );
5708 near
= vertical
? 'top' : 'left';
5709 far
= vertical
? 'bottom' : 'right';
5710 sizeProp
= vertical
? 'Height' : 'Width';
5711 popupSize
= vertical
? ( this.height
|| this.$popup
.height() ) : ( this.width
|| this.$popup
.width() );
5713 this.setAnchorEdge( anchorEdgeMap
[ popupPosition
] );
5714 this.horizontalPosition
= vertical
? popupPosition
: hPosMap
[ align
];
5715 this.verticalPosition
= vertical
? vPosMap
[ align
] : popupPosition
;
5718 parentPosition
= OO
.ui
.mixin
.FloatableElement
.prototype.computePosition
.call( this );
5719 // Find out which property FloatableElement used for positioning, and adjust that value
5720 positionProp
= vertical
?
5721 ( parentPosition
.top
!== '' ? 'top' : 'bottom' ) :
5722 ( parentPosition
.left
!== '' ? 'left' : 'right' );
5724 // Figure out where the near and far edges of the popup and $floatableContainer are
5725 floatablePos
= this.$floatableContainer
.offset();
5726 floatablePos
[ far
] = floatablePos
[ near
] + this.$floatableContainer
[ 'outer' + sizeProp
]();
5727 // Measure where the offsetParent is and compute our position based on that and parentPosition
5728 offsetParentPos
= this.$element
.offsetParent()[ 0 ] === document
.documentElement
?
5729 { top
: 0, left
: 0 } :
5730 this.$element
.offsetParent().offset();
5732 if ( positionProp
=== near
) {
5733 popupPos
[ near
] = offsetParentPos
[ near
] + parentPosition
[ near
];
5734 popupPos
[ far
] = popupPos
[ near
] + popupSize
;
5736 popupPos
[ far
] = offsetParentPos
[ near
] +
5737 this.$element
.offsetParent()[ 'inner' + sizeProp
]() - parentPosition
[ far
];
5738 popupPos
[ near
] = popupPos
[ far
] - popupSize
;
5741 if ( this.anchored
) {
5742 // Position the anchor (which is positioned relative to the popup) to point to $floatableContainer
5743 anchorPos
= ( floatablePos
[ start
] + floatablePos
[ end
] ) / 2;
5744 anchorOffset
= ( start
=== far
? -1 : 1 ) * ( anchorPos
- popupPos
[ start
] );
5746 // If the anchor is less than 2*anchorSize from either edge, move the popup to make more space
5747 // this.$anchor.width()/height() returns 0 because of the CSS trickery we use, so use scrollWidth/Height
5748 anchorSize
= this.$anchor
[ 0 ][ 'scroll' + sizeProp
];
5749 anchorMargin
= parseFloat( this.$anchor
.css( 'margin-' + start
) );
5750 if ( anchorOffset
+ anchorMargin
< 2 * anchorSize
) {
5751 // Not enough space for the anchor on the start side; pull the popup startwards
5752 positionAdjustment
= ( positionProp
=== start
? -1 : 1 ) *
5753 ( 2 * anchorSize
- ( anchorOffset
+ anchorMargin
) );
5754 } else if ( anchorOffset
+ anchorMargin
> popupSize
- 2 * anchorSize
) {
5755 // Not enough space for the anchor on the end side; pull the popup endwards
5756 positionAdjustment
= ( positionProp
=== end
? -1 : 1 ) *
5757 ( anchorOffset
+ anchorMargin
- ( popupSize
- 2 * anchorSize
) );
5759 positionAdjustment
= 0;
5762 positionAdjustment
= 0;
5765 // Check if the popup will go beyond the edge of this.$container
5766 containerPos
= this.$container
[ 0 ] === document
.documentElement
?
5767 { top
: 0, left
: 0 } :
5768 this.$container
.offset();
5769 containerPos
[ far
] = containerPos
[ near
] + this.$container
[ 'inner' + sizeProp
]();
5770 if ( this.$container
[ 0 ] === document
.documentElement
) {
5771 viewportSpacing
= OO
.ui
.getViewportSpacing();
5772 containerPos
[ near
] += viewportSpacing
[ near
];
5773 containerPos
[ far
] -= viewportSpacing
[ far
];
5775 // Take into account how much the popup will move because of the adjustments we're going to make
5776 popupPos
[ near
] += ( positionProp
=== near
? 1 : -1 ) * positionAdjustment
;
5777 popupPos
[ far
] += ( positionProp
=== near
? 1 : -1 ) * positionAdjustment
;
5778 if ( containerPos
[ near
] + this.containerPadding
> popupPos
[ near
] ) {
5779 // Popup goes beyond the near (left/top) edge, move it to the right/bottom
5780 positionAdjustment
+= ( positionProp
=== near
? 1 : -1 ) *
5781 ( containerPos
[ near
] + this.containerPadding
- popupPos
[ near
] );
5782 } else if ( containerPos
[ far
] - this.containerPadding
< popupPos
[ far
] ) {
5783 // Popup goes beyond the far (right/bottom) edge, move it to the left/top
5784 positionAdjustment
+= ( positionProp
=== far
? 1 : -1 ) *
5785 ( popupPos
[ far
] - ( containerPos
[ far
] - this.containerPadding
) );
5788 if ( this.anchored
) {
5789 // Adjust anchorOffset for positionAdjustment
5790 anchorOffset
+= ( positionProp
=== start
? -1 : 1 ) * positionAdjustment
;
5792 // Position the anchor
5793 anchorCss
[ start
] = anchorOffset
;
5794 this.$anchor
.css( anchorCss
);
5797 // Move the popup if needed
5798 parentPosition
[ positionProp
] += positionAdjustment
;
5800 return parentPosition
;
5804 * Set popup alignment
5806 * @param {string} [align=center] Alignment of the popup, `center`, `force-left`, `force-right`,
5807 * `backwards` or `forwards`.
5809 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
5810 // Validate alignment
5811 if ( [ 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
5814 this.align
= 'center';
5820 * Get popup alignment
5822 * @return {string} Alignment of the popup, `center`, `force-left`, `force-right`,
5823 * `backwards` or `forwards`.
5825 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
5830 * Change the positioning of the popup.
5832 * @param {string} position 'above', 'below', 'before' or 'after'
5834 OO
.ui
.PopupWidget
.prototype.setPosition = function ( position
) {
5835 if ( [ 'above', 'below', 'before', 'after' ].indexOf( position
) === -1 ) {
5838 this.popupPosition
= position
;
5843 * Get popup positioning.
5845 * @return {string} 'above', 'below', 'before' or 'after'
5847 OO
.ui
.PopupWidget
.prototype.getPosition = function () {
5848 return this.popupPosition
;
5852 * Set popup auto-flipping.
5854 * @param {boolean} autoFlip Whether to automatically switch the popup's position between
5855 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5856 * desired direction to display the popup without clipping
5858 OO
.ui
.PopupWidget
.prototype.setAutoFlip = function ( autoFlip
) {
5859 autoFlip
= !!autoFlip
;
5861 if ( this.autoFlip
!== autoFlip
) {
5862 this.autoFlip
= autoFlip
;
5867 * Set which elements will not close the popup when clicked.
5869 * For auto-closing popups, clicks on these elements will not cause the popup to auto-close.
5871 * @param {jQuery} $autoCloseIgnore Elements to ignore for auto-closing
5873 OO
.ui
.PopupWidget
.prototype.setAutoCloseIgnore = function ( $autoCloseIgnore
) {
5874 this.$autoCloseIgnore
= $autoCloseIgnore
;
5878 * Get an ID of the body element, this can be used as the
5879 * `aria-describedby` attribute for an input field.
5881 * @return {string} The ID of the body element
5883 OO
.ui
.PopupWidget
.prototype.getBodyId = function () {
5884 var id
= this.$body
.attr( 'id' );
5885 if ( id
=== undefined ) {
5886 id
= OO
.ui
.generateElementId();
5887 this.$body
.attr( 'id', id
);
5893 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5894 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5895 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5896 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5902 * @param {Object} [config] Configuration options
5903 * @cfg {Object} [popup] Configuration to pass to popup
5904 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5906 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
5907 // Configuration initialization
5908 config
= config
|| {};
5911 this.popup
= new OO
.ui
.PopupWidget( $.extend(
5914 $floatableContainer
: this.$element
5918 $autoCloseIgnore
: this.$element
.add( config
.popup
&& config
.popup
.$autoCloseIgnore
)
5928 * @return {OO.ui.PopupWidget} Popup widget
5930 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
5935 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
5936 * which is used to display additional information or options.
5939 * // Example of a popup button.
5940 * var popupButton = new OO.ui.PopupButtonWidget( {
5941 * label: 'Popup button with options',
5944 * $content: $( '<p>Additional options here.</p>' ),
5946 * align: 'force-left'
5949 * // Append the button to the DOM.
5950 * $( 'body' ).append( popupButton.$element );
5953 * @extends OO.ui.ButtonWidget
5954 * @mixins OO.ui.mixin.PopupElement
5957 * @param {Object} [config] Configuration options
5958 * @cfg {jQuery} [$overlay] Render the popup into a separate layer. This configuration is useful in cases where
5959 * the expanded popup is larger than its containing `<div>`. The specified overlay layer is usually on top of the
5960 * containing `<div>` and has a larger area. By default, the popup uses relative positioning.
5961 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
5963 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
5964 // Configuration initialization
5965 config
= config
|| {};
5967 // Parent constructor
5968 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
5970 // Mixin constructors
5971 OO
.ui
.mixin
.PopupElement
.call( this, config
);
5974 this.$overlay
= ( config
.$overlay
=== true ? OO
.ui
.getDefaultOverlay() : config
.$overlay
) || this.$element
;
5977 this.connect( this, { click
: 'onAction' } );
5981 .addClass( 'oo-ui-popupButtonWidget' );
5983 .addClass( 'oo-ui-popupButtonWidget-popup' )
5984 .toggleClass( 'oo-ui-popupButtonWidget-framed-popup', this.isFramed() )
5985 .toggleClass( 'oo-ui-popupButtonWidget-frameless-popup', !this.isFramed() );
5986 this.$overlay
.append( this.popup
.$element
);
5991 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
5992 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
5997 * Handle the button action being triggered.
6001 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
6002 this.popup
.toggle();
6006 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
6008 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
6013 * @mixins OO.ui.mixin.GroupElement
6016 * @param {Object} [config] Configuration options
6018 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
6019 // Mixin constructors
6020 OO
.ui
.mixin
.GroupElement
.call( this, config
);
6025 OO
.mixinClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
6030 * Set the disabled state of the widget.
6032 * This will also update the disabled state of child widgets.
6034 * @param {boolean} disabled Disable widget
6036 * @return {OO.ui.Widget} The widget, for chaining
6038 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
6042 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
6043 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
6045 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
6047 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6048 this.items
[ i
].updateDisabled();
6056 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
6058 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
6059 * allows bidirectional communication.
6061 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
6069 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
6076 * Check if widget is disabled.
6078 * Checks parent if present, making disabled state inheritable.
6080 * @return {boolean} Widget is disabled
6082 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
6083 return this.disabled
||
6084 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
6088 * Set group element is in.
6090 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
6092 * @return {OO.ui.Widget} The widget, for chaining
6094 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
6096 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
6097 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
6099 // Initialize item disabled states
6100 this.updateDisabled();
6106 * OptionWidgets are special elements that can be selected and configured with data. The
6107 * data is often unique for each option, but it does not have to be. OptionWidgets are used
6108 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
6109 * and examples, please see the [OOUI documentation on MediaWiki][1].
6111 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6114 * @extends OO.ui.Widget
6115 * @mixins OO.ui.mixin.ItemWidget
6116 * @mixins OO.ui.mixin.LabelElement
6117 * @mixins OO.ui.mixin.FlaggedElement
6118 * @mixins OO.ui.mixin.AccessKeyedElement
6121 * @param {Object} [config] Configuration options
6123 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
6124 // Configuration initialization
6125 config
= config
|| {};
6127 // Parent constructor
6128 OO
.ui
.OptionWidget
.parent
.call( this, config
);
6130 // Mixin constructors
6131 OO
.ui
.mixin
.ItemWidget
.call( this );
6132 OO
.ui
.mixin
.LabelElement
.call( this, config
);
6133 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
6134 OO
.ui
.mixin
.AccessKeyedElement
.call( this, config
);
6137 this.selected
= false;
6138 this.highlighted
= false;
6139 this.pressed
= false;
6143 .data( 'oo-ui-optionWidget', this )
6144 // Allow programmatic focussing (and by accesskey), but not tabbing
6145 .attr( 'tabindex', '-1' )
6146 .attr( 'role', 'option' )
6147 .attr( 'aria-selected', 'false' )
6148 .addClass( 'oo-ui-optionWidget' )
6149 .append( this.$label
);
6154 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
6155 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
6156 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
6157 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
6158 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
6160 /* Static Properties */
6163 * Whether this option can be selected. See #setSelected.
6167 * @property {boolean}
6169 OO
.ui
.OptionWidget
.static.selectable
= true;
6172 * Whether this option can be highlighted. See #setHighlighted.
6176 * @property {boolean}
6178 OO
.ui
.OptionWidget
.static.highlightable
= true;
6181 * Whether this option can be pressed. See #setPressed.
6185 * @property {boolean}
6187 OO
.ui
.OptionWidget
.static.pressable
= true;
6190 * Whether this option will be scrolled into view when it is selected.
6194 * @property {boolean}
6196 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
6201 * Check if the option can be selected.
6203 * @return {boolean} Item is selectable
6205 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
6206 return this.constructor.static.selectable
&& !this.disabled
&& this.isVisible();
6210 * Check if the option can be highlighted. A highlight indicates that the option
6211 * may be selected when a user presses enter or clicks. Disabled items cannot
6214 * @return {boolean} Item is highlightable
6216 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
6217 return this.constructor.static.highlightable
&& !this.disabled
&& this.isVisible();
6221 * Check if the option can be pressed. The pressed state occurs when a user mouses
6222 * down on an item, but has not yet let go of the mouse.
6224 * @return {boolean} Item is pressable
6226 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
6227 return this.constructor.static.pressable
&& !this.disabled
&& this.isVisible();
6231 * Check if the option is selected.
6233 * @return {boolean} Item is selected
6235 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
6236 return this.selected
;
6240 * Check if the option is highlighted. A highlight indicates that the
6241 * item may be selected when a user presses enter or clicks.
6243 * @return {boolean} Item is highlighted
6245 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
6246 return this.highlighted
;
6250 * Check if the option is pressed. The pressed state occurs when a user mouses
6251 * down on an item, but has not yet let go of the mouse. The item may appear
6252 * selected, but it will not be selected until the user releases the mouse.
6254 * @return {boolean} Item is pressed
6256 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
6257 return this.pressed
;
6261 * Set the option’s selected state. In general, all modifications to the selection
6262 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
6263 * method instead of this method.
6265 * @param {boolean} [state=false] Select option
6267 * @return {OO.ui.Widget} The widget, for chaining
6269 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
6270 if ( this.constructor.static.selectable
) {
6271 this.selected
= !!state
;
6273 .toggleClass( 'oo-ui-optionWidget-selected', state
)
6274 .attr( 'aria-selected', state
.toString() );
6275 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
6276 this.scrollElementIntoView();
6278 this.updateThemeClasses();
6284 * Set the option’s highlighted state. In general, all programmatic
6285 * modifications to the highlight should be handled by the
6286 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
6287 * method instead of this method.
6289 * @param {boolean} [state=false] Highlight option
6291 * @return {OO.ui.Widget} The widget, for chaining
6293 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
6294 if ( this.constructor.static.highlightable
) {
6295 this.highlighted
= !!state
;
6296 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
6297 this.updateThemeClasses();
6303 * Set the option’s pressed state. In general, all
6304 * programmatic modifications to the pressed state should be handled by the
6305 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
6306 * method instead of this method.
6308 * @param {boolean} [state=false] Press option
6310 * @return {OO.ui.Widget} The widget, for chaining
6312 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
6313 if ( this.constructor.static.pressable
) {
6314 this.pressed
= !!state
;
6315 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
6316 this.updateThemeClasses();
6322 * Get text to match search strings against.
6324 * The default implementation returns the label text, but subclasses
6325 * can override this to provide more complex behavior.
6327 * @return {string|boolean} String to match search string against
6329 OO
.ui
.OptionWidget
.prototype.getMatchText = function () {
6330 var label
= this.getLabel();
6331 return typeof label
=== 'string' ? label
: this.$label
.text();
6335 * A SelectWidget is of a generic selection of options. The OOUI library contains several types of
6336 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
6337 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
6340 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
6341 * information, please see the [OOUI documentation on MediaWiki][1].
6344 * // Example of a select widget with three options
6345 * var select = new OO.ui.SelectWidget( {
6347 * new OO.ui.OptionWidget( {
6349 * label: 'Option One',
6351 * new OO.ui.OptionWidget( {
6353 * label: 'Option Two',
6355 * new OO.ui.OptionWidget( {
6357 * label: 'Option Three',
6361 * $( 'body' ).append( select.$element );
6363 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6367 * @extends OO.ui.Widget
6368 * @mixins OO.ui.mixin.GroupWidget
6371 * @param {Object} [config] Configuration options
6372 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
6373 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
6374 * the [OOUI documentation on MediaWiki] [2] for examples.
6375 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6377 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
6378 // Configuration initialization
6379 config
= config
|| {};
6381 // Parent constructor
6382 OO
.ui
.SelectWidget
.parent
.call( this, config
);
6384 // Mixin constructors
6385 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
6388 this.pressed
= false;
6389 this.selecting
= null;
6390 this.onDocumentMouseUpHandler
= this.onDocumentMouseUp
.bind( this );
6391 this.onDocumentMouseMoveHandler
= this.onDocumentMouseMove
.bind( this );
6392 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
6393 this.onDocumentKeyPressHandler
= this.onDocumentKeyPress
.bind( this );
6394 this.keyPressBuffer
= '';
6395 this.keyPressBufferTimer
= null;
6396 this.blockMouseOverEvents
= 0;
6399 this.connect( this, {
6403 focusin
: this.onFocus
.bind( this ),
6404 mousedown
: this.onMouseDown
.bind( this ),
6405 mouseover
: this.onMouseOver
.bind( this ),
6406 mouseleave
: this.onMouseLeave
.bind( this )
6411 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
6412 .attr( 'role', 'listbox' );
6413 this.setFocusOwner( this.$element
);
6414 if ( Array
.isArray( config
.items
) ) {
6415 this.addItems( config
.items
);
6421 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
6422 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
6429 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
6431 * @param {OO.ui.OptionWidget|null} item Highlighted item
6437 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
6438 * pressed state of an option.
6440 * @param {OO.ui.OptionWidget|null} item Pressed item
6446 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
6448 * @param {OO.ui.OptionWidget|null} item Selected item
6453 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
6454 * @param {OO.ui.OptionWidget} item Chosen item
6460 * An `add` event is emitted when options are added to the select with the #addItems method.
6462 * @param {OO.ui.OptionWidget[]} items Added items
6463 * @param {number} index Index of insertion point
6469 * A `remove` event is emitted when options are removed from the select with the #clearItems
6470 * or #removeItems methods.
6472 * @param {OO.ui.OptionWidget[]} items Removed items
6478 * Handle focus events
6481 * @param {jQuery.Event} event
6483 OO
.ui
.SelectWidget
.prototype.onFocus = function ( event
) {
6485 if ( event
.target
=== this.$element
[ 0 ] ) {
6486 // This widget was focussed, e.g. by the user tabbing to it.
6487 // The styles for focus state depend on one of the items being selected.
6488 if ( !this.findSelectedItem() ) {
6489 item
= this.findFirstSelectableItem();
6492 if ( event
.target
.tabIndex
=== -1 ) {
6493 // One of the options got focussed (and the event bubbled up here).
6494 // They can't be tabbed to, but they can be activated using accesskeys.
6495 // OptionWidgets and focusable UI elements inside them have tabindex="-1" set.
6496 item
= this.findTargetItem( event
);
6498 // There is something actually user-focusable in one of the labels of the options, and the
6499 // user focussed it (e.g. by tabbing to it). Do nothing (especially, don't change the focus).
6505 if ( item
.constructor.static.highlightable
) {
6506 this.highlightItem( item
);
6508 this.selectItem( item
);
6512 if ( event
.target
!== this.$element
[ 0 ] ) {
6513 this.$focusOwner
.focus();
6518 * Handle mouse down events.
6521 * @param {jQuery.Event} e Mouse down event
6522 * @return {undefined/boolean} False to prevent default if event is handled
6524 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
6527 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
6528 this.togglePressed( true );
6529 item
= this.findTargetItem( e
);
6530 if ( item
&& item
.isSelectable() ) {
6531 this.pressItem( item
);
6532 this.selecting
= item
;
6533 this.getElementDocument().addEventListener( 'mouseup', this.onDocumentMouseUpHandler
, true );
6534 this.getElementDocument().addEventListener( 'mousemove', this.onDocumentMouseMoveHandler
, true );
6541 * Handle document mouse up events.
6544 * @param {MouseEvent} e Mouse up event
6545 * @return {undefined/boolean} False to prevent default if event is handled
6547 OO
.ui
.SelectWidget
.prototype.onDocumentMouseUp = function ( e
) {
6550 this.togglePressed( false );
6551 if ( !this.selecting
) {
6552 item
= this.findTargetItem( e
);
6553 if ( item
&& item
.isSelectable() ) {
6554 this.selecting
= item
;
6557 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
&& this.selecting
) {
6558 this.pressItem( null );
6559 this.chooseItem( this.selecting
);
6560 this.selecting
= null;
6563 this.getElementDocument().removeEventListener( 'mouseup', this.onDocumentMouseUpHandler
, true );
6564 this.getElementDocument().removeEventListener( 'mousemove', this.onDocumentMouseMoveHandler
, true );
6569 // Deprecated alias since 0.28.3
6570 OO
.ui
.SelectWidget
.prototype.onMouseUp = function () {
6571 OO
.ui
.warnDeprecation( 'onMouseUp is deprecated, use onDocumentMouseUp instead' );
6572 this.onDocumentMouseUp
.apply( this, arguments
);
6576 * Handle document mouse move events.
6579 * @param {MouseEvent} e Mouse move event
6581 OO
.ui
.SelectWidget
.prototype.onDocumentMouseMove = function ( e
) {
6584 if ( !this.isDisabled() && this.pressed
) {
6585 item
= this.findTargetItem( e
);
6586 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
6587 this.pressItem( item
);
6588 this.selecting
= item
;
6593 // Deprecated alias since 0.28.3
6594 OO
.ui
.SelectWidget
.prototype.onMouseMove = function () {
6595 OO
.ui
.warnDeprecation( 'onMouseMove is deprecated, use onDocumentMouseMove instead' );
6596 this.onDocumentMouseMove
.apply( this, arguments
);
6600 * Handle mouse over events.
6603 * @param {jQuery.Event} e Mouse over event
6604 * @return {undefined/boolean} False to prevent default if event is handled
6606 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
6608 if ( this.blockMouseOverEvents
) {
6611 if ( !this.isDisabled() ) {
6612 item
= this.findTargetItem( e
);
6613 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
6619 * Handle mouse leave events.
6622 * @param {jQuery.Event} e Mouse over event
6623 * @return {undefined/boolean} False to prevent default if event is handled
6625 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
6626 if ( !this.isDisabled() ) {
6627 this.highlightItem( null );
6633 * Handle document key down events.
6636 * @param {KeyboardEvent} e Key down event
6638 OO
.ui
.SelectWidget
.prototype.onDocumentKeyDown = function ( e
) {
6641 currentItem
= this.findHighlightedItem() || this.findSelectedItem();
6643 if ( !this.isDisabled() && this.isVisible() ) {
6644 switch ( e
.keyCode
) {
6645 case OO
.ui
.Keys
.ENTER
:
6646 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
6647 // Was only highlighted, now let's select it. No-op if already selected.
6648 this.chooseItem( currentItem
);
6653 case OO
.ui
.Keys
.LEFT
:
6654 this.clearKeyPressBuffer();
6655 nextItem
= this.findRelativeSelectableItem( currentItem
, -1 );
6658 case OO
.ui
.Keys
.DOWN
:
6659 case OO
.ui
.Keys
.RIGHT
:
6660 this.clearKeyPressBuffer();
6661 nextItem
= this.findRelativeSelectableItem( currentItem
, 1 );
6664 case OO
.ui
.Keys
.ESCAPE
:
6665 case OO
.ui
.Keys
.TAB
:
6666 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
6667 currentItem
.setHighlighted( false );
6669 this.unbindDocumentKeyDownListener();
6670 this.unbindDocumentKeyPressListener();
6671 // Don't prevent tabbing away / defocusing
6677 if ( nextItem
.constructor.static.highlightable
) {
6678 this.highlightItem( nextItem
);
6680 this.chooseItem( nextItem
);
6682 this.scrollItemIntoView( nextItem
);
6687 e
.stopPropagation();
6692 // Deprecated alias since 0.28.3
6693 OO
.ui
.SelectWidget
.prototype.onKeyDown = function () {
6694 OO
.ui
.warnDeprecation( 'onKeyDown is deprecated, use onDocumentKeyDown instead' );
6695 this.onDocumentKeyDown
.apply( this, arguments
);
6699 * Bind document key down listener.
6703 OO
.ui
.SelectWidget
.prototype.bindDocumentKeyDownListener = function () {
6704 this.getElementDocument().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
6707 // Deprecated alias since 0.28.3
6708 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
6709 OO
.ui
.warnDeprecation( 'bindKeyDownListener is deprecated, use bindDocumentKeyDownListener instead' );
6710 this.bindDocumentKeyDownListener
.apply( this, arguments
);
6714 * Unbind document key down listener.
6718 OO
.ui
.SelectWidget
.prototype.unbindDocumentKeyDownListener = function () {
6719 this.getElementDocument().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
6722 // Deprecated alias since 0.28.3
6723 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
6724 OO
.ui
.warnDeprecation( 'unbindKeyDownListener is deprecated, use unbindDocumentKeyDownListener instead' );
6725 this.unbindDocumentKeyDownListener
.apply( this, arguments
);
6729 * Scroll item into view, preventing spurious mouse highlight actions from happening.
6731 * @param {OO.ui.OptionWidget} item Item to scroll into view
6733 OO
.ui
.SelectWidget
.prototype.scrollItemIntoView = function ( item
) {
6735 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling
6736 // and around 100-150 ms after it is finished.
6737 this.blockMouseOverEvents
++;
6738 item
.scrollElementIntoView().done( function () {
6739 setTimeout( function () {
6740 widget
.blockMouseOverEvents
--;
6746 * Clear the key-press buffer
6750 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
6751 if ( this.keyPressBufferTimer
) {
6752 clearTimeout( this.keyPressBufferTimer
);
6753 this.keyPressBufferTimer
= null;
6755 this.keyPressBuffer
= '';
6759 * Handle key press events.
6762 * @param {KeyboardEvent} e Key press event
6763 * @return {undefined/boolean} False to prevent default if event is handled
6765 OO
.ui
.SelectWidget
.prototype.onDocumentKeyPress = function ( e
) {
6766 var c
, filter
, item
;
6768 if ( !e
.charCode
) {
6769 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
6770 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
6775 if ( String
.fromCodePoint
) {
6776 c
= String
.fromCodePoint( e
.charCode
);
6778 c
= String
.fromCharCode( e
.charCode
);
6781 if ( this.keyPressBufferTimer
) {
6782 clearTimeout( this.keyPressBufferTimer
);
6784 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
6786 item
= this.findHighlightedItem() || this.findSelectedItem();
6788 if ( this.keyPressBuffer
=== c
) {
6789 // Common (if weird) special case: typing "xxxx" will cycle through all
6790 // the items beginning with "x".
6792 item
= this.findRelativeSelectableItem( item
, 1 );
6795 this.keyPressBuffer
+= c
;
6798 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
6799 if ( !item
|| !filter( item
) ) {
6800 item
= this.findRelativeSelectableItem( item
, 1, filter
);
6803 if ( this.isVisible() && item
.constructor.static.highlightable
) {
6804 this.highlightItem( item
);
6806 this.chooseItem( item
);
6808 this.scrollItemIntoView( item
);
6812 e
.stopPropagation();
6815 // Deprecated alias since 0.28.3
6816 OO
.ui
.SelectWidget
.prototype.onKeyPress = function () {
6817 OO
.ui
.warnDeprecation( 'onKeyPress is deprecated, use onDocumentKeyPress instead' );
6818 this.onDocumentKeyPress
.apply( this, arguments
);
6822 * Get a matcher for the specific string
6825 * @param {string} s String to match against items
6826 * @param {boolean} [exact=false] Only accept exact matches
6827 * @return {Function} function ( OO.ui.OptionWidget ) => boolean
6829 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
, exact
) {
6832 if ( s
.normalize
) {
6835 s
= exact
? s
.trim() : s
.replace( /^\s+/, '' );
6836 re
= '^\\s*' + s
.replace( /([\\{}()|.?*+\-^$[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
6840 re
= new RegExp( re
, 'i' );
6841 return function ( item
) {
6842 var matchText
= item
.getMatchText();
6843 if ( matchText
.normalize
) {
6844 matchText
= matchText
.normalize();
6846 return re
.test( matchText
);
6851 * Bind document key press listener.
6855 OO
.ui
.SelectWidget
.prototype.bindDocumentKeyPressListener = function () {
6856 this.getElementDocument().addEventListener( 'keypress', this.onDocumentKeyPressHandler
, true );
6859 // Deprecated alias since 0.28.3
6860 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
6861 OO
.ui
.warnDeprecation( 'bindKeyPressListener is deprecated, use bindDocumentKeyPressListener instead' );
6862 this.bindDocumentKeyPressListener
.apply( this, arguments
);
6866 * Unbind document key down listener.
6868 * If you override this, be sure to call this.clearKeyPressBuffer() from your
6873 OO
.ui
.SelectWidget
.prototype.unbindDocumentKeyPressListener = function () {
6874 this.getElementDocument().removeEventListener( 'keypress', this.onDocumentKeyPressHandler
, true );
6875 this.clearKeyPressBuffer();
6878 // Deprecated alias since 0.28.3
6879 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
6880 OO
.ui
.warnDeprecation( 'unbindKeyPressListener is deprecated, use unbindDocumentKeyPressListener instead' );
6881 this.unbindDocumentKeyPressListener
.apply( this, arguments
);
6885 * Visibility change handler
6888 * @param {boolean} visible
6890 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
6892 this.clearKeyPressBuffer();
6897 * Get the closest item to a jQuery.Event.
6900 * @param {jQuery.Event} e
6901 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
6903 OO
.ui
.SelectWidget
.prototype.findTargetItem = function ( e
) {
6904 var $option
= $( e
.target
).closest( '.oo-ui-optionWidget' );
6905 if ( !$option
.closest( '.oo-ui-selectWidget' ).is( this.$element
) ) {
6908 return $option
.data( 'oo-ui-optionWidget' ) || null;
6912 * Find selected item.
6914 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
6916 OO
.ui
.SelectWidget
.prototype.findSelectedItem = function () {
6919 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6920 if ( this.items
[ i
].isSelected() ) {
6921 return this.items
[ i
];
6928 * Find highlighted item.
6930 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
6932 OO
.ui
.SelectWidget
.prototype.findHighlightedItem = function () {
6935 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6936 if ( this.items
[ i
].isHighlighted() ) {
6937 return this.items
[ i
];
6944 * Toggle pressed state.
6946 * Press is a state that occurs when a user mouses down on an item, but
6947 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
6948 * until the user releases the mouse.
6950 * @param {boolean} pressed An option is being pressed
6952 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
6953 if ( pressed
=== undefined ) {
6954 pressed
= !this.pressed
;
6956 if ( pressed
!== this.pressed
) {
6958 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
6959 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
6960 this.pressed
= pressed
;
6965 * Highlight an option. If the `item` param is omitted, no options will be highlighted
6966 * and any existing highlight will be removed. The highlight is mutually exclusive.
6968 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
6971 * @return {OO.ui.Widget} The widget, for chaining
6973 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
6974 var i
, len
, highlighted
,
6977 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6978 highlighted
= this.items
[ i
] === item
;
6979 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
6980 this.items
[ i
].setHighlighted( highlighted
);
6986 this.$focusOwner
.attr( 'aria-activedescendant', item
.getElementId() );
6988 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
6990 this.emit( 'highlight', item
);
6997 * Fetch an item by its label.
6999 * @param {string} label Label of the item to select.
7000 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
7001 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
7003 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
7005 len
= this.items
.length
,
7006 filter
= this.getItemMatcher( label
, true );
7008 for ( i
= 0; i
< len
; i
++ ) {
7009 item
= this.items
[ i
];
7010 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
7017 filter
= this.getItemMatcher( label
, false );
7018 for ( i
= 0; i
< len
; i
++ ) {
7019 item
= this.items
[ i
];
7020 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
7036 * Programmatically select an option by its label. If the item does not exist,
7037 * all options will be deselected.
7039 * @param {string} [label] Label of the item to select.
7040 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
7043 * @return {OO.ui.Widget} The widget, for chaining
7045 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
7046 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
7047 if ( label
=== undefined || !itemFromLabel
) {
7048 return this.selectItem();
7050 return this.selectItem( itemFromLabel
);
7054 * Programmatically select an option by its data. If the `data` parameter is omitted,
7055 * or if the item does not exist, all options will be deselected.
7057 * @param {Object|string} [data] Value of the item to select, omit to deselect all
7060 * @return {OO.ui.Widget} The widget, for chaining
7062 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
7063 var itemFromData
= this.findItemFromData( data
);
7064 if ( data
=== undefined || !itemFromData
) {
7065 return this.selectItem();
7067 return this.selectItem( itemFromData
);
7071 * Programmatically select an option by its reference. If the `item` parameter is omitted,
7072 * all options will be deselected.
7074 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
7077 * @return {OO.ui.Widget} The widget, for chaining
7079 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
7080 var i
, len
, selected
,
7083 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
7084 selected
= this.items
[ i
] === item
;
7085 if ( this.items
[ i
].isSelected() !== selected
) {
7086 this.items
[ i
].setSelected( selected
);
7091 if ( item
&& !item
.constructor.static.highlightable
) {
7093 this.$focusOwner
.attr( 'aria-activedescendant', item
.getElementId() );
7095 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
7098 this.emit( 'select', item
);
7107 * Press is a state that occurs when a user mouses down on an item, but has not
7108 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
7109 * releases the mouse.
7111 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
7114 * @return {OO.ui.Widget} The widget, for chaining
7116 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
7117 var i
, len
, pressed
,
7120 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
7121 pressed
= this.items
[ i
] === item
;
7122 if ( this.items
[ i
].isPressed() !== pressed
) {
7123 this.items
[ i
].setPressed( pressed
);
7128 this.emit( 'press', item
);
7137 * Note that ‘choose’ should never be modified programmatically. A user can choose
7138 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
7139 * use the #selectItem method.
7141 * This method is identical to #selectItem, but may vary in subclasses that take additional action
7142 * when users choose an item with the keyboard or mouse.
7144 * @param {OO.ui.OptionWidget} item Item to choose
7147 * @return {OO.ui.Widget} The widget, for chaining
7149 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
7151 this.selectItem( item
);
7152 this.emit( 'choose', item
);
7159 * Find an option by its position relative to the specified item (or to the start of the option array,
7160 * if item is `null`). The direction in which to search through the option array is specified with a
7161 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
7162 * `null` if there are no options in the array.
7164 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
7165 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
7166 * @param {Function} [filter] Only consider items for which this function returns
7167 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
7168 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
7170 OO
.ui
.SelectWidget
.prototype.findRelativeSelectableItem = function ( item
, direction
, filter
) {
7171 var currentIndex
, nextIndex
, i
,
7172 increase
= direction
> 0 ? 1 : -1,
7173 len
= this.items
.length
;
7175 if ( item
instanceof OO
.ui
.OptionWidget
) {
7176 currentIndex
= this.items
.indexOf( item
);
7177 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
7179 // If no item is selected and moving forward, start at the beginning.
7180 // If moving backward, start at the end.
7181 nextIndex
= direction
> 0 ? 0 : len
- 1;
7184 for ( i
= 0; i
< len
; i
++ ) {
7185 item
= this.items
[ nextIndex
];
7187 item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() &&
7188 ( !filter
|| filter( item
) )
7192 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
7198 * Find the next selectable item or `null` if there are no selectable items.
7199 * Disabled options and menu-section markers and breaks are not selectable.
7201 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
7203 OO
.ui
.SelectWidget
.prototype.findFirstSelectableItem = function () {
7204 return this.findRelativeSelectableItem( null, 1 );
7208 * Add an array of options to the select. Optionally, an index number can be used to
7209 * specify an insertion point.
7211 * @param {OO.ui.OptionWidget[]} items Items to add
7212 * @param {number} [index] Index to insert items after
7215 * @return {OO.ui.Widget} The widget, for chaining
7217 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
7219 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
7221 // Always provide an index, even if it was omitted
7222 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
7228 * Remove the specified array of options from the select. Options will be detached
7229 * from the DOM, not removed, so they can be reused later. To remove all options from
7230 * the select, you may wish to use the #clearItems method instead.
7232 * @param {OO.ui.OptionWidget[]} items Items to remove
7235 * @return {OO.ui.Widget} The widget, for chaining
7237 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
7240 // Deselect items being removed
7241 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
7243 if ( item
.isSelected() ) {
7244 this.selectItem( null );
7249 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
7251 this.emit( 'remove', items
);
7257 * Clear all options from the select. Options will be detached from the DOM, not removed,
7258 * so that they can be reused later. To remove a subset of options from the select, use
7259 * the #removeItems method.
7263 * @return {OO.ui.Widget} The widget, for chaining
7265 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
7266 var items
= this.items
.slice();
7269 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
7272 this.selectItem( null );
7274 this.emit( 'remove', items
);
7280 * Set the DOM element which has focus while the user is interacting with this SelectWidget.
7282 * Currently this is just used to set `aria-activedescendant` on it.
7285 * @param {jQuery} $focusOwner
7287 OO
.ui
.SelectWidget
.prototype.setFocusOwner = function ( $focusOwner
) {
7288 this.$focusOwner
= $focusOwner
;
7292 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
7293 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
7294 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
7295 * options. For more information about options and selects, please see the
7296 * [OOUI documentation on MediaWiki][1].
7299 * // Decorated options in a select widget
7300 * var select = new OO.ui.SelectWidget( {
7302 * new OO.ui.DecoratedOptionWidget( {
7304 * label: 'Option with icon',
7307 * new OO.ui.DecoratedOptionWidget( {
7309 * label: 'Option with indicator',
7314 * $( 'body' ).append( select.$element );
7316 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7319 * @extends OO.ui.OptionWidget
7320 * @mixins OO.ui.mixin.IconElement
7321 * @mixins OO.ui.mixin.IndicatorElement
7324 * @param {Object} [config] Configuration options
7326 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
7327 // Parent constructor
7328 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
7330 // Mixin constructors
7331 OO
.ui
.mixin
.IconElement
.call( this, config
);
7332 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
7336 .addClass( 'oo-ui-decoratedOptionWidget' )
7337 .prepend( this.$icon
)
7338 .append( this.$indicator
);
7343 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
7344 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
7345 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
7348 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
7349 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
7350 * the [OOUI documentation on MediaWiki] [1] for more information.
7352 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
7355 * @extends OO.ui.DecoratedOptionWidget
7358 * @param {Object} [config] Configuration options
7360 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
7361 // Parent constructor
7362 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
7365 this.checkIcon
= new OO
.ui
.IconWidget( {
7367 classes
: [ 'oo-ui-menuOptionWidget-checkIcon' ]
7372 .prepend( this.checkIcon
.$element
)
7373 .addClass( 'oo-ui-menuOptionWidget' );
7378 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
7380 /* Static Properties */
7386 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
7389 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
7390 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
7393 * var myDropdown = new OO.ui.DropdownWidget( {
7396 * new OO.ui.MenuSectionOptionWidget( {
7399 * new OO.ui.MenuOptionWidget( {
7401 * label: 'Welsh Corgi'
7403 * new OO.ui.MenuOptionWidget( {
7405 * label: 'Standard Poodle'
7407 * new OO.ui.MenuSectionOptionWidget( {
7410 * new OO.ui.MenuOptionWidget( {
7417 * $( 'body' ).append( myDropdown.$element );
7420 * @extends OO.ui.DecoratedOptionWidget
7423 * @param {Object} [config] Configuration options
7425 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
7426 // Parent constructor
7427 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
7430 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' )
7431 .removeAttr( 'role aria-selected' );
7436 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
7438 /* Static Properties */
7444 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
7450 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
7453 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
7454 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
7455 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
7456 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
7457 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
7458 * and customized to be opened, closed, and displayed as needed.
7460 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
7461 * mouse outside the menu.
7463 * Menus also have support for keyboard interaction:
7465 * - Enter/Return key: choose and select a menu option
7466 * - Up-arrow key: highlight the previous menu option
7467 * - Down-arrow key: highlight the next menu option
7468 * - Esc key: hide the menu
7470 * Unlike most widgets, MenuSelectWidget is initially hidden and must be shown by calling #toggle.
7472 * Please see the [OOUI documentation on MediaWiki][1] for more information.
7473 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7476 * @extends OO.ui.SelectWidget
7477 * @mixins OO.ui.mixin.ClippableElement
7478 * @mixins OO.ui.mixin.FloatableElement
7481 * @param {Object} [config] Configuration options
7482 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
7483 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
7484 * and {@link OO.ui.mixin.LookupElement LookupElement}
7485 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
7486 * the text the user types. This config is used by {@link OO.ui.TagMultiselectWidget TagMultiselectWidget}
7487 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
7488 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
7489 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
7490 * that button, unless the button (or its parent widget) is passed in here.
7491 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
7492 * @cfg {jQuery} [$autoCloseIgnore] If these elements are clicked, don't auto-hide the menu.
7493 * @cfg {boolean} [hideOnChoose=true] Hide the menu when the user chooses an option.
7494 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
7495 * @cfg {boolean} [highlightOnFilter] Highlight the first result when filtering
7496 * @cfg {number} [width] Width of the menu
7498 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
7499 // Configuration initialization
7500 config
= config
|| {};
7502 // Parent constructor
7503 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
7505 // Mixin constructors
7506 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
7507 OO
.ui
.mixin
.FloatableElement
.call( this, config
);
7509 // Initial vertical positions other than 'center' will result in
7510 // the menu being flipped if there is not enough space in the container.
7511 // Store the original position so we know what to reset to.
7512 this.originalVerticalPosition
= this.verticalPosition
;
7515 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
7516 this.hideOnChoose
= config
.hideOnChoose
=== undefined || !!config
.hideOnChoose
;
7517 this.filterFromInput
= !!config
.filterFromInput
;
7518 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
7519 this.$widget
= config
.widget
? config
.widget
.$element
: null;
7520 this.$autoCloseIgnore
= config
.$autoCloseIgnore
|| $( [] );
7521 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
7522 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
7523 this.highlightOnFilter
= !!config
.highlightOnFilter
;
7524 this.width
= config
.width
;
7527 this.$element
.addClass( 'oo-ui-menuSelectWidget' );
7528 if ( config
.widget
) {
7529 this.setFocusOwner( config
.widget
.$tabIndexed
);
7532 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
7533 // that reference properties not initialized at that time of parent class construction
7534 // TODO: Find a better way to handle post-constructor setup
7535 this.visible
= false;
7536 this.$element
.addClass( 'oo-ui-element-hidden' );
7541 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
7542 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
7543 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.FloatableElement
);
7550 * The menu is ready: it is visible and has been positioned and clipped.
7553 /* Static properties */
7556 * Positions to flip to if there isn't room in the container for the
7557 * menu in a specific direction.
7559 * @property {Object.<string,string>}
7561 OO
.ui
.MenuSelectWidget
.static.flippedPositions
= {
7571 * Handles document mouse down events.
7574 * @param {MouseEvent} e Mouse down event
7576 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
7580 this.$element
.add( this.$widget
).add( this.$autoCloseIgnore
).get(),
7585 this.toggle( false );
7592 OO
.ui
.MenuSelectWidget
.prototype.onDocumentKeyDown = function ( e
) {
7593 var currentItem
= this.findHighlightedItem() || this.findSelectedItem();
7595 if ( !this.isDisabled() && this.isVisible() ) {
7596 switch ( e
.keyCode
) {
7597 case OO
.ui
.Keys
.LEFT
:
7598 case OO
.ui
.Keys
.RIGHT
:
7599 // Do nothing if a text field is associated, arrow keys will be handled natively
7600 if ( !this.$input
) {
7601 OO
.ui
.MenuSelectWidget
.parent
.prototype.onDocumentKeyDown
.call( this, e
);
7604 case OO
.ui
.Keys
.ESCAPE
:
7605 case OO
.ui
.Keys
.TAB
:
7606 if ( currentItem
) {
7607 currentItem
.setHighlighted( false );
7609 this.toggle( false );
7610 // Don't prevent tabbing away, prevent defocusing
7611 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
7613 e
.stopPropagation();
7617 OO
.ui
.MenuSelectWidget
.parent
.prototype.onDocumentKeyDown
.call( this, e
);
7624 * Update menu item visibility and clipping after input changes (if filterFromInput is enabled)
7625 * or after items were added/removed (always).
7629 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
7630 var i
, item
, items
, visible
, section
, sectionEmpty
, filter
, exactFilter
,
7632 len
= this.items
.length
,
7633 showAll
= !this.isVisible(),
7636 if ( this.$input
&& this.filterFromInput
) {
7637 filter
= showAll
? null : this.getItemMatcher( this.$input
.val() );
7638 exactFilter
= this.getItemMatcher( this.$input
.val(), true );
7639 // Hide non-matching options, and also hide section headers if all options
7640 // in their section are hidden.
7641 for ( i
= 0; i
< len
; i
++ ) {
7642 item
= this.items
[ i
];
7643 if ( item
instanceof OO
.ui
.MenuSectionOptionWidget
) {
7645 // If the previous section was empty, hide its header
7646 section
.toggle( showAll
|| !sectionEmpty
);
7649 sectionEmpty
= true;
7650 } else if ( item
instanceof OO
.ui
.OptionWidget
) {
7651 visible
= showAll
|| filter( item
);
7652 exactMatch
= exactMatch
|| exactFilter( item
);
7653 anyVisible
= anyVisible
|| visible
;
7654 sectionEmpty
= sectionEmpty
&& !visible
;
7655 item
.toggle( visible
);
7658 // Process the final section
7660 section
.toggle( showAll
|| !sectionEmpty
);
7663 if ( anyVisible
&& this.items
.length
&& !exactMatch
) {
7664 this.scrollItemIntoView( this.items
[ 0 ] );
7667 this.$element
.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible
);
7669 if ( this.highlightOnFilter
) {
7670 // Highlight the first item on the list
7672 items
= this.getItems();
7673 for ( i
= 0; i
< items
.length
; i
++ ) {
7674 if ( items
[ i
].isVisible() ) {
7679 this.highlightItem( item
);
7684 // Reevaluate clipping
7691 OO
.ui
.MenuSelectWidget
.prototype.bindDocumentKeyDownListener = function () {
7692 if ( this.$input
) {
7693 this.$input
.on( 'keydown', this.onDocumentKeyDownHandler
);
7695 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindDocumentKeyDownListener
.call( this );
7702 OO
.ui
.MenuSelectWidget
.prototype.unbindDocumentKeyDownListener = function () {
7703 if ( this.$input
) {
7704 this.$input
.off( 'keydown', this.onDocumentKeyDownHandler
);
7706 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindDocumentKeyDownListener
.call( this );
7713 OO
.ui
.MenuSelectWidget
.prototype.bindDocumentKeyPressListener = function () {
7714 if ( this.$input
) {
7715 if ( this.filterFromInput
) {
7716 this.$input
.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
7717 this.updateItemVisibility();
7720 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindDocumentKeyPressListener
.call( this );
7727 OO
.ui
.MenuSelectWidget
.prototype.unbindDocumentKeyPressListener = function () {
7728 if ( this.$input
) {
7729 if ( this.filterFromInput
) {
7730 this.$input
.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
7731 this.updateItemVisibility();
7734 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindDocumentKeyPressListener
.call( this );
7741 * When a user chooses an item, the menu is closed, unless the hideOnChoose config option is set to false.
7743 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
7744 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
7746 * @param {OO.ui.OptionWidget} item Item to choose
7748 * @return {OO.ui.Widget} The widget, for chaining
7750 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
7751 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
7752 if ( this.hideOnChoose
) {
7753 this.toggle( false );
7761 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
7763 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
7765 this.updateItemVisibility();
7773 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
7775 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
7777 this.updateItemVisibility();
7785 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
7787 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
7789 this.updateItemVisibility();
7795 * Toggle visibility of the menu. The menu is initially hidden and must be shown by calling
7796 * `.toggle( true )` after its #$element is attached to the DOM.
7798 * Do not show the menu while it is not attached to the DOM. The calculations required to display
7799 * it in the right place and with the right dimensions only work correctly while it is attached.
7800 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
7801 * strictly enforced, so currently it only generates a warning in the browser console.
7806 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
7807 var change
, originalHeight
, flippedHeight
;
7809 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
7810 change
= visible
!== this.isVisible();
7812 if ( visible
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
7813 OO
.ui
.warnDeprecation( 'MenuSelectWidget#toggle: Before calling this method, the menu must be attached to the DOM.' );
7814 this.warnedUnattached
= true;
7817 if ( change
&& visible
) {
7818 // Reset position before showing the popup again. It's possible we no longer need to flip
7819 // (e.g. if the user scrolled).
7820 this.setVerticalPosition( this.originalVerticalPosition
);
7824 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
7830 this.setIdealSize( this.width
);
7831 } else if ( this.$floatableContainer
) {
7832 this.$clippable
.css( 'width', 'auto' );
7834 this.$floatableContainer
[ 0 ].offsetWidth
> this.$clippable
[ 0 ].offsetWidth
?
7835 // Dropdown is smaller than handle so expand to width
7836 this.$floatableContainer
[ 0 ].offsetWidth
:
7837 // Dropdown is larger than handle so auto size
7840 this.$clippable
.css( 'width', '' );
7843 this.togglePositioning( !!this.$floatableContainer
);
7844 this.toggleClipping( true );
7846 this.bindDocumentKeyDownListener();
7847 this.bindDocumentKeyPressListener();
7850 ( this.isClippedVertically() || this.isFloatableOutOfView() ) &&
7851 this.originalVerticalPosition
!== 'center'
7853 // If opening the menu in one direction causes it to be clipped, flip it
7854 originalHeight
= this.$element
.height();
7855 this.setVerticalPosition(
7856 this.constructor.static.flippedPositions
[ this.originalVerticalPosition
]
7858 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
7859 // If flipping also causes it to be clipped, open in whichever direction
7860 // we have more space
7861 flippedHeight
= this.$element
.height();
7862 if ( originalHeight
> flippedHeight
) {
7863 this.setVerticalPosition( this.originalVerticalPosition
);
7867 // Note that we do not flip the menu's opening direction if the clipping changes
7868 // later (e.g. after the user scrolls), that seems like it would be annoying
7870 this.$focusOwner
.attr( 'aria-expanded', 'true' );
7872 if ( this.findSelectedItem() ) {
7873 this.$focusOwner
.attr( 'aria-activedescendant', this.findSelectedItem().getElementId() );
7874 this.findSelectedItem().scrollElementIntoView( { duration
: 0 } );
7878 if ( this.autoHide
) {
7879 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
7882 this.emit( 'ready' );
7884 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
7885 this.unbindDocumentKeyDownListener();
7886 this.unbindDocumentKeyPressListener();
7887 this.$focusOwner
.attr( 'aria-expanded', 'false' );
7888 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
7889 this.togglePositioning( false );
7890 this.toggleClipping( false );
7898 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
7899 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
7900 * users can interact with it.
7902 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7903 * OO.ui.DropdownInputWidget instead.
7906 * // Example: A DropdownWidget with a menu that contains three options
7907 * var dropDown = new OO.ui.DropdownWidget( {
7908 * label: 'Dropdown menu: Select a menu option',
7911 * new OO.ui.MenuOptionWidget( {
7915 * new OO.ui.MenuOptionWidget( {
7919 * new OO.ui.MenuOptionWidget( {
7927 * $( 'body' ).append( dropDown.$element );
7929 * dropDown.getMenu().selectItemByData( 'b' );
7931 * dropDown.getMenu().findSelectedItem().getData(); // returns 'b'
7933 * For more information, please see the [OOUI documentation on MediaWiki] [1].
7935 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
7938 * @extends OO.ui.Widget
7939 * @mixins OO.ui.mixin.IconElement
7940 * @mixins OO.ui.mixin.IndicatorElement
7941 * @mixins OO.ui.mixin.LabelElement
7942 * @mixins OO.ui.mixin.TitledElement
7943 * @mixins OO.ui.mixin.TabIndexedElement
7946 * @param {Object} [config] Configuration options
7947 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.MenuSelectWidget menu select widget}
7948 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
7949 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
7950 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
7951 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
7953 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
7954 // Configuration initialization
7955 config
= $.extend( { indicator
: 'down' }, config
);
7957 // Parent constructor
7958 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
7960 // Properties (must be set before TabIndexedElement constructor call)
7961 this.$handle
= $( '<span>' );
7962 this.$overlay
= ( config
.$overlay
=== true ? OO
.ui
.getDefaultOverlay() : config
.$overlay
) || this.$element
;
7964 // Mixin constructors
7965 OO
.ui
.mixin
.IconElement
.call( this, config
);
7966 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
7967 OO
.ui
.mixin
.LabelElement
.call( this, config
);
7968 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
7969 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
7972 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend( {
7974 $floatableContainer
: this.$element
7979 click
: this.onClick
.bind( this ),
7980 keydown
: this.onKeyDown
.bind( this ),
7981 // Hack? Handle type-to-search when menu is not expanded and not handling its own events
7982 keypress
: this.menu
.onDocumentKeyPressHandler
,
7983 blur
: this.menu
.clearKeyPressBuffer
.bind( this.menu
)
7985 this.menu
.connect( this, {
7986 select
: 'onMenuSelect',
7987 toggle
: 'onMenuToggle'
7992 .addClass( 'oo-ui-dropdownWidget-handle' )
7995 'aria-owns': this.menu
.getElementId(),
7996 'aria-autocomplete': 'list'
7998 .append( this.$icon
, this.$label
, this.$indicator
);
8000 .addClass( 'oo-ui-dropdownWidget' )
8001 .append( this.$handle
);
8002 this.$overlay
.append( this.menu
.$element
);
8007 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
8008 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
8009 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
8010 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
8011 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
8012 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
8019 * @return {OO.ui.MenuSelectWidget} Menu of widget
8021 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
8026 * Handles menu select events.
8029 * @param {OO.ui.MenuOptionWidget} item Selected menu item
8031 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
8035 this.setLabel( null );
8039 selectedLabel
= item
.getLabel();
8041 // If the label is a DOM element, clone it, because setLabel will append() it
8042 if ( selectedLabel
instanceof jQuery
) {
8043 selectedLabel
= selectedLabel
.clone();
8046 this.setLabel( selectedLabel
);
8050 * Handle menu toggle events.
8053 * @param {boolean} isVisible Open state of the menu
8055 OO
.ui
.DropdownWidget
.prototype.onMenuToggle = function ( isVisible
) {
8056 this.$element
.toggleClass( 'oo-ui-dropdownWidget-open', isVisible
);
8059 this.$element
.hasClass( 'oo-ui-dropdownWidget-open' ).toString()
8064 * Handle mouse click events.
8067 * @param {jQuery.Event} e Mouse click event
8068 * @return {undefined/boolean} False to prevent default if event is handled
8070 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
8071 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
8078 * Handle key down events.
8081 * @param {jQuery.Event} e Key down event
8082 * @return {undefined/boolean} False to prevent default if event is handled
8084 OO
.ui
.DropdownWidget
.prototype.onKeyDown = function ( e
) {
8086 !this.isDisabled() &&
8088 e
.which
=== OO
.ui
.Keys
.ENTER
||
8090 e
.which
=== OO
.ui
.Keys
.SPACE
&&
8091 // Avoid conflicts with type-to-search, see SelectWidget#onKeyPress.
8092 // Space only closes the menu is the user is not typing to search.
8093 this.menu
.keyPressBuffer
=== ''
8096 !this.menu
.isVisible() &&
8098 e
.which
=== OO
.ui
.Keys
.UP
||
8099 e
.which
=== OO
.ui
.Keys
.DOWN
8110 * RadioOptionWidget is an option widget that looks like a radio button.
8111 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
8112 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8114 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8117 * @extends OO.ui.OptionWidget
8120 * @param {Object} [config] Configuration options
8122 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
8123 // Configuration initialization
8124 config
= config
|| {};
8126 // Properties (must be done before parent constructor which calls #setDisabled)
8127 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
8129 // Parent constructor
8130 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
8133 // Remove implicit role, we're handling it ourselves
8134 this.radio
.$input
.attr( 'role', 'presentation' );
8136 .addClass( 'oo-ui-radioOptionWidget' )
8137 .attr( 'role', 'radio' )
8138 .attr( 'aria-checked', 'false' )
8139 .removeAttr( 'aria-selected' )
8140 .prepend( this.radio
.$element
);
8145 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
8147 /* Static Properties */
8153 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
8159 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
8165 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
8171 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
8178 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
8179 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
8181 this.radio
.setSelected( state
);
8183 .attr( 'aria-checked', state
.toString() )
8184 .removeAttr( 'aria-selected' );
8192 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
8193 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
8195 this.radio
.setDisabled( this.isDisabled() );
8201 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
8202 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
8203 * an interface for adding, removing and selecting options.
8204 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8206 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8207 * OO.ui.RadioSelectInputWidget instead.
8210 * // A RadioSelectWidget with RadioOptions.
8211 * var option1 = new OO.ui.RadioOptionWidget( {
8213 * label: 'Selected radio option'
8216 * var option2 = new OO.ui.RadioOptionWidget( {
8218 * label: 'Unselected radio option'
8221 * var radioSelect=new OO.ui.RadioSelectWidget( {
8222 * items: [ option1, option2 ]
8225 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
8226 * radioSelect.selectItem( option1 );
8228 * $( 'body' ).append( radioSelect.$element );
8230 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8234 * @extends OO.ui.SelectWidget
8235 * @mixins OO.ui.mixin.TabIndexedElement
8238 * @param {Object} [config] Configuration options
8240 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
8241 // Parent constructor
8242 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
8244 // Mixin constructors
8245 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
8249 focus
: this.bindDocumentKeyDownListener
.bind( this ),
8250 blur
: this.unbindDocumentKeyDownListener
.bind( this )
8255 .addClass( 'oo-ui-radioSelectWidget' )
8256 .attr( 'role', 'radiogroup' );
8261 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
8262 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
8265 * MultioptionWidgets are special elements that can be selected and configured with data. The
8266 * data is often unique for each option, but it does not have to be. MultioptionWidgets are used
8267 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
8268 * and examples, please see the [OOUI documentation on MediaWiki][1].
8270 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Multioptions
8273 * @extends OO.ui.Widget
8274 * @mixins OO.ui.mixin.ItemWidget
8275 * @mixins OO.ui.mixin.LabelElement
8278 * @param {Object} [config] Configuration options
8279 * @cfg {boolean} [selected=false] Whether the option is initially selected
8281 OO
.ui
.MultioptionWidget
= function OoUiMultioptionWidget( config
) {
8282 // Configuration initialization
8283 config
= config
|| {};
8285 // Parent constructor
8286 OO
.ui
.MultioptionWidget
.parent
.call( this, config
);
8288 // Mixin constructors
8289 OO
.ui
.mixin
.ItemWidget
.call( this );
8290 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8293 this.selected
= null;
8297 .addClass( 'oo-ui-multioptionWidget' )
8298 .append( this.$label
);
8299 this.setSelected( config
.selected
);
8304 OO
.inheritClass( OO
.ui
.MultioptionWidget
, OO
.ui
.Widget
);
8305 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.ItemWidget
);
8306 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.LabelElement
);
8313 * A change event is emitted when the selected state of the option changes.
8315 * @param {boolean} selected Whether the option is now selected
8321 * Check if the option is selected.
8323 * @return {boolean} Item is selected
8325 OO
.ui
.MultioptionWidget
.prototype.isSelected = function () {
8326 return this.selected
;
8330 * Set the option’s selected state. In general, all modifications to the selection
8331 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
8332 * method instead of this method.
8334 * @param {boolean} [state=false] Select option
8336 * @return {OO.ui.Widget} The widget, for chaining
8338 OO
.ui
.MultioptionWidget
.prototype.setSelected = function ( state
) {
8340 if ( this.selected
!== state
) {
8341 this.selected
= state
;
8342 this.emit( 'change', state
);
8343 this.$element
.toggleClass( 'oo-ui-multioptionWidget-selected', state
);
8349 * MultiselectWidget allows selecting multiple options from a list.
8351 * For more information about menus and options, please see the [OOUI documentation on MediaWiki][1].
8353 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
8357 * @extends OO.ui.Widget
8358 * @mixins OO.ui.mixin.GroupWidget
8361 * @param {Object} [config] Configuration options
8362 * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
8364 OO
.ui
.MultiselectWidget
= function OoUiMultiselectWidget( config
) {
8365 // Parent constructor
8366 OO
.ui
.MultiselectWidget
.parent
.call( this, config
);
8368 // Configuration initialization
8369 config
= config
|| {};
8371 // Mixin constructors
8372 OO
.ui
.mixin
.GroupWidget
.call( this, config
);
8375 this.aggregate( { change
: 'select' } );
8376 // This is mostly for compatibility with TagMultiselectWidget... normally, 'change' is emitted
8377 // by GroupElement only when items are added/removed
8378 this.connect( this, { select
: [ 'emit', 'change' ] } );
8381 if ( config
.items
) {
8382 this.addItems( config
.items
);
8384 this.$group
.addClass( 'oo-ui-multiselectWidget-group' );
8385 this.$element
.addClass( 'oo-ui-multiselectWidget' )
8386 .append( this.$group
);
8391 OO
.inheritClass( OO
.ui
.MultiselectWidget
, OO
.ui
.Widget
);
8392 OO
.mixinClass( OO
.ui
.MultiselectWidget
, OO
.ui
.mixin
.GroupWidget
);
8399 * A change event is emitted when the set of items changes, or an item is selected or deselected.
8405 * A select event is emitted when an item is selected or deselected.
8411 * Find options that are selected.
8413 * @return {OO.ui.MultioptionWidget[]} Selected options
8415 OO
.ui
.MultiselectWidget
.prototype.findSelectedItems = function () {
8416 return this.items
.filter( function ( item
) {
8417 return item
.isSelected();
8422 * Find the data of options that are selected.
8424 * @return {Object[]|string[]} Values of selected options
8426 OO
.ui
.MultiselectWidget
.prototype.findSelectedItemsData = function () {
8427 return this.findSelectedItems().map( function ( item
) {
8433 * Select options by reference. Options not mentioned in the `items` array will be deselected.
8435 * @param {OO.ui.MultioptionWidget[]} items Items to select
8437 * @return {OO.ui.Widget} The widget, for chaining
8439 OO
.ui
.MultiselectWidget
.prototype.selectItems = function ( items
) {
8440 this.items
.forEach( function ( item
) {
8441 var selected
= items
.indexOf( item
) !== -1;
8442 item
.setSelected( selected
);
8448 * Select items by their data. Options not mentioned in the `datas` array will be deselected.
8450 * @param {Object[]|string[]} datas Values of items to select
8452 * @return {OO.ui.Widget} The widget, for chaining
8454 OO
.ui
.MultiselectWidget
.prototype.selectItemsByData = function ( datas
) {
8457 items
= datas
.map( function ( data
) {
8458 return widget
.findItemFromData( data
);
8460 this.selectItems( items
);
8465 * CheckboxMultioptionWidget is an option widget that looks like a checkbox.
8466 * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
8467 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8469 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8472 * @extends OO.ui.MultioptionWidget
8475 * @param {Object} [config] Configuration options
8477 OO
.ui
.CheckboxMultioptionWidget
= function OoUiCheckboxMultioptionWidget( config
) {
8478 // Configuration initialization
8479 config
= config
|| {};
8481 // Properties (must be done before parent constructor which calls #setDisabled)
8482 this.checkbox
= new OO
.ui
.CheckboxInputWidget();
8484 // Parent constructor
8485 OO
.ui
.CheckboxMultioptionWidget
.parent
.call( this, config
);
8488 this.checkbox
.on( 'change', this.onCheckboxChange
.bind( this ) );
8489 this.$element
.on( 'keydown', this.onKeyDown
.bind( this ) );
8493 .addClass( 'oo-ui-checkboxMultioptionWidget' )
8494 .prepend( this.checkbox
.$element
);
8499 OO
.inheritClass( OO
.ui
.CheckboxMultioptionWidget
, OO
.ui
.MultioptionWidget
);
8501 /* Static Properties */
8507 OO
.ui
.CheckboxMultioptionWidget
.static.tagName
= 'label';
8512 * Handle checkbox selected state change.
8516 OO
.ui
.CheckboxMultioptionWidget
.prototype.onCheckboxChange = function () {
8517 this.setSelected( this.checkbox
.isSelected() );
8523 OO
.ui
.CheckboxMultioptionWidget
.prototype.setSelected = function ( state
) {
8524 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setSelected
.call( this, state
);
8525 this.checkbox
.setSelected( state
);
8532 OO
.ui
.CheckboxMultioptionWidget
.prototype.setDisabled = function ( disabled
) {
8533 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
8534 this.checkbox
.setDisabled( this.isDisabled() );
8541 OO
.ui
.CheckboxMultioptionWidget
.prototype.focus = function () {
8542 this.checkbox
.focus();
8546 * Handle key down events.
8549 * @param {jQuery.Event} e
8551 OO
.ui
.CheckboxMultioptionWidget
.prototype.onKeyDown = function ( e
) {
8553 element
= this.getElementGroup(),
8556 if ( e
.keyCode
=== OO
.ui
.Keys
.LEFT
|| e
.keyCode
=== OO
.ui
.Keys
.UP
) {
8557 nextItem
= element
.getRelativeFocusableItem( this, -1 );
8558 } else if ( e
.keyCode
=== OO
.ui
.Keys
.RIGHT
|| e
.keyCode
=== OO
.ui
.Keys
.DOWN
) {
8559 nextItem
= element
.getRelativeFocusableItem( this, 1 );
8569 * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
8570 * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
8571 * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
8572 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8574 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8575 * OO.ui.CheckboxMultiselectInputWidget instead.
8578 * // A CheckboxMultiselectWidget with CheckboxMultioptions.
8579 * var option1 = new OO.ui.CheckboxMultioptionWidget( {
8582 * label: 'Selected checkbox'
8585 * var option2 = new OO.ui.CheckboxMultioptionWidget( {
8587 * label: 'Unselected checkbox'
8590 * var multiselect=new OO.ui.CheckboxMultiselectWidget( {
8591 * items: [ option1, option2 ]
8594 * $( 'body' ).append( multiselect.$element );
8596 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8599 * @extends OO.ui.MultiselectWidget
8602 * @param {Object} [config] Configuration options
8604 OO
.ui
.CheckboxMultiselectWidget
= function OoUiCheckboxMultiselectWidget( config
) {
8605 // Parent constructor
8606 OO
.ui
.CheckboxMultiselectWidget
.parent
.call( this, config
);
8609 this.$lastClicked
= null;
8612 this.$group
.on( 'click', this.onClick
.bind( this ) );
8616 .addClass( 'oo-ui-checkboxMultiselectWidget' );
8621 OO
.inheritClass( OO
.ui
.CheckboxMultiselectWidget
, OO
.ui
.MultiselectWidget
);
8626 * Get an option by its position relative to the specified item (or to the start of the option array,
8627 * if item is `null`). The direction in which to search through the option array is specified with a
8628 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
8629 * `null` if there are no options in the array.
8631 * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
8632 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
8633 * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items in the select
8635 OO
.ui
.CheckboxMultiselectWidget
.prototype.getRelativeFocusableItem = function ( item
, direction
) {
8636 var currentIndex
, nextIndex
, i
,
8637 increase
= direction
> 0 ? 1 : -1,
8638 len
= this.items
.length
;
8641 currentIndex
= this.items
.indexOf( item
);
8642 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
8644 // If no item is selected and moving forward, start at the beginning.
8645 // If moving backward, start at the end.
8646 nextIndex
= direction
> 0 ? 0 : len
- 1;
8649 for ( i
= 0; i
< len
; i
++ ) {
8650 item
= this.items
[ nextIndex
];
8651 if ( item
&& !item
.isDisabled() ) {
8654 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
8660 * Handle click events on checkboxes.
8662 * @param {jQuery.Event} e
8664 OO
.ui
.CheckboxMultiselectWidget
.prototype.onClick = function ( e
) {
8665 var $options
, lastClickedIndex
, nowClickedIndex
, i
, direction
, wasSelected
, items
,
8666 $lastClicked
= this.$lastClicked
,
8667 $nowClicked
= $( e
.target
).closest( '.oo-ui-checkboxMultioptionWidget' )
8668 .not( '.oo-ui-widget-disabled' );
8670 // Allow selecting multiple options at once by Shift-clicking them
8671 if ( $lastClicked
&& $nowClicked
.length
&& e
.shiftKey
) {
8672 $options
= this.$group
.find( '.oo-ui-checkboxMultioptionWidget' );
8673 lastClickedIndex
= $options
.index( $lastClicked
);
8674 nowClickedIndex
= $options
.index( $nowClicked
);
8675 // If it's the same item, either the user is being silly, or it's a fake event generated by the
8676 // browser. In either case we don't need custom handling.
8677 if ( nowClickedIndex
!== lastClickedIndex
) {
8679 wasSelected
= items
[ nowClickedIndex
].isSelected();
8680 direction
= nowClickedIndex
> lastClickedIndex
? 1 : -1;
8682 // This depends on the DOM order of the items and the order of the .items array being the same.
8683 for ( i
= lastClickedIndex
; i
!== nowClickedIndex
; i
+= direction
) {
8684 if ( !items
[ i
].isDisabled() ) {
8685 items
[ i
].setSelected( !wasSelected
);
8688 // For the now-clicked element, use immediate timeout to allow the browser to do its own
8689 // handling first, then set our value. The order in which events happen is different for
8690 // clicks on the <input> and on the <label> and there are additional fake clicks fired for
8691 // non-click actions that change the checkboxes.
8693 setTimeout( function () {
8694 if ( !items
[ nowClickedIndex
].isDisabled() ) {
8695 items
[ nowClickedIndex
].setSelected( !wasSelected
);
8701 if ( $nowClicked
.length
) {
8702 this.$lastClicked
= $nowClicked
;
8710 * @return {OO.ui.Widget} The widget, for chaining
8712 OO
.ui
.CheckboxMultiselectWidget
.prototype.focus = function () {
8714 if ( !this.isDisabled() ) {
8715 item
= this.getRelativeFocusableItem( null, 1 );
8726 OO
.ui
.CheckboxMultiselectWidget
.prototype.simulateLabelClick = function () {
8731 * Progress bars visually display the status of an operation, such as a download,
8732 * and can be either determinate or indeterminate:
8734 * - **determinate** process bars show the percent of an operation that is complete.
8736 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
8737 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
8738 * not use percentages.
8740 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
8743 * // Examples of determinate and indeterminate progress bars.
8744 * var progressBar1 = new OO.ui.ProgressBarWidget( {
8747 * var progressBar2 = new OO.ui.ProgressBarWidget();
8749 * // Create a FieldsetLayout to layout progress bars
8750 * var fieldset = new OO.ui.FieldsetLayout;
8751 * fieldset.addItems( [
8752 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
8753 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
8755 * $( 'body' ).append( fieldset.$element );
8758 * @extends OO.ui.Widget
8761 * @param {Object} [config] Configuration options
8762 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
8763 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
8764 * By default, the progress bar is indeterminate.
8766 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
8767 // Configuration initialization
8768 config
= config
|| {};
8770 // Parent constructor
8771 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
8774 this.$bar
= $( '<div>' );
8775 this.progress
= null;
8778 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
8779 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
8782 role
: 'progressbar',
8784 'aria-valuemax': 100
8786 .addClass( 'oo-ui-progressBarWidget' )
8787 .append( this.$bar
);
8792 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
8794 /* Static Properties */
8800 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
8805 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
8807 * @return {number|boolean} Progress percent
8809 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
8810 return this.progress
;
8814 * Set the percent of the process completed or `false` for an indeterminate process.
8816 * @param {number|boolean} progress Progress percent or `false` for indeterminate
8818 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
8819 this.progress
= progress
;
8821 if ( progress
!== false ) {
8822 this.$bar
.css( 'width', this.progress
+ '%' );
8823 this.$element
.attr( 'aria-valuenow', this.progress
);
8825 this.$bar
.css( 'width', '' );
8826 this.$element
.removeAttr( 'aria-valuenow' );
8828 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress
=== false );
8832 * InputWidget is the base class for all input widgets, which
8833 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
8834 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
8835 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
8837 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
8841 * @extends OO.ui.Widget
8842 * @mixins OO.ui.mixin.FlaggedElement
8843 * @mixins OO.ui.mixin.TabIndexedElement
8844 * @mixins OO.ui.mixin.TitledElement
8845 * @mixins OO.ui.mixin.AccessKeyedElement
8848 * @param {Object} [config] Configuration options
8849 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
8850 * @cfg {string} [value=''] The value of the input.
8851 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
8852 * @cfg {string} [inputId] The value of the input’s HTML `id` attribute.
8853 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
8854 * before it is accepted.
8856 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
8857 // Configuration initialization
8858 config
= config
|| {};
8860 // Parent constructor
8861 OO
.ui
.InputWidget
.parent
.call( this, config
);
8864 // See #reusePreInfuseDOM about config.$input
8865 this.$input
= config
.$input
|| this.getInputElement( config
);
8867 this.inputFilter
= config
.inputFilter
;
8869 // Mixin constructors
8870 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
8871 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
8872 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
8873 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$input
} ) );
8876 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
8880 .addClass( 'oo-ui-inputWidget-input' )
8881 .attr( 'name', config
.name
)
8882 .prop( 'disabled', this.isDisabled() );
8884 .addClass( 'oo-ui-inputWidget' )
8885 .append( this.$input
);
8886 this.setValue( config
.value
);
8888 this.setDir( config
.dir
);
8890 if ( config
.inputId
!== undefined ) {
8891 this.setInputId( config
.inputId
);
8897 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
8898 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
8899 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
8900 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
8901 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
8903 /* Static Methods */
8908 OO
.ui
.InputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
8909 config
= OO
.ui
.InputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
8910 // Reusing `$input` lets browsers preserve inputted values across page reloads, see T114134.
8911 config
.$input
= $( node
).find( '.oo-ui-inputWidget-input' );
8918 OO
.ui
.InputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8919 var state
= OO
.ui
.InputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8920 if ( config
.$input
&& config
.$input
.length
) {
8921 state
.value
= config
.$input
.val();
8922 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
8923 state
.focus
= config
.$input
.is( ':focus' );
8933 * A change event is emitted when the value of the input changes.
8935 * @param {string} value
8941 * Get input element.
8943 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
8944 * different circumstances. The element must have a `value` property (like form elements).
8947 * @param {Object} config Configuration options
8948 * @return {jQuery} Input element
8950 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
8951 return $( '<input>' );
8955 * Handle potentially value-changing events.
8958 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
8960 OO
.ui
.InputWidget
.prototype.onEdit = function () {
8962 if ( !this.isDisabled() ) {
8963 // Allow the stack to clear so the value will be updated
8964 setTimeout( function () {
8965 widget
.setValue( widget
.$input
.val() );
8971 * Get the value of the input.
8973 * @return {string} Input value
8975 OO
.ui
.InputWidget
.prototype.getValue = function () {
8976 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
8977 // it, and we won't know unless they're kind enough to trigger a 'change' event.
8978 var value
= this.$input
.val();
8979 if ( this.value
!== value
) {
8980 this.setValue( value
);
8986 * Set the directionality of the input.
8988 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
8990 * @return {OO.ui.Widget} The widget, for chaining
8992 OO
.ui
.InputWidget
.prototype.setDir = function ( dir
) {
8993 this.$input
.prop( 'dir', dir
);
8998 * Set the value of the input.
9000 * @param {string} value New value
9003 * @return {OO.ui.Widget} The widget, for chaining
9005 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
9006 value
= this.cleanUpValue( value
);
9007 // Update the DOM if it has changed. Note that with cleanUpValue, it
9008 // is possible for the DOM value to change without this.value changing.
9009 if ( this.$input
.val() !== value
) {
9010 this.$input
.val( value
);
9012 if ( this.value
!== value
) {
9014 this.emit( 'change', this.value
);
9016 // The first time that the value is set (probably while constructing the widget),
9017 // remember it in defaultValue. This property can be later used to check whether
9018 // the value of the input has been changed since it was created.
9019 if ( this.defaultValue
=== undefined ) {
9020 this.defaultValue
= this.value
;
9021 this.$input
[ 0 ].defaultValue
= this.defaultValue
;
9027 * Clean up incoming value.
9029 * Ensures value is a string, and converts undefined and null to empty string.
9032 * @param {string} value Original value
9033 * @return {string} Cleaned up value
9035 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
9036 if ( value
=== undefined || value
=== null ) {
9038 } else if ( this.inputFilter
) {
9039 return this.inputFilter( String( value
) );
9041 return String( value
);
9048 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
9049 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9050 if ( this.$input
) {
9051 this.$input
.prop( 'disabled', this.isDisabled() );
9057 * Set the 'id' attribute of the `<input>` element.
9059 * @param {string} id
9061 * @return {OO.ui.Widget} The widget, for chaining
9063 OO
.ui
.InputWidget
.prototype.setInputId = function ( id
) {
9064 this.$input
.attr( 'id', id
);
9071 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
9072 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
9073 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
9074 this.setValue( state
.value
);
9076 if ( state
.focus
) {
9082 * Data widget intended for creating 'hidden'-type inputs.
9085 * @extends OO.ui.Widget
9088 * @param {Object} [config] Configuration options
9089 * @cfg {string} [value=''] The value of the input.
9090 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
9092 OO
.ui
.HiddenInputWidget
= function OoUiHiddenInputWidget( config
) {
9093 // Configuration initialization
9094 config
= $.extend( { value
: '', name
: '' }, config
);
9096 // Parent constructor
9097 OO
.ui
.HiddenInputWidget
.parent
.call( this, config
);
9100 this.$element
.attr( {
9102 value
: config
.value
,
9105 this.$element
.removeAttr( 'aria-disabled' );
9110 OO
.inheritClass( OO
.ui
.HiddenInputWidget
, OO
.ui
.Widget
);
9112 /* Static Properties */
9118 OO
.ui
.HiddenInputWidget
.static.tagName
= 'input';
9121 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
9122 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
9123 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
9124 * HTML `<button>` (the default) or an HTML `<input>` tags. See the
9125 * [OOUI documentation on MediaWiki] [1] for more information.
9128 * // A ButtonInputWidget rendered as an HTML button, the default.
9129 * var button = new OO.ui.ButtonInputWidget( {
9130 * label: 'Input button',
9134 * $( 'body' ).append( button.$element );
9136 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#Button_inputs
9139 * @extends OO.ui.InputWidget
9140 * @mixins OO.ui.mixin.ButtonElement
9141 * @mixins OO.ui.mixin.IconElement
9142 * @mixins OO.ui.mixin.IndicatorElement
9143 * @mixins OO.ui.mixin.LabelElement
9144 * @mixins OO.ui.mixin.TitledElement
9147 * @param {Object} [config] Configuration options
9148 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
9149 * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
9150 * Widgets configured to be an `<input>` do not support {@link #icon icons} and {@link #indicator indicators},
9151 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
9152 * be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
9154 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
9155 // Configuration initialization
9156 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
9158 // See InputWidget#reusePreInfuseDOM about config.$input
9159 if ( config
.$input
) {
9160 config
.$input
.empty();
9163 // Properties (must be set before parent constructor, which calls #setValue)
9164 this.useInputTag
= config
.useInputTag
;
9166 // Parent constructor
9167 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
9169 // Mixin constructors
9170 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
9171 OO
.ui
.mixin
.IconElement
.call( this, config
);
9172 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
9173 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9174 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
9177 if ( !config
.useInputTag
) {
9178 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
9180 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
9185 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
9186 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
9187 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
9188 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
9189 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
9190 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
9192 /* Static Properties */
9198 OO
.ui
.ButtonInputWidget
.static.tagName
= 'span';
9206 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
9208 type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ? config
.type
: 'button';
9209 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
9215 * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
9217 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
9218 * text, or `null` for no label
9220 * @return {OO.ui.Widget} The widget, for chaining
9222 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
9223 if ( typeof label
=== 'function' ) {
9224 label
= OO
.ui
.resolveMsg( label
);
9227 if ( this.useInputTag
) {
9228 // Discard non-plaintext labels
9229 if ( typeof label
!== 'string' ) {
9233 this.$input
.val( label
);
9236 return OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
9240 * Set the value of the input.
9242 * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
9243 * they do not support {@link #value values}.
9245 * @param {string} value New value
9247 * @return {OO.ui.Widget} The widget, for chaining
9249 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
9250 if ( !this.useInputTag
) {
9251 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
9259 OO
.ui
.ButtonInputWidget
.prototype.getInputId = function () {
9260 // Disable generating `<label>` elements for buttons. One would very rarely need additional label
9261 // for a button, and it's already a big clickable target, and it causes unexpected rendering.
9266 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
9267 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
9268 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
9269 * alignment. For more information, please see the [OOUI documentation on MediaWiki][1].
9271 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9274 * // An example of selected, unselected, and disabled checkbox inputs
9275 * var checkbox1=new OO.ui.CheckboxInputWidget( {
9279 * var checkbox2=new OO.ui.CheckboxInputWidget( {
9282 * var checkbox3=new OO.ui.CheckboxInputWidget( {
9286 * // Create a fieldset layout with fields for each checkbox.
9287 * var fieldset = new OO.ui.FieldsetLayout( {
9288 * label: 'Checkboxes'
9290 * fieldset.addItems( [
9291 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
9292 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
9293 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
9295 * $( 'body' ).append( fieldset.$element );
9297 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9300 * @extends OO.ui.InputWidget
9303 * @param {Object} [config] Configuration options
9304 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
9306 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
9307 // Configuration initialization
9308 config
= config
|| {};
9310 // Parent constructor
9311 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
9314 this.checkIcon
= new OO
.ui
.IconWidget( {
9316 classes
: [ 'oo-ui-checkboxInputWidget-checkIcon' ]
9321 .addClass( 'oo-ui-checkboxInputWidget' )
9322 // Required for pretty styling in WikimediaUI theme
9323 .append( this.checkIcon
.$element
);
9324 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
9329 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
9331 /* Static Properties */
9337 OO
.ui
.CheckboxInputWidget
.static.tagName
= 'span';
9339 /* Static Methods */
9344 OO
.ui
.CheckboxInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9345 var state
= OO
.ui
.CheckboxInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9346 state
.checked
= config
.$input
.prop( 'checked' );
9356 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
9357 return $( '<input>' ).attr( 'type', 'checkbox' );
9363 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
9365 if ( !this.isDisabled() ) {
9366 // Allow the stack to clear so the value will be updated
9367 setTimeout( function () {
9368 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
9374 * Set selection state of this checkbox.
9376 * @param {boolean} state `true` for selected
9378 * @return {OO.ui.Widget} The widget, for chaining
9380 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
9382 if ( this.selected
!== state
) {
9383 this.selected
= state
;
9384 this.$input
.prop( 'checked', this.selected
);
9385 this.emit( 'change', this.selected
);
9387 // The first time that the selection state is set (probably while constructing the widget),
9388 // remember it in defaultSelected. This property can be later used to check whether
9389 // the selection state of the input has been changed since it was created.
9390 if ( this.defaultSelected
=== undefined ) {
9391 this.defaultSelected
= this.selected
;
9392 this.$input
[ 0 ].defaultChecked
= this.defaultSelected
;
9398 * Check if this checkbox is selected.
9400 * @return {boolean} Checkbox is selected
9402 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
9403 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
9404 // it, and we won't know unless they're kind enough to trigger a 'change' event.
9405 var selected
= this.$input
.prop( 'checked' );
9406 if ( this.selected
!== selected
) {
9407 this.setSelected( selected
);
9409 return this.selected
;
9415 OO
.ui
.CheckboxInputWidget
.prototype.simulateLabelClick = function () {
9416 if ( !this.isDisabled() ) {
9417 this.$input
.click();
9425 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
9426 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
9427 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
9428 this.setSelected( state
.checked
);
9433 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
9434 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
9435 * of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9436 * more information about input widgets.
9438 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
9439 * are no options. If no `value` configuration option is provided, the first option is selected.
9440 * If you need a state representing no value (no option being selected), use a DropdownWidget.
9442 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
9445 * // Example: A DropdownInputWidget with three options
9446 * var dropdownInput = new OO.ui.DropdownInputWidget( {
9448 * { data: 'a', label: 'First' },
9449 * { data: 'b', label: 'Second'},
9450 * { data: 'c', label: 'Third' }
9453 * $( 'body' ).append( dropdownInput.$element );
9455 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9458 * @extends OO.ui.InputWidget
9461 * @param {Object} [config] Configuration options
9462 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9463 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
9464 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
9465 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
9466 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
9467 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
9469 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
9470 // Configuration initialization
9471 config
= config
|| {};
9473 // Properties (must be done before parent constructor which calls #setDisabled)
9474 this.dropdownWidget
= new OO
.ui
.DropdownWidget( $.extend(
9476 $overlay
: config
.$overlay
9480 // Set up the options before parent constructor, which uses them to validate config.value.
9481 // Use this instead of setOptions() because this.$input is not set up yet.
9482 this.setOptionsData( config
.options
|| [] );
9484 // Parent constructor
9485 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
9488 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
9492 .addClass( 'oo-ui-dropdownInputWidget' )
9493 .append( this.dropdownWidget
.$element
);
9494 this.setTabIndexedElement( this.dropdownWidget
.$tabIndexed
);
9499 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
9507 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
9508 return $( '<select>' );
9512 * Handles menu select events.
9515 * @param {OO.ui.MenuOptionWidget|null} item Selected menu item
9517 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
9518 this.setValue( item
? item
.getData() : '' );
9524 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
9526 value
= this.cleanUpValue( value
);
9527 // Only allow setting values that are actually present in the dropdown
9528 selected
= this.dropdownWidget
.getMenu().findItemFromData( value
) ||
9529 this.dropdownWidget
.getMenu().findFirstSelectableItem();
9530 this.dropdownWidget
.getMenu().selectItem( selected
);
9531 value
= selected
? selected
.getData() : '';
9532 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
9533 if ( this.optionsDirty
) {
9534 // We reached this from the constructor or from #setOptions.
9535 // We have to update the <select> element.
9536 this.updateOptionsInterface();
9544 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
9545 this.dropdownWidget
.setDisabled( state
);
9546 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9551 * Set the options available for this input.
9553 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9555 * @return {OO.ui.Widget} The widget, for chaining
9557 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
9558 var value
= this.getValue();
9560 this.setOptionsData( options
);
9562 // Re-set the value to update the visible interface (DropdownWidget and <select>).
9563 // In case the previous value is no longer an available option, select the first valid one.
9564 this.setValue( value
);
9570 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
9572 * This method may be called before the parent constructor, so various properties may not be
9575 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9578 OO
.ui
.DropdownInputWidget
.prototype.setOptionsData = function ( options
) {
9583 this.optionsDirty
= true;
9585 optionWidgets
= options
.map( function ( opt
) {
9588 if ( opt
.optgroup
!== undefined ) {
9589 return widget
.createMenuSectionOptionWidget( opt
.optgroup
);
9592 optValue
= widget
.cleanUpValue( opt
.data
);
9593 return widget
.createMenuOptionWidget(
9595 opt
.label
!== undefined ? opt
.label
: optValue
9600 this.dropdownWidget
.getMenu().clearItems().addItems( optionWidgets
);
9604 * Create a menu option widget.
9607 * @param {string} data Item data
9608 * @param {string} label Item label
9609 * @return {OO.ui.MenuOptionWidget} Option widget
9611 OO
.ui
.DropdownInputWidget
.prototype.createMenuOptionWidget = function ( data
, label
) {
9612 return new OO
.ui
.MenuOptionWidget( {
9619 * Create a menu section option widget.
9622 * @param {string} label Section item label
9623 * @return {OO.ui.MenuSectionOptionWidget} Menu section option widget
9625 OO
.ui
.DropdownInputWidget
.prototype.createMenuSectionOptionWidget = function ( label
) {
9626 return new OO
.ui
.MenuSectionOptionWidget( {
9632 * Update the user-visible interface to match the internal list of options and value.
9634 * This method must only be called after the parent constructor.
9638 OO
.ui
.DropdownInputWidget
.prototype.updateOptionsInterface = function () {
9640 $optionsContainer
= this.$input
,
9641 defaultValue
= this.defaultValue
,
9644 this.$input
.empty();
9646 this.dropdownWidget
.getMenu().getItems().forEach( function ( optionWidget
) {
9649 if ( !( optionWidget
instanceof OO
.ui
.MenuSectionOptionWidget
) ) {
9650 $optionNode
= $( '<option>' )
9651 .attr( 'value', optionWidget
.getData() )
9652 .text( optionWidget
.getLabel() );
9654 // Remember original selection state. This property can be later used to check whether
9655 // the selection state of the input has been changed since it was created.
9656 $optionNode
[ 0 ].defaultSelected
= ( optionWidget
.getData() === defaultValue
);
9658 $optionsContainer
.append( $optionNode
);
9660 $optionNode
= $( '<optgroup>' )
9661 .attr( 'label', optionWidget
.getLabel() );
9662 widget
.$input
.append( $optionNode
);
9663 $optionsContainer
= $optionNode
;
9667 this.optionsDirty
= false;
9673 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
9674 this.dropdownWidget
.focus();
9681 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
9682 this.dropdownWidget
.blur();
9687 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
9688 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
9689 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
9690 * please see the [OOUI documentation on MediaWiki][1].
9692 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9695 * // An example of selected, unselected, and disabled radio inputs
9696 * var radio1 = new OO.ui.RadioInputWidget( {
9700 * var radio2 = new OO.ui.RadioInputWidget( {
9703 * var radio3 = new OO.ui.RadioInputWidget( {
9707 * // Create a fieldset layout with fields for each radio button.
9708 * var fieldset = new OO.ui.FieldsetLayout( {
9709 * label: 'Radio inputs'
9711 * fieldset.addItems( [
9712 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
9713 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
9714 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
9716 * $( 'body' ).append( fieldset.$element );
9718 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9721 * @extends OO.ui.InputWidget
9724 * @param {Object} [config] Configuration options
9725 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
9727 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
9728 // Configuration initialization
9729 config
= config
|| {};
9731 // Parent constructor
9732 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
9736 .addClass( 'oo-ui-radioInputWidget' )
9737 // Required for pretty styling in WikimediaUI theme
9738 .append( $( '<span>' ) );
9739 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
9744 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
9746 /* Static Properties */
9752 OO
.ui
.RadioInputWidget
.static.tagName
= 'span';
9754 /* Static Methods */
9759 OO
.ui
.RadioInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9760 var state
= OO
.ui
.RadioInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9761 state
.checked
= config
.$input
.prop( 'checked' );
9771 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
9772 return $( '<input>' ).attr( 'type', 'radio' );
9778 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
9779 // RadioInputWidget doesn't track its state.
9783 * Set selection state of this radio button.
9785 * @param {boolean} state `true` for selected
9787 * @return {OO.ui.Widget} The widget, for chaining
9789 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
9790 // RadioInputWidget doesn't track its state.
9791 this.$input
.prop( 'checked', state
);
9792 // The first time that the selection state is set (probably while constructing the widget),
9793 // remember it in defaultSelected. This property can be later used to check whether
9794 // the selection state of the input has been changed since it was created.
9795 if ( this.defaultSelected
=== undefined ) {
9796 this.defaultSelected
= state
;
9797 this.$input
[ 0 ].defaultChecked
= this.defaultSelected
;
9803 * Check if this radio button is selected.
9805 * @return {boolean} Radio is selected
9807 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
9808 return this.$input
.prop( 'checked' );
9814 OO
.ui
.RadioInputWidget
.prototype.simulateLabelClick = function () {
9815 if ( !this.isDisabled() ) {
9816 this.$input
.click();
9824 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
9825 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
9826 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
9827 this.setSelected( state
.checked
);
9832 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
9833 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
9834 * of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9835 * more information about input widgets.
9837 * This and OO.ui.DropdownInputWidget support the same configuration options.
9840 * // Example: A RadioSelectInputWidget with three options
9841 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
9843 * { data: 'a', label: 'First' },
9844 * { data: 'b', label: 'Second'},
9845 * { data: 'c', label: 'Third' }
9848 * $( 'body' ).append( radioSelectInput.$element );
9850 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9853 * @extends OO.ui.InputWidget
9856 * @param {Object} [config] Configuration options
9857 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9859 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
9860 // Configuration initialization
9861 config
= config
|| {};
9863 // Properties (must be done before parent constructor which calls #setDisabled)
9864 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
9865 // Set up the options before parent constructor, which uses them to validate config.value.
9866 // Use this instead of setOptions() because this.$input is not set up yet
9867 this.setOptionsData( config
.options
|| [] );
9869 // Parent constructor
9870 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
9873 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
9877 .addClass( 'oo-ui-radioSelectInputWidget' )
9878 .append( this.radioSelectWidget
.$element
);
9879 this.setTabIndexedElement( this.radioSelectWidget
.$tabIndexed
);
9884 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
9886 /* Static Methods */
9891 OO
.ui
.RadioSelectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9892 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9893 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
9900 OO
.ui
.RadioSelectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
9901 config
= OO
.ui
.RadioSelectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
9902 // Cannot reuse the `<input type=radio>` set
9903 delete config
.$input
;
9913 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
9914 // Use this instead of <input type="hidden">, because hidden inputs do not have separate
9915 // 'value' and 'defaultValue' properties, and InputWidget wants to handle 'defaultValue'.
9916 return $( '<input>' ).addClass( 'oo-ui-element-hidden' );
9920 * Handles menu select events.
9923 * @param {OO.ui.RadioOptionWidget} item Selected menu item
9925 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
9926 this.setValue( item
.getData() );
9932 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
9934 value
= this.cleanUpValue( value
);
9935 // Only allow setting values that are actually present in the dropdown
9936 selected
= this.radioSelectWidget
.findItemFromData( value
) ||
9937 this.radioSelectWidget
.findFirstSelectableItem();
9938 this.radioSelectWidget
.selectItem( selected
);
9939 value
= selected
? selected
.getData() : '';
9940 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
9947 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
9948 this.radioSelectWidget
.setDisabled( state
);
9949 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9954 * Set the options available for this input.
9956 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9958 * @return {OO.ui.Widget} The widget, for chaining
9960 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
9961 var value
= this.getValue();
9963 this.setOptionsData( options
);
9965 // Re-set the value to update the visible interface (RadioSelectWidget).
9966 // In case the previous value is no longer an available option, select the first valid one.
9967 this.setValue( value
);
9973 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
9975 * This method may be called before the parent constructor, so various properties may not be
9978 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9981 OO
.ui
.RadioSelectInputWidget
.prototype.setOptionsData = function ( options
) {
9984 this.radioSelectWidget
9986 .addItems( options
.map( function ( opt
) {
9987 var optValue
= widget
.cleanUpValue( opt
.data
);
9988 return new OO
.ui
.RadioOptionWidget( {
9990 label
: opt
.label
!== undefined ? opt
.label
: optValue
9998 OO
.ui
.RadioSelectInputWidget
.prototype.focus = function () {
9999 this.radioSelectWidget
.focus();
10006 OO
.ui
.RadioSelectInputWidget
.prototype.blur = function () {
10007 this.radioSelectWidget
.blur();
10012 * CheckboxMultiselectInputWidget is a
10013 * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
10014 * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
10015 * HTML `<input type=checkbox>` tags. Please see the [OOUI documentation on MediaWiki][1] for
10016 * more information about input widgets.
10019 * // Example: A CheckboxMultiselectInputWidget with three options
10020 * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
10022 * { data: 'a', label: 'First' },
10023 * { data: 'b', label: 'Second'},
10024 * { data: 'c', label: 'Third' }
10027 * $( 'body' ).append( multiselectInput.$element );
10029 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
10032 * @extends OO.ui.InputWidget
10035 * @param {Object} [config] Configuration options
10036 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: …, disabled: … }`
10038 OO
.ui
.CheckboxMultiselectInputWidget
= function OoUiCheckboxMultiselectInputWidget( config
) {
10039 // Configuration initialization
10040 config
= config
|| {};
10042 // Properties (must be done before parent constructor which calls #setDisabled)
10043 this.checkboxMultiselectWidget
= new OO
.ui
.CheckboxMultiselectWidget();
10044 // Must be set before the #setOptionsData call below
10045 this.inputName
= config
.name
;
10046 // Set up the options before parent constructor, which uses them to validate config.value.
10047 // Use this instead of setOptions() because this.$input is not set up yet
10048 this.setOptionsData( config
.options
|| [] );
10050 // Parent constructor
10051 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.call( this, config
);
10054 this.checkboxMultiselectWidget
.connect( this, { select
: 'onCheckboxesSelect' } );
10058 .addClass( 'oo-ui-checkboxMultiselectInputWidget' )
10059 .append( this.checkboxMultiselectWidget
.$element
);
10060 // We don't use this.$input, but rather the CheckboxInputWidgets inside each option
10061 this.$input
.detach();
10066 OO
.inheritClass( OO
.ui
.CheckboxMultiselectInputWidget
, OO
.ui
.InputWidget
);
10068 /* Static Methods */
10073 OO
.ui
.CheckboxMultiselectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
10074 var state
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
10075 state
.value
= $( node
).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
10076 .toArray().map( function ( el
) { return el
.value
; } );
10083 OO
.ui
.CheckboxMultiselectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
10084 config
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
10085 // Cannot reuse the `<input type=checkbox>` set
10086 delete config
.$input
;
10096 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getInputElement = function () {
10098 return $( '<unused>' );
10102 * Handles CheckboxMultiselectWidget select events.
10106 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.onCheckboxesSelect = function () {
10107 this.setValue( this.checkboxMultiselectWidget
.findSelectedItemsData() );
10113 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getValue = function () {
10114 var value
= this.$element
.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
10115 .toArray().map( function ( el
) { return el
.value
; } );
10116 if ( this.value
!== value
) {
10117 this.setValue( value
);
10125 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setValue = function ( value
) {
10126 value
= this.cleanUpValue( value
);
10127 this.checkboxMultiselectWidget
.selectItemsByData( value
);
10128 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setValue
.call( this, value
);
10129 if ( this.optionsDirty
) {
10130 // We reached this from the constructor or from #setOptions.
10131 // We have to update the <select> element.
10132 this.updateOptionsInterface();
10138 * Clean up incoming value.
10140 * @param {string[]} value Original value
10141 * @return {string[]} Cleaned up value
10143 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.cleanUpValue = function ( value
) {
10144 var i
, singleValue
,
10146 if ( !Array
.isArray( value
) ) {
10149 for ( i
= 0; i
< value
.length
; i
++ ) {
10151 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( this, value
[ i
] );
10152 // Remove options that we don't have here
10153 if ( !this.checkboxMultiselectWidget
.findItemFromData( singleValue
) ) {
10156 cleanValue
.push( singleValue
);
10164 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setDisabled = function ( state
) {
10165 this.checkboxMultiselectWidget
.setDisabled( state
);
10166 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
10171 * Set the options available for this input.
10173 * @param {Object[]} options Array of menu options in the format `{ data: …, label: …, disabled: … }`
10175 * @return {OO.ui.Widget} The widget, for chaining
10177 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setOptions = function ( options
) {
10178 var value
= this.getValue();
10180 this.setOptionsData( options
);
10182 // Re-set the value to update the visible interface (CheckboxMultiselectWidget).
10183 // This will also get rid of any stale options that we just removed.
10184 this.setValue( value
);
10190 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
10192 * This method may be called before the parent constructor, so various properties may not be
10195 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10198 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setOptionsData = function ( options
) {
10201 this.optionsDirty
= true;
10203 this.checkboxMultiselectWidget
10205 .addItems( options
.map( function ( opt
) {
10206 var optValue
, item
, optDisabled
;
10208 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( widget
, opt
.data
);
10209 optDisabled
= opt
.disabled
!== undefined ? opt
.disabled
: false;
10210 item
= new OO
.ui
.CheckboxMultioptionWidget( {
10212 label
: opt
.label
!== undefined ? opt
.label
: optValue
,
10213 disabled
: optDisabled
10215 // Set the 'name' and 'value' for form submission
10216 item
.checkbox
.$input
.attr( 'name', widget
.inputName
);
10217 item
.checkbox
.setValue( optValue
);
10223 * Update the user-visible interface to match the internal list of options and value.
10225 * This method must only be called after the parent constructor.
10229 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.updateOptionsInterface = function () {
10230 var defaultValue
= this.defaultValue
;
10232 this.checkboxMultiselectWidget
.getItems().forEach( function ( item
) {
10233 // Remember original selection state. This property can be later used to check whether
10234 // the selection state of the input has been changed since it was created.
10235 var isDefault
= defaultValue
.indexOf( item
.getData() ) !== -1;
10236 item
.checkbox
.defaultSelected
= isDefault
;
10237 item
.checkbox
.$input
[ 0 ].defaultChecked
= isDefault
;
10240 this.optionsDirty
= false;
10246 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.focus = function () {
10247 this.checkboxMultiselectWidget
.focus();
10252 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
10253 * size of the field as well as its presentation. In addition, these widgets can be configured
10254 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
10255 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
10256 * which modifies incoming values rather than validating them.
10257 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
10259 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
10262 * // Example of a text input widget
10263 * var textInput = new OO.ui.TextInputWidget( {
10264 * value: 'Text input'
10266 * $( 'body' ).append( textInput.$element );
10268 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
10271 * @extends OO.ui.InputWidget
10272 * @mixins OO.ui.mixin.IconElement
10273 * @mixins OO.ui.mixin.IndicatorElement
10274 * @mixins OO.ui.mixin.PendingElement
10275 * @mixins OO.ui.mixin.LabelElement
10278 * @param {Object} [config] Configuration options
10279 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password'
10280 * 'email', 'url' or 'number'.
10281 * @cfg {string} [placeholder] Placeholder text
10282 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
10283 * instruct the browser to focus this widget.
10284 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
10285 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
10287 * For unfortunate historical reasons, this counts the number of UTF-16 code units rather than
10288 * Unicode codepoints, which means that codepoints outside the Basic Multilingual Plane (e.g.
10289 * many emojis) count as 2 characters each.
10290 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
10291 * the value or placeholder text: `'before'` or `'after'`
10292 * @cfg {boolean} [required=false] Mark the field as required with `true`. Implies `indicator: 'required'`.
10293 * Note that `false` & setting `indicator: 'required' will result in no indicator shown.
10294 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
10295 * @cfg {boolean} [spellcheck] Should the browser support spellcheck for this field (`undefined` means
10296 * leaving it up to the browser).
10297 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
10298 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
10299 * (the value must contain only numbers); when RegExp, a regular expression that must match the
10300 * value for it to be considered valid; when Function, a function receiving the value as parameter
10301 * that must return true, or promise resolving to true, for it to be considered valid.
10303 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
10304 // Configuration initialization
10305 config
= $.extend( {
10307 labelPosition
: 'after'
10310 // Parent constructor
10311 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
10313 // Mixin constructors
10314 OO
.ui
.mixin
.IconElement
.call( this, config
);
10315 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
10316 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
10317 OO
.ui
.mixin
.LabelElement
.call( this, config
);
10320 this.type
= this.getSaneType( config
);
10321 this.readOnly
= false;
10322 this.required
= false;
10323 this.validate
= null;
10324 this.styleHeight
= null;
10325 this.scrollWidth
= null;
10327 this.setValidation( config
.validate
);
10328 this.setLabelPosition( config
.labelPosition
);
10332 keypress
: this.onKeyPress
.bind( this ),
10333 blur
: this.onBlur
.bind( this ),
10334 focus
: this.onFocus
.bind( this )
10336 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
10337 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
10338 this.on( 'labelChange', this.updatePosition
.bind( this ) );
10339 this.on( 'change', OO
.ui
.debounce( this.onDebouncedChange
.bind( this ), 250 ) );
10343 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
10344 .append( this.$icon
, this.$indicator
);
10345 this.setReadOnly( !!config
.readOnly
);
10346 this.setRequired( !!config
.required
);
10347 if ( config
.placeholder
!== undefined ) {
10348 this.$input
.attr( 'placeholder', config
.placeholder
);
10350 if ( config
.maxLength
!== undefined ) {
10351 this.$input
.attr( 'maxlength', config
.maxLength
);
10353 if ( config
.autofocus
) {
10354 this.$input
.attr( 'autofocus', 'autofocus' );
10356 if ( config
.autocomplete
=== false ) {
10357 this.$input
.attr( 'autocomplete', 'off' );
10358 // Turning off autocompletion also disables "form caching" when the user navigates to a
10359 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
10361 beforeunload: function () {
10362 this.$input
.removeAttr( 'autocomplete' );
10364 pageshow: function () {
10365 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
10366 // whole page... it shouldn't hurt, though.
10367 this.$input
.attr( 'autocomplete', 'off' );
10371 if ( config
.spellcheck
!== undefined ) {
10372 this.$input
.attr( 'spellcheck', config
.spellcheck
? 'true' : 'false' );
10374 if ( this.label
) {
10375 this.isWaitingToBeAttached
= true;
10376 this.installParentChangeDetector();
10382 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
10383 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
10384 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
10385 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
10386 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
10388 /* Static Properties */
10390 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
10398 * An `enter` event is emitted when the user presses 'enter' inside the text box.
10406 * Handle icon mouse down events.
10409 * @param {jQuery.Event} e Mouse down event
10410 * @return {undefined/boolean} False to prevent default if event is handled
10412 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
10413 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
10420 * Handle indicator mouse down events.
10423 * @param {jQuery.Event} e Mouse down event
10424 * @return {undefined/boolean} False to prevent default if event is handled
10426 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
10427 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
10434 * Handle key press events.
10437 * @param {jQuery.Event} e Key press event
10438 * @fires enter If enter key is pressed
10440 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
10441 if ( e
.which
=== OO
.ui
.Keys
.ENTER
) {
10442 this.emit( 'enter', e
);
10447 * Handle blur events.
10450 * @param {jQuery.Event} e Blur event
10452 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
10453 this.setValidityFlag();
10457 * Handle focus events.
10460 * @param {jQuery.Event} e Focus event
10462 OO
.ui
.TextInputWidget
.prototype.onFocus = function () {
10463 if ( this.isWaitingToBeAttached
) {
10464 // If we've received focus, then we must be attached to the document, and if
10465 // isWaitingToBeAttached is still true, that means the handler never fired. Fire it now.
10466 this.onElementAttach();
10468 this.setValidityFlag( true );
10472 * Handle element attach events.
10475 * @param {jQuery.Event} e Element attach event
10477 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
10478 this.isWaitingToBeAttached
= false;
10479 // Any previously calculated size is now probably invalid if we reattached elsewhere
10480 this.valCache
= null;
10481 this.positionLabel();
10485 * Handle debounced change events.
10487 * @param {string} value
10490 OO
.ui
.TextInputWidget
.prototype.onDebouncedChange = function () {
10491 this.setValidityFlag();
10495 * Check if the input is {@link #readOnly read-only}.
10497 * @return {boolean}
10499 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
10500 return this.readOnly
;
10504 * Set the {@link #readOnly read-only} state of the input.
10506 * @param {boolean} state Make input read-only
10508 * @return {OO.ui.Widget} The widget, for chaining
10510 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
10511 this.readOnly
= !!state
;
10512 this.$input
.prop( 'readOnly', this.readOnly
);
10517 * Check if the input is {@link #required required}.
10519 * @return {boolean}
10521 OO
.ui
.TextInputWidget
.prototype.isRequired = function () {
10522 return this.required
;
10526 * Set the {@link #required required} state of the input.
10528 * @param {boolean} state Make input required
10530 * @return {OO.ui.Widget} The widget, for chaining
10532 OO
.ui
.TextInputWidget
.prototype.setRequired = function ( state
) {
10533 this.required
= !!state
;
10534 if ( this.required
) {
10536 .prop( 'required', true )
10537 .attr( 'aria-required', 'true' );
10538 if ( this.getIndicator() === null ) {
10539 this.setIndicator( 'required' );
10543 .prop( 'required', false )
10544 .removeAttr( 'aria-required' );
10545 if ( this.getIndicator() === 'required' ) {
10546 this.setIndicator( null );
10553 * Support function for making #onElementAttach work across browsers.
10555 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
10556 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
10558 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
10559 * first time that the element gets attached to the documented.
10561 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
10562 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
10563 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
10566 if ( MutationObserver
) {
10567 // The new way. If only it wasn't so ugly.
10569 if ( this.isElementAttached() ) {
10570 // Widget is attached already, do nothing. This breaks the functionality of this function when
10571 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
10572 // would require observation of the whole document, which would hurt performance of other,
10573 // more important code.
10577 // Find topmost node in the tree
10578 topmostNode
= this.$element
[ 0 ];
10579 while ( topmostNode
.parentNode
) {
10580 topmostNode
= topmostNode
.parentNode
;
10583 // We have no way to detect the $element being attached somewhere without observing the entire
10584 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
10585 // parent node of $element, and instead detect when $element is removed from it (and thus
10586 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
10587 // doesn't get attached, we end up back here and create the parent.
10589 mutationObserver
= new MutationObserver( function ( mutations
) {
10590 var i
, j
, removedNodes
;
10591 for ( i
= 0; i
< mutations
.length
; i
++ ) {
10592 removedNodes
= mutations
[ i
].removedNodes
;
10593 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
10594 if ( removedNodes
[ j
] === topmostNode
) {
10595 setTimeout( onRemove
, 0 );
10602 onRemove = function () {
10603 // If the node was attached somewhere else, report it
10604 if ( widget
.isElementAttached() ) {
10605 widget
.onElementAttach();
10607 mutationObserver
.disconnect();
10608 widget
.installParentChangeDetector();
10611 // Create a fake parent and observe it
10612 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
10613 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
10615 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
10616 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
10617 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
10625 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
10626 if ( this.getSaneType( config
) === 'number' ) {
10627 return $( '<input>' )
10628 .attr( 'step', 'any' )
10629 .attr( 'type', 'number' );
10631 return $( '<input>' ).attr( 'type', this.getSaneType( config
) );
10636 * Get sanitized value for 'type' for given config.
10638 * @param {Object} config Configuration options
10639 * @return {string|null}
10642 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
10643 var allowedTypes
= [
10650 return allowedTypes
.indexOf( config
.type
) !== -1 ? config
.type
: 'text';
10654 * Focus the input and select a specified range within the text.
10656 * @param {number} from Select from offset
10657 * @param {number} [to] Select to offset, defaults to from
10659 * @return {OO.ui.Widget} The widget, for chaining
10661 OO
.ui
.TextInputWidget
.prototype.selectRange = function ( from, to
) {
10662 var isBackwards
, start
, end
,
10663 input
= this.$input
[ 0 ];
10667 isBackwards
= to
< from;
10668 start
= isBackwards
? to
: from;
10669 end
= isBackwards
? from : to
;
10674 input
.setSelectionRange( start
, end
, isBackwards
? 'backward' : 'forward' );
10676 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
10677 // Rather than expensively check if the input is attached every time, just check
10678 // if it was the cause of an error being thrown. If not, rethrow the error.
10679 if ( this.getElementDocument().body
.contains( input
) ) {
10687 * Get an object describing the current selection range in a directional manner
10689 * @return {Object} Object containing 'from' and 'to' offsets
10691 OO
.ui
.TextInputWidget
.prototype.getRange = function () {
10692 var input
= this.$input
[ 0 ],
10693 start
= input
.selectionStart
,
10694 end
= input
.selectionEnd
,
10695 isBackwards
= input
.selectionDirection
=== 'backward';
10698 from: isBackwards
? end
: start
,
10699 to
: isBackwards
? start
: end
10704 * Get the length of the text input value.
10706 * This could differ from the length of #getValue if the
10707 * value gets filtered
10709 * @return {number} Input length
10711 OO
.ui
.TextInputWidget
.prototype.getInputLength = function () {
10712 return this.$input
[ 0 ].value
.length
;
10716 * Focus the input and select the entire text.
10719 * @return {OO.ui.Widget} The widget, for chaining
10721 OO
.ui
.TextInputWidget
.prototype.select = function () {
10722 return this.selectRange( 0, this.getInputLength() );
10726 * Focus the input and move the cursor to the start.
10729 * @return {OO.ui.Widget} The widget, for chaining
10731 OO
.ui
.TextInputWidget
.prototype.moveCursorToStart = function () {
10732 return this.selectRange( 0 );
10736 * Focus the input and move the cursor to the end.
10739 * @return {OO.ui.Widget} The widget, for chaining
10741 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
10742 return this.selectRange( this.getInputLength() );
10746 * Insert new content into the input.
10748 * @param {string} content Content to be inserted
10750 * @return {OO.ui.Widget} The widget, for chaining
10752 OO
.ui
.TextInputWidget
.prototype.insertContent = function ( content
) {
10754 range
= this.getRange(),
10755 value
= this.getValue();
10757 start
= Math
.min( range
.from, range
.to
);
10758 end
= Math
.max( range
.from, range
.to
);
10760 this.setValue( value
.slice( 0, start
) + content
+ value
.slice( end
) );
10761 this.selectRange( start
+ content
.length
);
10766 * Insert new content either side of a selection.
10768 * @param {string} pre Content to be inserted before the selection
10769 * @param {string} post Content to be inserted after the selection
10771 * @return {OO.ui.Widget} The widget, for chaining
10773 OO
.ui
.TextInputWidget
.prototype.encapsulateContent = function ( pre
, post
) {
10775 range
= this.getRange(),
10776 offset
= pre
.length
;
10778 start
= Math
.min( range
.from, range
.to
);
10779 end
= Math
.max( range
.from, range
.to
);
10781 this.selectRange( start
).insertContent( pre
);
10782 this.selectRange( offset
+ end
).insertContent( post
);
10784 this.selectRange( offset
+ start
, offset
+ end
);
10789 * Set the validation pattern.
10791 * The validation pattern is either a regular expression, a function, or the symbolic name of a
10792 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
10793 * value must contain only numbers).
10795 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
10796 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
10798 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
10799 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
10800 this.validate
= validate
;
10802 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
10807 * Sets the 'invalid' flag appropriately.
10809 * @param {boolean} [isValid] Optionally override validation result
10811 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
10813 setFlag = function ( valid
) {
10815 widget
.$input
.attr( 'aria-invalid', 'true' );
10817 widget
.$input
.removeAttr( 'aria-invalid' );
10819 widget
.setFlags( { invalid
: !valid
} );
10822 if ( isValid
!== undefined ) {
10823 setFlag( isValid
);
10825 this.getValidity().then( function () {
10834 * Get the validity of current value.
10836 * This method returns a promise that resolves if the value is valid and rejects if
10837 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
10839 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
10841 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
10844 function rejectOrResolve( valid
) {
10846 return $.Deferred().resolve().promise();
10848 return $.Deferred().reject().promise();
10852 // Check browser validity and reject if it is invalid
10854 this.$input
[ 0 ].checkValidity
!== undefined &&
10855 this.$input
[ 0 ].checkValidity() === false
10857 return rejectOrResolve( false );
10860 // Run our checks if the browser thinks the field is valid
10861 if ( this.validate
instanceof Function
) {
10862 result
= this.validate( this.getValue() );
10863 if ( result
&& $.isFunction( result
.promise
) ) {
10864 return result
.promise().then( function ( valid
) {
10865 return rejectOrResolve( valid
);
10868 return rejectOrResolve( result
);
10871 return rejectOrResolve( this.getValue().match( this.validate
) );
10876 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
10878 * @param {string} labelPosition Label position, 'before' or 'after'
10880 * @return {OO.ui.Widget} The widget, for chaining
10882 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
10883 this.labelPosition
= labelPosition
;
10884 if ( this.label
) {
10885 // If there is no label and we only change the position, #updatePosition is a no-op,
10886 // but it takes really a lot of work to do nothing.
10887 this.updatePosition();
10893 * Update the position of the inline label.
10895 * This method is called by #setLabelPosition, and can also be called on its own if
10896 * something causes the label to be mispositioned.
10899 * @return {OO.ui.Widget} The widget, for chaining
10901 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
10902 var after
= this.labelPosition
=== 'after';
10905 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
10906 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
10908 this.valCache
= null;
10909 this.scrollWidth
= null;
10910 this.positionLabel();
10916 * Position the label by setting the correct padding on the input.
10920 * @return {OO.ui.Widget} The widget, for chaining
10922 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
10923 var after
, rtl
, property
, newCss
;
10925 if ( this.isWaitingToBeAttached
) {
10926 // #onElementAttach will be called soon, which calls this method
10931 'padding-right': '',
10935 if ( this.label
) {
10936 this.$element
.append( this.$label
);
10938 this.$label
.detach();
10939 // Clear old values if present
10940 this.$input
.css( newCss
);
10944 after
= this.labelPosition
=== 'after';
10945 rtl
= this.$element
.css( 'direction' ) === 'rtl';
10946 property
= after
=== rtl
? 'padding-left' : 'padding-right';
10948 newCss
[ property
] = this.$label
.outerWidth( true ) + ( after
? this.scrollWidth
: 0 );
10949 // We have to clear the padding on the other side, in case the element direction changed
10950 this.$input
.css( newCss
);
10957 * @extends OO.ui.TextInputWidget
10960 * @param {Object} [config] Configuration options
10962 OO
.ui
.SearchInputWidget
= function OoUiSearchInputWidget( config
) {
10963 config
= $.extend( {
10967 // Parent constructor
10968 OO
.ui
.SearchInputWidget
.parent
.call( this, config
);
10971 this.connect( this, {
10976 this.updateSearchIndicator();
10977 this.connect( this, {
10978 disable
: 'onDisable'
10984 OO
.inheritClass( OO
.ui
.SearchInputWidget
, OO
.ui
.TextInputWidget
);
10992 OO
.ui
.SearchInputWidget
.prototype.getSaneType = function () {
10999 OO
.ui
.SearchInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
11000 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
11001 // Clear the text field
11002 this.setValue( '' );
11009 * Update the 'clear' indicator displayed on type: 'search' text
11010 * fields, hiding it when the field is already empty or when it's not
11013 OO
.ui
.SearchInputWidget
.prototype.updateSearchIndicator = function () {
11014 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
11015 this.setIndicator( null );
11017 this.setIndicator( 'clear' );
11022 * Handle change events.
11026 OO
.ui
.SearchInputWidget
.prototype.onChange = function () {
11027 this.updateSearchIndicator();
11031 * Handle disable events.
11033 * @param {boolean} disabled Element is disabled
11036 OO
.ui
.SearchInputWidget
.prototype.onDisable = function () {
11037 this.updateSearchIndicator();
11043 OO
.ui
.SearchInputWidget
.prototype.setReadOnly = function ( state
) {
11044 OO
.ui
.SearchInputWidget
.parent
.prototype.setReadOnly
.call( this, state
);
11045 this.updateSearchIndicator();
11051 * @extends OO.ui.TextInputWidget
11054 * @param {Object} [config] Configuration options
11055 * @cfg {number} [rows] Number of visible lines in textarea. If used with `autosize`,
11056 * specifies minimum number of rows to display.
11057 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
11058 * Use the #maxRows config to specify a maximum number of displayed rows.
11059 * @cfg {number} [maxRows] Maximum number of rows to display when #autosize is set to true.
11060 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
11062 OO
.ui
.MultilineTextInputWidget
= function OoUiMultilineTextInputWidget( config
) {
11063 config
= $.extend( {
11066 // Parent constructor
11067 OO
.ui
.MultilineTextInputWidget
.parent
.call( this, config
);
11070 this.autosize
= !!config
.autosize
;
11071 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
11072 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
11074 // Clone for resizing
11075 if ( this.autosize
) {
11076 this.$clone
= this.$input
11078 .removeAttr( 'id' )
11079 .removeAttr( 'name' )
11080 .insertAfter( this.$input
)
11081 .attr( 'aria-hidden', 'true' )
11082 .addClass( 'oo-ui-element-hidden' );
11086 this.connect( this, {
11091 if ( config
.rows
) {
11092 this.$input
.attr( 'rows', config
.rows
);
11094 if ( this.autosize
) {
11095 this.$input
.addClass( 'oo-ui-textInputWidget-autosized' );
11096 this.isWaitingToBeAttached
= true;
11097 this.installParentChangeDetector();
11103 OO
.inheritClass( OO
.ui
.MultilineTextInputWidget
, OO
.ui
.TextInputWidget
);
11105 /* Static Methods */
11110 OO
.ui
.MultilineTextInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
11111 var state
= OO
.ui
.MultilineTextInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
11112 state
.scrollTop
= config
.$input
.scrollTop();
11121 OO
.ui
.MultilineTextInputWidget
.prototype.onElementAttach = function () {
11122 OO
.ui
.MultilineTextInputWidget
.parent
.prototype.onElementAttach
.call( this );
11127 * Handle change events.
11131 OO
.ui
.MultilineTextInputWidget
.prototype.onChange = function () {
11138 OO
.ui
.MultilineTextInputWidget
.prototype.updatePosition = function () {
11139 OO
.ui
.MultilineTextInputWidget
.parent
.prototype.updatePosition
.call( this );
11146 * Modify to emit 'enter' on Ctrl/Meta+Enter, instead of plain Enter
11148 OO
.ui
.MultilineTextInputWidget
.prototype.onKeyPress = function ( e
) {
11150 ( e
.which
=== OO
.ui
.Keys
.ENTER
&& ( e
.ctrlKey
|| e
.metaKey
) ) ||
11151 // Some platforms emit keycode 10 for ctrl+enter in a textarea
11154 this.emit( 'enter', e
);
11159 * Automatically adjust the size of the text input.
11161 * This only affects multiline inputs that are {@link #autosize autosized}.
11164 * @return {OO.ui.Widget} The widget, for chaining
11167 OO
.ui
.MultilineTextInputWidget
.prototype.adjustSize = function () {
11168 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
,
11169 idealHeight
, newHeight
, scrollWidth
, property
;
11171 if ( this.$input
.val() !== this.valCache
) {
11172 if ( this.autosize
) {
11174 .val( this.$input
.val() )
11175 .attr( 'rows', this.minRows
)
11176 // Set inline height property to 0 to measure scroll height
11177 .css( 'height', 0 );
11179 this.$clone
.removeClass( 'oo-ui-element-hidden' );
11181 this.valCache
= this.$input
.val();
11183 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
11185 // Remove inline height property to measure natural heights
11186 this.$clone
.css( 'height', '' );
11187 innerHeight
= this.$clone
.innerHeight();
11188 outerHeight
= this.$clone
.outerHeight();
11190 // Measure max rows height
11192 .attr( 'rows', this.maxRows
)
11193 .css( 'height', 'auto' )
11195 maxInnerHeight
= this.$clone
.innerHeight();
11197 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
11198 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
11199 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
11200 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
11202 this.$clone
.addClass( 'oo-ui-element-hidden' );
11204 // Only apply inline height when expansion beyond natural height is needed
11205 // Use the difference between the inner and outer height as a buffer
11206 newHeight
= idealHeight
> innerHeight
? idealHeight
+ ( outerHeight
- innerHeight
) : '';
11207 if ( newHeight
!== this.styleHeight
) {
11208 this.$input
.css( 'height', newHeight
);
11209 this.styleHeight
= newHeight
;
11210 this.emit( 'resize' );
11213 scrollWidth
= this.$input
[ 0 ].offsetWidth
- this.$input
[ 0 ].clientWidth
;
11214 if ( scrollWidth
!== this.scrollWidth
) {
11215 property
= this.$element
.css( 'direction' ) === 'rtl' ? 'left' : 'right';
11217 this.$label
.css( { right
: '', left
: '' } );
11218 this.$indicator
.css( { right
: '', left
: '' } );
11220 if ( scrollWidth
) {
11221 this.$indicator
.css( property
, scrollWidth
);
11222 if ( this.labelPosition
=== 'after' ) {
11223 this.$label
.css( property
, scrollWidth
);
11227 this.scrollWidth
= scrollWidth
;
11228 this.positionLabel();
11238 OO
.ui
.MultilineTextInputWidget
.prototype.getInputElement = function () {
11239 return $( '<textarea>' );
11243 * Check if the input automatically adjusts its size.
11245 * @return {boolean}
11247 OO
.ui
.MultilineTextInputWidget
.prototype.isAutosizing = function () {
11248 return !!this.autosize
;
11254 OO
.ui
.MultilineTextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
11255 OO
.ui
.MultilineTextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
11256 if ( state
.scrollTop
!== undefined ) {
11257 this.$input
.scrollTop( state
.scrollTop
);
11262 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
11263 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
11264 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
11266 * - by typing a value in the text input field. If the value exactly matches the value of a menu
11267 * option, that option will appear to be selected.
11268 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
11271 * After the user chooses an option, its `data` will be used as a new value for the widget.
11272 * A `label` also can be specified for each option: if given, it will be shown instead of the
11273 * `data` in the dropdown menu.
11275 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
11277 * For more information about menus and options, please see the [OOUI documentation on MediaWiki][1].
11280 * // Example: A ComboBoxInputWidget.
11281 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11282 * value: 'Option 1',
11284 * { data: 'Option 1' },
11285 * { data: 'Option 2' },
11286 * { data: 'Option 3' }
11289 * $( 'body' ).append( comboBox.$element );
11292 * // Example: A ComboBoxInputWidget with additional option labels.
11293 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11294 * value: 'Option 1',
11297 * data: 'Option 1',
11298 * label: 'Option One'
11301 * data: 'Option 2',
11302 * label: 'Option Two'
11305 * data: 'Option 3',
11306 * label: 'Option Three'
11310 * $( 'body' ).append( comboBox.$element );
11312 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
11315 * @extends OO.ui.TextInputWidget
11318 * @param {Object} [config] Configuration options
11319 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
11320 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
11321 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
11322 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
11323 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
11324 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11326 OO
.ui
.ComboBoxInputWidget
= function OoUiComboBoxInputWidget( config
) {
11327 // Configuration initialization
11328 config
= $.extend( {
11329 autocomplete
: false
11332 // ComboBoxInputWidget shouldn't support `multiline`
11333 config
.multiline
= false;
11335 // See InputWidget#reusePreInfuseDOM about `config.$input`
11336 if ( config
.$input
) {
11337 config
.$input
.removeAttr( 'list' );
11340 // Parent constructor
11341 OO
.ui
.ComboBoxInputWidget
.parent
.call( this, config
);
11344 this.$overlay
= ( config
.$overlay
=== true ? OO
.ui
.getDefaultOverlay() : config
.$overlay
) || this.$element
;
11345 this.dropdownButton
= new OO
.ui
.ButtonWidget( {
11346 classes
: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ],
11348 disabled
: this.disabled
11350 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend(
11354 $floatableContainer
: this.$element
,
11355 disabled
: this.isDisabled()
11361 this.connect( this, {
11362 change
: 'onInputChange',
11363 enter
: 'onInputEnter'
11365 this.dropdownButton
.connect( this, {
11366 click
: 'onDropdownButtonClick'
11368 this.menu
.connect( this, {
11369 choose
: 'onMenuChoose',
11370 add
: 'onMenuItemsChange',
11371 remove
: 'onMenuItemsChange',
11372 toggle
: 'onMenuToggle'
11376 this.$input
.attr( {
11378 'aria-owns': this.menu
.getElementId(),
11379 'aria-autocomplete': 'list'
11381 // Do not override options set via config.menu.items
11382 if ( config
.options
!== undefined ) {
11383 this.setOptions( config
.options
);
11385 this.$field
= $( '<div>' )
11386 .addClass( 'oo-ui-comboBoxInputWidget-field' )
11387 .append( this.$input
, this.dropdownButton
.$element
);
11389 .addClass( 'oo-ui-comboBoxInputWidget' )
11390 .append( this.$field
);
11391 this.$overlay
.append( this.menu
.$element
);
11392 this.onMenuItemsChange();
11397 OO
.inheritClass( OO
.ui
.ComboBoxInputWidget
, OO
.ui
.TextInputWidget
);
11402 * Get the combobox's menu.
11404 * @return {OO.ui.MenuSelectWidget} Menu widget
11406 OO
.ui
.ComboBoxInputWidget
.prototype.getMenu = function () {
11411 * Get the combobox's text input widget.
11413 * @return {OO.ui.TextInputWidget} Text input widget
11415 OO
.ui
.ComboBoxInputWidget
.prototype.getInput = function () {
11420 * Handle input change events.
11423 * @param {string} value New value
11425 OO
.ui
.ComboBoxInputWidget
.prototype.onInputChange = function ( value
) {
11426 var match
= this.menu
.findItemFromData( value
);
11428 this.menu
.selectItem( match
);
11429 if ( this.menu
.findHighlightedItem() ) {
11430 this.menu
.highlightItem( match
);
11433 if ( !this.isDisabled() ) {
11434 this.menu
.toggle( true );
11439 * Handle input enter events.
11443 OO
.ui
.ComboBoxInputWidget
.prototype.onInputEnter = function () {
11444 if ( !this.isDisabled() ) {
11445 this.menu
.toggle( false );
11450 * Handle button click events.
11454 OO
.ui
.ComboBoxInputWidget
.prototype.onDropdownButtonClick = function () {
11455 this.menu
.toggle();
11460 * Handle menu choose events.
11463 * @param {OO.ui.OptionWidget} item Chosen item
11465 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuChoose = function ( item
) {
11466 this.setValue( item
.getData() );
11470 * Handle menu item change events.
11474 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuItemsChange = function () {
11475 var match
= this.menu
.findItemFromData( this.getValue() );
11476 this.menu
.selectItem( match
);
11477 if ( this.menu
.findHighlightedItem() ) {
11478 this.menu
.highlightItem( match
);
11480 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu
.isEmpty() );
11484 * Handle menu toggle events.
11487 * @param {boolean} isVisible Open state of the menu
11489 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuToggle = function ( isVisible
) {
11490 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-open', isVisible
);
11496 OO
.ui
.ComboBoxInputWidget
.prototype.setDisabled = function ( disabled
) {
11498 OO
.ui
.ComboBoxInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
11500 if ( this.dropdownButton
) {
11501 this.dropdownButton
.setDisabled( this.isDisabled() );
11504 this.menu
.setDisabled( this.isDisabled() );
11511 * Set the options available for this input.
11513 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
11515 * @return {OO.ui.Widget} The widget, for chaining
11517 OO
.ui
.ComboBoxInputWidget
.prototype.setOptions = function ( options
) {
11520 .addItems( options
.map( function ( opt
) {
11521 return new OO
.ui
.MenuOptionWidget( {
11523 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
11531 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
11532 * which is a widget that is specified by reference before any optional configuration settings.
11534 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
11536 * - **left**: The label is placed before the field-widget and aligned with the left margin.
11537 * A left-alignment is used for forms with many fields.
11538 * - **right**: The label is placed before the field-widget and aligned to the right margin.
11539 * A right-alignment is used for long but familiar forms which users tab through,
11540 * verifying the current field with a quick glance at the label.
11541 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
11542 * that users fill out from top to bottom.
11543 * - **inline**: The label is placed after the field-widget and aligned to the left.
11544 * An inline-alignment is best used with checkboxes or radio buttons.
11546 * Help text can either be:
11548 * - accessed via a help icon that appears in the upper right corner of the rendered field layout, or
11549 * - shown as a subtle explanation below the label.
11551 * If the help text is brief, or is essential to always expose it, set `helpInline` to `true`. If it
11552 * is long or not essential, leave `helpInline` to its default, `false`.
11554 * Please see the [OOUI documentation on MediaWiki] [1] for examples and more information.
11556 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
11559 * @extends OO.ui.Layout
11560 * @mixins OO.ui.mixin.LabelElement
11561 * @mixins OO.ui.mixin.TitledElement
11564 * @param {OO.ui.Widget} fieldWidget Field widget
11565 * @param {Object} [config] Configuration options
11566 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top'
11568 * @cfg {Array} [errors] Error messages about the widget, which will be
11569 * displayed below the widget.
11570 * The array may contain strings or OO.ui.HtmlSnippet instances.
11571 * @cfg {Array} [notices] Notices about the widget, which will be displayed
11572 * below the widget.
11573 * The array may contain strings or OO.ui.HtmlSnippet instances.
11574 * These are more visible than `help` messages when `helpInline` is set, and so
11575 * might be good for transient messages.
11576 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified
11577 * and `helpInline` is `false`, a "help" icon will appear in the upper-right
11578 * corner of the rendered field; clicking it will display the text in a popup.
11579 * If `helpInline` is `true`, then a subtle description will be shown after the
11581 * @cfg {boolean} [helpInline=false] Whether or not the help should be inline,
11582 * or shown when the "help" icon is clicked.
11583 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if
11585 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11587 * @throws {Error} An error is thrown if no widget is specified
11589 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
11590 // Allow passing positional parameters inside the config object
11591 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
11592 config
= fieldWidget
;
11593 fieldWidget
= config
.fieldWidget
;
11596 // Make sure we have required constructor arguments
11597 if ( fieldWidget
=== undefined ) {
11598 throw new Error( 'Widget not found' );
11601 // Configuration initialization
11602 config
= $.extend( { align
: 'left', helpInline
: false }, config
);
11604 // Parent constructor
11605 OO
.ui
.FieldLayout
.parent
.call( this, config
);
11607 // Mixin constructors
11608 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, {
11609 $label
: $( '<label>' )
11611 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
11614 this.fieldWidget
= fieldWidget
;
11617 this.$field
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
11618 this.$messages
= $( '<ul>' );
11619 this.$header
= $( '<span>' );
11620 this.$body
= $( '<div>' );
11622 this.helpInline
= config
.helpInline
;
11625 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
11628 this.$help
= config
.help
?
11629 this.createHelpElement( config
.help
, config
.$overlay
) :
11631 if ( this.fieldWidget
.getInputId() ) {
11632 this.$label
.attr( 'for', this.fieldWidget
.getInputId() );
11633 if ( this.helpInline
) {
11634 this.$help
.attr( 'for', this.fieldWidget
.getInputId() );
11637 this.$label
.on( 'click', function () {
11638 this.fieldWidget
.simulateLabelClick();
11640 if ( this.helpInline
) {
11641 this.$help
.on( 'click', function () {
11642 this.fieldWidget
.simulateLabelClick();
11647 .addClass( 'oo-ui-fieldLayout' )
11648 .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget
.isDisabled() )
11649 .append( this.$body
);
11650 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
11651 this.$header
.addClass( 'oo-ui-fieldLayout-header' );
11652 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
11654 .addClass( 'oo-ui-fieldLayout-field' )
11655 .append( this.fieldWidget
.$element
);
11657 this.setErrors( config
.errors
|| [] );
11658 this.setNotices( config
.notices
|| [] );
11659 this.setAlignment( config
.align
);
11660 // Call this again to take into account the widget's accessKey
11661 this.updateTitle();
11666 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
11667 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
11668 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
11673 * Handle field disable events.
11676 * @param {boolean} value Field is disabled
11678 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
11679 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
11683 * Get the widget contained by the field.
11685 * @return {OO.ui.Widget} Field widget
11687 OO
.ui
.FieldLayout
.prototype.getField = function () {
11688 return this.fieldWidget
;
11692 * Return `true` if the given field widget can be used with `'inline'` alignment (see
11693 * #setAlignment). Return `false` if it can't or if this can't be determined.
11695 * @return {boolean}
11697 OO
.ui
.FieldLayout
.prototype.isFieldInline = function () {
11698 // This is very simplistic, but should be good enough.
11699 return this.getField().$element
.prop( 'tagName' ).toLowerCase() === 'span';
11704 * @param {string} kind 'error' or 'notice'
11705 * @param {string|OO.ui.HtmlSnippet} text
11708 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
11709 var $listItem
, $icon
, message
;
11710 $listItem
= $( '<li>' );
11711 if ( kind
=== 'error' ) {
11712 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
11713 $listItem
.attr( 'role', 'alert' );
11714 } else if ( kind
=== 'notice' ) {
11715 $icon
= new OO
.ui
.IconWidget( { icon
: 'notice' } ).$element
;
11719 message
= new OO
.ui
.LabelWidget( { label
: text
} );
11721 .append( $icon
, message
.$element
)
11722 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
11727 * Set the field alignment mode.
11730 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
11732 * @return {OO.ui.BookletLayout} The layout, for chaining
11734 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
11735 if ( value
!== this.align
) {
11736 // Default to 'left'
11737 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
11741 if ( value
=== 'inline' && !this.isFieldInline() ) {
11744 // Reorder elements
11746 if ( this.helpInline
) {
11747 if ( value
=== 'top' ) {
11748 this.$header
.append( this.$label
);
11749 this.$body
.append( this.$header
, this.$field
, this.$help
);
11750 } else if ( value
=== 'inline' ) {
11751 this.$header
.append( this.$label
, this.$help
);
11752 this.$body
.append( this.$field
, this.$header
);
11754 this.$header
.append( this.$label
, this.$help
);
11755 this.$body
.append( this.$header
, this.$field
);
11758 if ( value
=== 'top' ) {
11759 this.$header
.append( this.$help
, this.$label
);
11760 this.$body
.append( this.$header
, this.$field
);
11761 } else if ( value
=== 'inline' ) {
11762 this.$header
.append( this.$help
, this.$label
);
11763 this.$body
.append( this.$field
, this.$header
);
11765 this.$header
.append( this.$label
);
11766 this.$body
.append( this.$header
, this.$help
, this.$field
);
11769 // Set classes. The following classes can be used here:
11770 // * oo-ui-fieldLayout-align-left
11771 // * oo-ui-fieldLayout-align-right
11772 // * oo-ui-fieldLayout-align-top
11773 // * oo-ui-fieldLayout-align-inline
11774 if ( this.align
) {
11775 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
11777 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
11778 this.align
= value
;
11785 * Set the list of error messages.
11787 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
11788 * The array may contain strings or OO.ui.HtmlSnippet instances.
11790 * @return {OO.ui.BookletLayout} The layout, for chaining
11792 OO
.ui
.FieldLayout
.prototype.setErrors = function ( errors
) {
11793 this.errors
= errors
.slice();
11794 this.updateMessages();
11799 * Set the list of notice messages.
11801 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
11802 * The array may contain strings or OO.ui.HtmlSnippet instances.
11804 * @return {OO.ui.BookletLayout} The layout, for chaining
11806 OO
.ui
.FieldLayout
.prototype.setNotices = function ( notices
) {
11807 this.notices
= notices
.slice();
11808 this.updateMessages();
11813 * Update the rendering of error and notice messages.
11817 OO
.ui
.FieldLayout
.prototype.updateMessages = function () {
11819 this.$messages
.empty();
11821 if ( this.errors
.length
|| this.notices
.length
) {
11822 this.$body
.after( this.$messages
);
11824 this.$messages
.remove();
11828 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
11829 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
11831 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
11832 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
11837 * Include information about the widget's accessKey in our title. TitledElement calls this method.
11838 * (This is a bit of a hack.)
11841 * @param {string} title Tooltip label for 'title' attribute
11844 OO
.ui
.FieldLayout
.prototype.formatTitleWithAccessKey = function ( title
) {
11845 if ( this.fieldWidget
&& this.fieldWidget
.formatTitleWithAccessKey
) {
11846 return this.fieldWidget
.formatTitleWithAccessKey( title
);
11852 * Creates and returns the help element. Also sets the `aria-describedby`
11853 * attribute on the main element of the `fieldWidget`.
11856 * @param {string|OO.ui.HtmlSnippet} [help] Help text.
11857 * @param {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup.
11858 * @return {jQuery} The element that should become `this.$help`.
11860 OO
.ui
.FieldLayout
.prototype.createHelpElement = function ( help
, $overlay
) {
11861 var helpId
, helpWidget
;
11863 if ( this.helpInline
) {
11864 helpWidget
= new OO
.ui
.LabelWidget( {
11866 classes
: [ 'oo-ui-inline-help' ]
11869 helpId
= helpWidget
.getElementId();
11871 helpWidget
= new OO
.ui
.PopupButtonWidget( {
11872 $overlay
: $overlay
,
11876 classes
: [ 'oo-ui-fieldLayout-help' ],
11879 label
: OO
.ui
.msg( 'ooui-field-help' ),
11880 invisibleLabel
: true
11882 if ( help
instanceof OO
.ui
.HtmlSnippet
) {
11883 helpWidget
.getPopup().$body
.html( help
.toString() );
11885 helpWidget
.getPopup().$body
.text( help
);
11888 helpId
= helpWidget
.getPopup().getBodyId();
11891 // Set the 'aria-describedby' attribute on the fieldWidget
11892 // Preference given to an input or a button
11894 this.fieldWidget
.$input
||
11895 this.fieldWidget
.$button
||
11896 this.fieldWidget
.$element
11897 ).attr( 'aria-describedby', helpId
);
11899 return helpWidget
.$element
;
11903 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
11904 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
11905 * is required and is specified before any optional configuration settings.
11907 * Labels can be aligned in one of four ways:
11909 * - **left**: The label is placed before the field-widget and aligned with the left margin.
11910 * A left-alignment is used for forms with many fields.
11911 * - **right**: The label is placed before the field-widget and aligned to the right margin.
11912 * A right-alignment is used for long but familiar forms which users tab through,
11913 * verifying the current field with a quick glance at the label.
11914 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
11915 * that users fill out from top to bottom.
11916 * - **inline**: The label is placed after the field-widget and aligned to the left.
11917 * An inline-alignment is best used with checkboxes or radio buttons.
11919 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
11920 * text is specified.
11923 * // Example of an ActionFieldLayout
11924 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
11925 * new OO.ui.TextInputWidget( {
11926 * placeholder: 'Field widget'
11928 * new OO.ui.ButtonWidget( {
11932 * label: 'An ActionFieldLayout. This label is aligned top',
11934 * help: 'This is help text'
11938 * $( 'body' ).append( actionFieldLayout.$element );
11941 * @extends OO.ui.FieldLayout
11944 * @param {OO.ui.Widget} fieldWidget Field widget
11945 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
11946 * @param {Object} config
11948 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
11949 // Allow passing positional parameters inside the config object
11950 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
11951 config
= fieldWidget
;
11952 fieldWidget
= config
.fieldWidget
;
11953 buttonWidget
= config
.buttonWidget
;
11956 // Parent constructor
11957 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
11960 this.buttonWidget
= buttonWidget
;
11961 this.$button
= $( '<span>' );
11962 this.$input
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
11966 .addClass( 'oo-ui-actionFieldLayout' );
11968 .addClass( 'oo-ui-actionFieldLayout-button' )
11969 .append( this.buttonWidget
.$element
);
11971 .addClass( 'oo-ui-actionFieldLayout-input' )
11972 .append( this.fieldWidget
.$element
);
11974 .append( this.$input
, this.$button
);
11979 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
11982 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
11983 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
11984 * configured with a label as well. For more information and examples,
11985 * please see the [OOUI documentation on MediaWiki][1].
11988 * // Example of a fieldset layout
11989 * var input1 = new OO.ui.TextInputWidget( {
11990 * placeholder: 'A text input field'
11993 * var input2 = new OO.ui.TextInputWidget( {
11994 * placeholder: 'A text input field'
11997 * var fieldset = new OO.ui.FieldsetLayout( {
11998 * label: 'Example of a fieldset layout'
12001 * fieldset.addItems( [
12002 * new OO.ui.FieldLayout( input1, {
12003 * label: 'Field One'
12005 * new OO.ui.FieldLayout( input2, {
12006 * label: 'Field Two'
12009 * $( 'body' ).append( fieldset.$element );
12011 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
12014 * @extends OO.ui.Layout
12015 * @mixins OO.ui.mixin.IconElement
12016 * @mixins OO.ui.mixin.LabelElement
12017 * @mixins OO.ui.mixin.GroupElement
12020 * @param {Object} [config] Configuration options
12021 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
12022 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
12023 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
12024 * For important messages, you are advised to use `notices`, as they are always shown.
12025 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
12026 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
12028 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
12029 // Configuration initialization
12030 config
= config
|| {};
12032 // Parent constructor
12033 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
12035 // Mixin constructors
12036 OO
.ui
.mixin
.IconElement
.call( this, config
);
12037 OO
.ui
.mixin
.LabelElement
.call( this, config
);
12038 OO
.ui
.mixin
.GroupElement
.call( this, config
);
12041 this.$header
= $( '<legend>' );
12042 if ( config
.help
) {
12043 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
12044 $overlay
: config
.$overlay
,
12048 classes
: [ 'oo-ui-fieldsetLayout-help' ],
12051 label
: OO
.ui
.msg( 'ooui-field-help' ),
12052 invisibleLabel
: true
12054 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
12055 this.popupButtonWidget
.getPopup().$body
.html( config
.help
.toString() );
12057 this.popupButtonWidget
.getPopup().$body
.text( config
.help
);
12059 this.$help
= this.popupButtonWidget
.$element
;
12061 this.$help
= $( [] );
12066 .addClass( 'oo-ui-fieldsetLayout-header' )
12067 .append( this.$icon
, this.$label
, this.$help
);
12068 this.$group
.addClass( 'oo-ui-fieldsetLayout-group' );
12070 .addClass( 'oo-ui-fieldsetLayout' )
12071 .prepend( this.$header
, this.$group
);
12072 if ( Array
.isArray( config
.items
) ) {
12073 this.addItems( config
.items
);
12079 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
12080 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
12081 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
12082 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
12084 /* Static Properties */
12090 OO
.ui
.FieldsetLayout
.static.tagName
= 'fieldset';
12093 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
12094 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
12095 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
12096 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
12098 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
12099 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
12100 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
12101 * some fancier controls. Some controls have both regular and InputWidget variants, for example
12102 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
12103 * often have simplified APIs to match the capabilities of HTML forms.
12104 * See the [OOUI documentation on MediaWiki] [2] for more information about InputWidgets.
12106 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Forms
12107 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
12110 * // Example of a form layout that wraps a fieldset layout
12111 * var input1 = new OO.ui.TextInputWidget( {
12112 * placeholder: 'Username'
12114 * var input2 = new OO.ui.TextInputWidget( {
12115 * placeholder: 'Password',
12118 * var submit = new OO.ui.ButtonInputWidget( {
12122 * var fieldset = new OO.ui.FieldsetLayout( {
12123 * label: 'A form layout'
12125 * fieldset.addItems( [
12126 * new OO.ui.FieldLayout( input1, {
12127 * label: 'Username',
12130 * new OO.ui.FieldLayout( input2, {
12131 * label: 'Password',
12134 * new OO.ui.FieldLayout( submit )
12136 * var form = new OO.ui.FormLayout( {
12137 * items: [ fieldset ],
12138 * action: '/api/formhandler',
12141 * $( 'body' ).append( form.$element );
12144 * @extends OO.ui.Layout
12145 * @mixins OO.ui.mixin.GroupElement
12148 * @param {Object} [config] Configuration options
12149 * @cfg {string} [method] HTML form `method` attribute
12150 * @cfg {string} [action] HTML form `action` attribute
12151 * @cfg {string} [enctype] HTML form `enctype` attribute
12152 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
12154 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
12157 // Configuration initialization
12158 config
= config
|| {};
12160 // Parent constructor
12161 OO
.ui
.FormLayout
.parent
.call( this, config
);
12163 // Mixin constructors
12164 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
12167 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
12169 // Make sure the action is safe
12170 action
= config
.action
;
12171 if ( action
!== undefined && !OO
.ui
.isSafeUrl( action
) ) {
12172 action
= './' + action
;
12177 .addClass( 'oo-ui-formLayout' )
12179 method
: config
.method
,
12181 enctype
: config
.enctype
12183 if ( Array
.isArray( config
.items
) ) {
12184 this.addItems( config
.items
);
12190 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
12191 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
12196 * A 'submit' event is emitted when the form is submitted.
12201 /* Static Properties */
12207 OO
.ui
.FormLayout
.static.tagName
= 'form';
12212 * Handle form submit events.
12215 * @param {jQuery.Event} e Submit event
12217 * @return {OO.ui.FormLayout} The layout, for chaining
12219 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
12220 if ( this.emit( 'submit' ) ) {
12226 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
12227 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
12230 * // Example of a panel layout
12231 * var panel = new OO.ui.PanelLayout( {
12235 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
12237 * $( 'body' ).append( panel.$element );
12240 * @extends OO.ui.Layout
12243 * @param {Object} [config] Configuration options
12244 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
12245 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
12246 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
12247 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
12249 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
12250 // Configuration initialization
12251 config
= $.extend( {
12258 // Parent constructor
12259 OO
.ui
.PanelLayout
.parent
.call( this, config
);
12262 this.$element
.addClass( 'oo-ui-panelLayout' );
12263 if ( config
.scrollable
) {
12264 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
12266 if ( config
.padded
) {
12267 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
12269 if ( config
.expanded
) {
12270 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
12272 if ( config
.framed
) {
12273 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
12279 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
12284 * Focus the panel layout
12286 * The default implementation just focuses the first focusable element in the panel
12288 OO
.ui
.PanelLayout
.prototype.focus = function () {
12289 OO
.ui
.findFocusable( this.$element
).focus();
12293 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
12294 * items), with small margins between them. Convenient when you need to put a number of block-level
12295 * widgets on a single line next to each other.
12297 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
12300 * // HorizontalLayout with a text input and a label
12301 * var layout = new OO.ui.HorizontalLayout( {
12303 * new OO.ui.LabelWidget( { label: 'Label' } ),
12304 * new OO.ui.TextInputWidget( { value: 'Text' } )
12307 * $( 'body' ).append( layout.$element );
12310 * @extends OO.ui.Layout
12311 * @mixins OO.ui.mixin.GroupElement
12314 * @param {Object} [config] Configuration options
12315 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
12317 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
12318 // Configuration initialization
12319 config
= config
|| {};
12321 // Parent constructor
12322 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
12324 // Mixin constructors
12325 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
12328 this.$element
.addClass( 'oo-ui-horizontalLayout' );
12329 if ( Array
.isArray( config
.items
) ) {
12330 this.addItems( config
.items
);
12336 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
12337 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);
12340 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
12341 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
12342 * (to adjust the value in increments) to allow the user to enter a number.
12345 * // Example: A NumberInputWidget.
12346 * var numberInput = new OO.ui.NumberInputWidget( {
12347 * label: 'NumberInputWidget',
12348 * input: { value: 5 },
12352 * $( 'body' ).append( numberInput.$element );
12355 * @extends OO.ui.TextInputWidget
12358 * @param {Object} [config] Configuration options
12359 * @cfg {Object} [minusButton] Configuration options to pass to the
12360 * {@link OO.ui.ButtonWidget decrementing button widget}.
12361 * @cfg {Object} [plusButton] Configuration options to pass to the
12362 * {@link OO.ui.ButtonWidget incrementing button widget}.
12363 * @cfg {number} [min=-Infinity] Minimum allowed value
12364 * @cfg {number} [max=Infinity] Maximum allowed value
12365 * @cfg {number|null} [step] If specified, the field only accepts values that are multiples of this.
12366 * @cfg {number} [buttonStep=step||1] Delta when using the buttons or up/down arrow keys.
12367 * Defaults to `step` if specified, otherwise `1`.
12368 * @cfg {number} [pageStep=10*buttonStep] Delta when using the page-up/page-down keys.
12369 * Defaults to 10 times `buttonStep`.
12370 * @cfg {boolean} [showButtons=true] Whether to show the plus and minus buttons.
12372 OO
.ui
.NumberInputWidget
= function OoUiNumberInputWidget( config
) {
12373 var $field
= $( '<div>' )
12374 .addClass( 'oo-ui-numberInputWidget-field' );
12376 // Configuration initialization
12377 config
= $.extend( {
12383 // For backward compatibility
12384 $.extend( config
, config
.input
);
12387 // Parent constructor
12388 OO
.ui
.NumberInputWidget
.parent
.call( this, $.extend( config
, {
12392 if ( config
.showButtons
) {
12393 this.minusButton
= new OO
.ui
.ButtonWidget( $.extend(
12395 disabled
: this.isDisabled(),
12397 classes
: [ 'oo-ui-numberInputWidget-minusButton' ],
12402 this.minusButton
.$element
.attr( 'aria-hidden', 'true' );
12403 this.plusButton
= new OO
.ui
.ButtonWidget( $.extend(
12405 disabled
: this.isDisabled(),
12407 classes
: [ 'oo-ui-numberInputWidget-plusButton' ],
12412 this.plusButton
.$element
.attr( 'aria-hidden', 'true' );
12417 keydown
: this.onKeyDown
.bind( this ),
12418 'wheel mousewheel DOMMouseScroll': this.onWheel
.bind( this )
12420 if ( config
.showButtons
) {
12421 this.plusButton
.connect( this, {
12422 click
: [ 'onButtonClick', +1 ]
12424 this.minusButton
.connect( this, {
12425 click
: [ 'onButtonClick', -1 ]
12430 $field
.append( this.$input
);
12431 if ( config
.showButtons
) {
12433 .prepend( this.minusButton
.$element
)
12434 .append( this.plusButton
.$element
);
12438 if ( config
.allowInteger
|| config
.isInteger
) {
12439 // Backward compatibility
12442 this.setRange( config
.min
, config
.max
);
12443 this.setStep( config
.buttonStep
, config
.pageStep
, config
.step
);
12444 // Set the validation method after we set step and range
12445 // so that it doesn't immediately call setValidityFlag
12446 this.setValidation( this.validateNumber
.bind( this ) );
12449 .addClass( 'oo-ui-numberInputWidget' )
12450 .toggleClass( 'oo-ui-numberInputWidget-buttoned', config
.showButtons
)
12456 OO
.inheritClass( OO
.ui
.NumberInputWidget
, OO
.ui
.TextInputWidget
);
12460 // Backward compatibility
12461 OO
.ui
.NumberInputWidget
.prototype.setAllowInteger = function ( flag
) {
12462 this.setStep( flag
? 1 : null );
12464 // Backward compatibility
12465 OO
.ui
.NumberInputWidget
.prototype.setIsInteger
= OO
.ui
.NumberInputWidget
.prototype.setAllowInteger
;
12467 // Backward compatibility
12468 OO
.ui
.NumberInputWidget
.prototype.getAllowInteger = function () {
12469 return this.step
=== 1;
12471 // Backward compatibility
12472 OO
.ui
.NumberInputWidget
.prototype.getIsInteger
= OO
.ui
.NumberInputWidget
.prototype.getAllowInteger
;
12475 * Set the range of allowed values
12477 * @param {number} min Minimum allowed value
12478 * @param {number} max Maximum allowed value
12480 OO
.ui
.NumberInputWidget
.prototype.setRange = function ( min
, max
) {
12482 throw new Error( 'Minimum (' + min
+ ') must not be greater than maximum (' + max
+ ')' );
12486 this.$input
.attr( 'min', this.min
);
12487 this.$input
.attr( 'max', this.max
);
12488 this.setValidityFlag();
12492 * Get the current range
12494 * @return {number[]} Minimum and maximum values
12496 OO
.ui
.NumberInputWidget
.prototype.getRange = function () {
12497 return [ this.min
, this.max
];
12501 * Set the stepping deltas
12503 * @param {number} [buttonStep=step||1] Delta when using the buttons or up/down arrow keys.
12504 * Defaults to `step` if specified, otherwise `1`.
12505 * @param {number} [pageStep=10*buttonStep] Delta when using the page-up/page-down keys.
12506 * Defaults to 10 times `buttonStep`.
12507 * @param {number|null} [step] If specified, the field only accepts values that are multiples of this.
12509 OO
.ui
.NumberInputWidget
.prototype.setStep = function ( buttonStep
, pageStep
, step
) {
12510 if ( buttonStep
=== undefined ) {
12511 buttonStep
= step
|| 1;
12513 if ( pageStep
=== undefined ) {
12514 pageStep
= 10 * buttonStep
;
12516 if ( step
!== null && step
<= 0 ) {
12517 throw new Error( 'Step value, if given, must be positive' );
12519 if ( buttonStep
<= 0 ) {
12520 throw new Error( 'Button step value must be positive' );
12522 if ( pageStep
<= 0 ) {
12523 throw new Error( 'Page step value must be positive' );
12526 this.buttonStep
= buttonStep
;
12527 this.pageStep
= pageStep
;
12528 this.$input
.attr( 'step', this.step
|| 'any' );
12529 this.setValidityFlag();
12535 OO
.ui
.NumberInputWidget
.prototype.setValue = function ( value
) {
12536 if ( value
=== '' ) {
12537 // Some browsers allow a value in the input even if there isn't one reported by $input.val()
12538 // so here we make sure an 'empty' value is actually displayed as such.
12539 this.$input
.val( '' );
12541 return OO
.ui
.NumberInputWidget
.parent
.prototype.setValue
.call( this, value
);
12545 * Get the current stepping values
12547 * @return {number[]} Button step, page step, and validity step
12549 OO
.ui
.NumberInputWidget
.prototype.getStep = function () {
12550 return [ this.buttonStep
, this.pageStep
, this.step
];
12554 * Get the current value of the widget as a number
12556 * @return {number} May be NaN, or an invalid number
12558 OO
.ui
.NumberInputWidget
.prototype.getNumericValue = function () {
12559 return +this.getValue();
12563 * Adjust the value of the widget
12565 * @param {number} delta Adjustment amount
12567 OO
.ui
.NumberInputWidget
.prototype.adjustValue = function ( delta
) {
12568 var n
, v
= this.getNumericValue();
12571 if ( isNaN( delta
) || !isFinite( delta
) ) {
12572 throw new Error( 'Delta must be a finite number' );
12575 if ( isNaN( v
) ) {
12579 n
= Math
.max( Math
.min( n
, this.max
), this.min
);
12581 n
= Math
.round( n
/ this.step
) * this.step
;
12586 this.setValue( n
);
12593 * @param {string} value Field value
12594 * @return {boolean}
12596 OO
.ui
.NumberInputWidget
.prototype.validateNumber = function ( value
) {
12598 if ( value
=== '' ) {
12599 return !this.isRequired();
12602 if ( isNaN( n
) || !isFinite( n
) ) {
12606 if ( this.step
&& Math
.floor( n
/ this.step
) !== n
/ this.step
) {
12610 if ( n
< this.min
|| n
> this.max
) {
12618 * Handle mouse click events.
12621 * @param {number} dir +1 or -1
12623 OO
.ui
.NumberInputWidget
.prototype.onButtonClick = function ( dir
) {
12624 this.adjustValue( dir
* this.buttonStep
);
12628 * Handle mouse wheel events.
12631 * @param {jQuery.Event} event
12632 * @return {undefined/boolean} False to prevent default if event is handled
12634 OO
.ui
.NumberInputWidget
.prototype.onWheel = function ( event
) {
12637 if ( !this.isDisabled() && this.$input
.is( ':focus' ) ) {
12638 // Standard 'wheel' event
12639 if ( event
.originalEvent
.deltaMode
!== undefined ) {
12640 this.sawWheelEvent
= true;
12642 if ( event
.originalEvent
.deltaY
) {
12643 delta
= -event
.originalEvent
.deltaY
;
12644 } else if ( event
.originalEvent
.deltaX
) {
12645 delta
= event
.originalEvent
.deltaX
;
12648 // Non-standard events
12649 if ( !this.sawWheelEvent
) {
12650 if ( event
.originalEvent
.wheelDeltaX
) {
12651 delta
= -event
.originalEvent
.wheelDeltaX
;
12652 } else if ( event
.originalEvent
.wheelDeltaY
) {
12653 delta
= event
.originalEvent
.wheelDeltaY
;
12654 } else if ( event
.originalEvent
.wheelDelta
) {
12655 delta
= event
.originalEvent
.wheelDelta
;
12656 } else if ( event
.originalEvent
.detail
) {
12657 delta
= -event
.originalEvent
.detail
;
12662 delta
= delta
< 0 ? -1 : 1;
12663 this.adjustValue( delta
* this.buttonStep
);
12671 * Handle key down events.
12674 * @param {jQuery.Event} e Key down event
12675 * @return {undefined/boolean} False to prevent default if event is handled
12677 OO
.ui
.NumberInputWidget
.prototype.onKeyDown = function ( e
) {
12678 if ( !this.isDisabled() ) {
12679 switch ( e
.which
) {
12680 case OO
.ui
.Keys
.UP
:
12681 this.adjustValue( this.buttonStep
);
12683 case OO
.ui
.Keys
.DOWN
:
12684 this.adjustValue( -this.buttonStep
);
12686 case OO
.ui
.Keys
.PAGEUP
:
12687 this.adjustValue( this.pageStep
);
12689 case OO
.ui
.Keys
.PAGEDOWN
:
12690 this.adjustValue( -this.pageStep
);
12699 OO
.ui
.NumberInputWidget
.prototype.setDisabled = function ( disabled
) {
12701 OO
.ui
.NumberInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
12703 if ( this.minusButton
) {
12704 this.minusButton
.setDisabled( this.isDisabled() );
12706 if ( this.plusButton
) {
12707 this.plusButton
.setDisabled( this.isDisabled() );
12715 //# sourceMappingURL=oojs-ui-core.js.map.json