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-01T02:03:33Z
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
1383 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1384 show
= show
=== undefined ? !this.visible
: !!show
;
1386 if ( show
!== this.isVisible() ) {
1387 this.visible
= show
;
1388 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1389 this.emit( 'toggle', show
);
1396 * Check if element is visible.
1398 * @return {boolean} element is visible
1400 OO
.ui
.Element
.prototype.isVisible = function () {
1401 return this.visible
;
1407 * @return {Mixed} Element data
1409 OO
.ui
.Element
.prototype.getData = function () {
1416 * @param {Mixed} data Element data
1419 OO
.ui
.Element
.prototype.setData = function ( data
) {
1425 * Set the element has an 'id' attribute.
1427 * @param {string} id
1430 OO
.ui
.Element
.prototype.setElementId = function ( id
) {
1431 this.elementId
= id
;
1432 this.$element
.attr( 'id', id
);
1437 * Ensure that the element has an 'id' attribute, setting it to an unique value if it's missing,
1438 * and return its value.
1442 OO
.ui
.Element
.prototype.getElementId = function () {
1443 if ( this.elementId
=== null ) {
1444 this.setElementId( OO
.ui
.generateElementId() );
1446 return this.elementId
;
1450 * Check if element supports one or more methods.
1452 * @param {string|string[]} methods Method or list of methods to check
1453 * @return {boolean} All methods are supported
1455 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1459 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1460 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1461 if ( $.isFunction( this[ methods
[ i
] ] ) ) {
1466 return methods
.length
=== support
;
1470 * Update the theme-provided classes.
1472 * @localdoc This is called in element mixins and widget classes any time state changes.
1473 * Updating is debounced, minimizing overhead of changing multiple attributes and
1474 * guaranteeing that theme updates do not occur within an element's constructor
1476 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1477 OO
.ui
.theme
.queueUpdateElementClasses( this );
1481 * Get the HTML tag name.
1483 * Override this method to base the result on instance information.
1485 * @return {string} HTML tag name
1487 OO
.ui
.Element
.prototype.getTagName = function () {
1488 return this.constructor.static.tagName
;
1492 * Check if the element is attached to the DOM
1494 * @return {boolean} The element is attached to the DOM
1496 OO
.ui
.Element
.prototype.isElementAttached = function () {
1497 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1501 * Get the DOM document.
1503 * @return {HTMLDocument} Document object
1505 OO
.ui
.Element
.prototype.getElementDocument = function () {
1506 // Don't cache this in other ways either because subclasses could can change this.$element
1507 return OO
.ui
.Element
.static.getDocument( this.$element
);
1511 * Get the DOM window.
1513 * @return {Window} Window object
1515 OO
.ui
.Element
.prototype.getElementWindow = function () {
1516 return OO
.ui
.Element
.static.getWindow( this.$element
);
1520 * Get closest scrollable container.
1522 * @return {HTMLElement} Closest scrollable container
1524 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1525 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1529 * Get group element is in.
1531 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1533 OO
.ui
.Element
.prototype.getElementGroup = function () {
1534 return this.elementGroup
;
1538 * Set group element is in.
1540 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1543 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1544 this.elementGroup
= group
;
1549 * Scroll element into view.
1551 * @param {Object} [config] Configuration options
1552 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1554 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1556 !this.isElementAttached() ||
1557 !this.isVisible() ||
1558 ( this.getElementGroup() && !this.getElementGroup().isVisible() )
1560 return $.Deferred().resolve();
1562 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1566 * Restore the pre-infusion dynamic state for this widget.
1568 * This method is called after #$element has been inserted into DOM. The parameter is the return
1569 * value of #gatherPreInfuseState.
1572 * @param {Object} state
1574 OO
.ui
.Element
.prototype.restorePreInfuseState = function () {
1578 * Wraps an HTML snippet for use with configuration values which default
1579 * to strings. This bypasses the default html-escaping done to string
1585 * @param {string} [content] HTML content
1587 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
1589 this.content
= content
;
1594 OO
.initClass( OO
.ui
.HtmlSnippet
);
1601 * @return {string} Unchanged HTML snippet.
1603 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
1604 return this.content
;
1608 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1609 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1610 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1611 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1612 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1616 * @extends OO.ui.Element
1617 * @mixins OO.EventEmitter
1620 * @param {Object} [config] Configuration options
1622 OO
.ui
.Layout
= function OoUiLayout( config
) {
1623 // Configuration initialization
1624 config
= config
|| {};
1626 // Parent constructor
1627 OO
.ui
.Layout
.parent
.call( this, config
);
1629 // Mixin constructors
1630 OO
.EventEmitter
.call( this );
1633 this.$element
.addClass( 'oo-ui-layout' );
1638 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1639 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1644 * Reset scroll offsets
1648 OO
.ui
.Layout
.prototype.resetScroll = function () {
1649 this.$element
[ 0 ].scrollTop
= 0;
1650 // TODO: Reset scrollLeft in an RTL-aware manner, see OO.ui.Element.static.getScrollLeft.
1656 * Widgets are compositions of one or more OOUI elements that users can both view
1657 * and interact with. All widgets can be configured and modified via a standard API,
1658 * and their state can change dynamically according to a model.
1662 * @extends OO.ui.Element
1663 * @mixins OO.EventEmitter
1666 * @param {Object} [config] Configuration options
1667 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1668 * appearance reflects this state.
1670 OO
.ui
.Widget
= function OoUiWidget( config
) {
1671 // Initialize config
1672 config
= $.extend( { disabled
: false }, config
);
1674 // Parent constructor
1675 OO
.ui
.Widget
.parent
.call( this, config
);
1677 // Mixin constructors
1678 OO
.EventEmitter
.call( this );
1681 this.disabled
= null;
1682 this.wasDisabled
= null;
1685 this.$element
.addClass( 'oo-ui-widget' );
1686 this.setDisabled( !!config
.disabled
);
1691 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1692 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1699 * A 'disable' event is emitted when the disabled state of the widget changes
1700 * (i.e. on disable **and** enable).
1702 * @param {boolean} disabled Widget is disabled
1708 * A 'toggle' event is emitted when the visibility of the widget changes.
1710 * @param {boolean} visible Widget is visible
1716 * Check if the widget is disabled.
1718 * @return {boolean} Widget is disabled
1720 OO
.ui
.Widget
.prototype.isDisabled = function () {
1721 return this.disabled
;
1725 * Set the 'disabled' state of the widget.
1727 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1729 * @param {boolean} disabled Disable widget
1732 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
1735 this.disabled
= !!disabled
;
1736 isDisabled
= this.isDisabled();
1737 if ( isDisabled
!== this.wasDisabled
) {
1738 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
1739 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
1740 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
1741 this.emit( 'disable', isDisabled
);
1742 this.updateThemeClasses();
1744 this.wasDisabled
= isDisabled
;
1750 * Update the disabled state, in case of changes in parent widget.
1754 OO
.ui
.Widget
.prototype.updateDisabled = function () {
1755 this.setDisabled( this.disabled
);
1760 * Get an ID of a labelable node which is part of this widget, if any, to be used for `<label for>`
1763 * If this function returns null, the widget should have a meaningful #simulateLabelClick method
1766 * @return {string|null} The ID of the labelable element
1768 OO
.ui
.Widget
.prototype.getInputId = function () {
1773 * Simulate the behavior of clicking on a label (a HTML `<label>` element) bound to this input.
1774 * HTML only allows `<label>` to act on specific "labelable" elements; complex widgets might need to
1775 * override this method to provide intuitive, accessible behavior.
1777 * By default, this does nothing. OO.ui.mixin.TabIndexedElement overrides it for focusable widgets.
1778 * Individual widgets may override it too.
1780 * This method is called by OO.ui.LabelWidget and OO.ui.FieldLayout. It should not be called
1783 OO
.ui
.Widget
.prototype.simulateLabelClick = function () {
1794 OO
.ui
.Theme
= function OoUiTheme() {
1795 this.elementClassesQueue
= [];
1796 this.debouncedUpdateQueuedElementClasses
= OO
.ui
.debounce( this.updateQueuedElementClasses
);
1801 OO
.initClass( OO
.ui
.Theme
);
1806 * Get a list of classes to be applied to a widget.
1808 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
1809 * otherwise state transitions will not work properly.
1811 * @param {OO.ui.Element} element Element for which to get classes
1812 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1814 OO
.ui
.Theme
.prototype.getElementClasses = function () {
1815 return { on
: [], off
: [] };
1819 * Update CSS classes provided by the theme.
1821 * For elements with theme logic hooks, this should be called any time there's a state change.
1823 * @param {OO.ui.Element} element Element for which to update classes
1825 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
1826 var $elements
= $( [] ),
1827 classes
= this.getElementClasses( element
);
1829 if ( element
.$icon
) {
1830 $elements
= $elements
.add( element
.$icon
);
1832 if ( element
.$indicator
) {
1833 $elements
= $elements
.add( element
.$indicator
);
1837 .removeClass( classes
.off
)
1838 .addClass( classes
.on
);
1844 OO
.ui
.Theme
.prototype.updateQueuedElementClasses = function () {
1846 for ( i
= 0; i
< this.elementClassesQueue
.length
; i
++ ) {
1847 this.updateElementClasses( this.elementClassesQueue
[ i
] );
1850 this.elementClassesQueue
= [];
1854 * Queue #updateElementClasses to be called for this element.
1856 * @localdoc QUnit tests override this method to directly call #queueUpdateElementClasses,
1857 * to make them synchronous.
1859 * @param {OO.ui.Element} element Element for which to update classes
1861 OO
.ui
.Theme
.prototype.queueUpdateElementClasses = function ( element
) {
1862 // Keep items in the queue unique. Use lastIndexOf to start checking from the end because that's
1863 // the most common case (this method is often called repeatedly for the same element).
1864 if ( this.elementClassesQueue
.lastIndexOf( element
) !== -1 ) {
1867 this.elementClassesQueue
.push( element
);
1868 this.debouncedUpdateQueuedElementClasses();
1872 * Get the transition duration in milliseconds for dialogs opening/closing
1874 * The dialog should be fully rendered this many milliseconds after the
1875 * ready process has executed.
1877 * @return {number} Transition duration in milliseconds
1879 OO
.ui
.Theme
.prototype.getDialogTransitionDuration = function () {
1884 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
1885 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
1886 * order in which users will navigate through the focusable elements via the "tab" key.
1889 * // TabIndexedElement is mixed into the ButtonWidget class
1890 * // to provide a tabIndex property.
1891 * var button1 = new OO.ui.ButtonWidget( {
1895 * var button2 = new OO.ui.ButtonWidget( {
1899 * var button3 = new OO.ui.ButtonWidget( {
1903 * var button4 = new OO.ui.ButtonWidget( {
1907 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
1913 * @param {Object} [config] Configuration options
1914 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
1915 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
1916 * functionality will be applied to it instead.
1917 * @cfg {string|number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
1918 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
1919 * to remove the element from the tab-navigation flow.
1921 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
1922 // Configuration initialization
1923 config
= $.extend( { tabIndex
: 0 }, config
);
1926 this.$tabIndexed
= null;
1927 this.tabIndex
= null;
1930 this.connect( this, { disable
: 'onTabIndexedElementDisable' } );
1933 this.setTabIndex( config
.tabIndex
);
1934 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
1939 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
1944 * Set the element that should use the tabindex functionality.
1946 * This method is used to retarget a tabindex mixin so that its functionality applies
1947 * to the specified element. If an element is currently using the functionality, the mixin’s
1948 * effect on that element is removed before the new element is set up.
1950 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
1953 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
1954 var tabIndex
= this.tabIndex
;
1955 // Remove attributes from old $tabIndexed
1956 this.setTabIndex( null );
1957 // Force update of new $tabIndexed
1958 this.$tabIndexed
= $tabIndexed
;
1959 this.tabIndex
= tabIndex
;
1960 return this.updateTabIndex();
1964 * Set the value of the tabindex.
1966 * @param {string|number|null} tabIndex Tabindex value, or `null` for no tabindex
1969 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
1970 tabIndex
= /^-?\d+$/.test( tabIndex
) ? Number( tabIndex
) : null;
1972 if ( this.tabIndex
!== tabIndex
) {
1973 this.tabIndex
= tabIndex
;
1974 this.updateTabIndex();
1981 * Update the `tabindex` attribute, in case of changes to tab index or
1987 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
1988 if ( this.$tabIndexed
) {
1989 if ( this.tabIndex
!== null ) {
1990 // Do not index over disabled elements
1991 this.$tabIndexed
.attr( {
1992 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
1993 // Support: ChromeVox and NVDA
1994 // These do not seem to inherit aria-disabled from parent elements
1995 'aria-disabled': this.isDisabled().toString()
1998 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
2005 * Handle disable events.
2008 * @param {boolean} disabled Element is disabled
2010 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
2011 this.updateTabIndex();
2015 * Get the value of the tabindex.
2017 * @return {number|null} Tabindex value
2019 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
2020 return this.tabIndex
;
2024 * Get an ID of a focusable element of this widget, if any, to be used for `<label for>` value.
2026 * If the element already has an ID then that is returned, otherwise unique ID is
2027 * generated, set on the element, and returned.
2029 * @return {string|null} The ID of the focusable element
2031 OO
.ui
.mixin
.TabIndexedElement
.prototype.getInputId = function () {
2034 if ( !this.$tabIndexed
) {
2037 if ( !this.isLabelableNode( this.$tabIndexed
) ) {
2041 id
= this.$tabIndexed
.attr( 'id' );
2042 if ( id
=== undefined ) {
2043 id
= OO
.ui
.generateElementId();
2044 this.$tabIndexed
.attr( 'id', id
);
2051 * Whether the node is 'labelable' according to the HTML spec
2052 * (i.e., whether it can be interacted with through a `<label for="…">`).
2053 * See: <https://html.spec.whatwg.org/multipage/forms.html#category-label>.
2056 * @param {jQuery} $node
2059 OO
.ui
.mixin
.TabIndexedElement
.prototype.isLabelableNode = function ( $node
) {
2061 labelableTags
= [ 'button', 'meter', 'output', 'progress', 'select', 'textarea' ],
2062 tagName
= $node
.prop( 'tagName' ).toLowerCase();
2064 if ( tagName
=== 'input' && $node
.attr( 'type' ) !== 'hidden' ) {
2067 if ( labelableTags
.indexOf( tagName
) !== -1 ) {
2074 * Focus this element.
2078 OO
.ui
.mixin
.TabIndexedElement
.prototype.focus = function () {
2079 if ( !this.isDisabled() ) {
2080 this.$tabIndexed
.focus();
2086 * Blur this element.
2090 OO
.ui
.mixin
.TabIndexedElement
.prototype.blur = function () {
2091 this.$tabIndexed
.blur();
2096 * @inheritdoc OO.ui.Widget
2098 OO
.ui
.mixin
.TabIndexedElement
.prototype.simulateLabelClick = function () {
2103 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
2104 * interface element that can be configured with access keys for accessibility.
2105 * See the [OOUI documentation on MediaWiki] [1] for examples.
2107 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches#Buttons
2113 * @param {Object} [config] Configuration options
2114 * @cfg {jQuery} [$button] The button element created by the class.
2115 * If this configuration is omitted, the button element will use a generated `<a>`.
2116 * @cfg {boolean} [framed=true] Render the button with a frame
2118 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
2119 // Configuration initialization
2120 config
= config
|| {};
2123 this.$button
= null;
2125 this.active
= config
.active
!== undefined && config
.active
;
2126 this.onDocumentMouseUpHandler
= this.onDocumentMouseUp
.bind( this );
2127 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
2128 this.onDocumentKeyUpHandler
= this.onDocumentKeyUp
.bind( this );
2129 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
2130 this.onClickHandler
= this.onClick
.bind( this );
2131 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
2134 this.$element
.addClass( 'oo-ui-buttonElement' );
2135 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
2136 this.setButtonElement( config
.$button
|| $( '<a>' ) );
2141 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
2143 /* Static Properties */
2146 * Cancel mouse down events.
2148 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
2149 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
2150 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
2155 * @property {boolean}
2157 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
2162 * A 'click' event is emitted when the button element is clicked.
2170 * Set the button element.
2172 * This method is used to retarget a button mixin so that its functionality applies to
2173 * the specified button element instead of the one created by the class. If a button element
2174 * is already set, the method will remove the mixin’s effect on that element.
2176 * @param {jQuery} $button Element to use as button
2178 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
2179 if ( this.$button
) {
2181 .removeClass( 'oo-ui-buttonElement-button' )
2182 .removeAttr( 'role accesskey' )
2184 mousedown
: this.onMouseDownHandler
,
2185 keydown
: this.onKeyDownHandler
,
2186 click
: this.onClickHandler
,
2187 keypress
: this.onKeyPressHandler
2191 this.$button
= $button
2192 .addClass( 'oo-ui-buttonElement-button' )
2194 mousedown
: this.onMouseDownHandler
,
2195 keydown
: this.onKeyDownHandler
,
2196 click
: this.onClickHandler
,
2197 keypress
: this.onKeyPressHandler
2200 // Add `role="button"` on `<a>` elements, where it's needed
2201 // `toUpperCase()` is added for XHTML documents
2202 if ( this.$button
.prop( 'tagName' ).toUpperCase() === 'A' ) {
2203 this.$button
.attr( 'role', 'button' );
2208 * Handles mouse down events.
2211 * @param {jQuery.Event} e Mouse down event
2213 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
2214 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
2217 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
2218 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
2219 // reliably remove the pressed class
2220 this.getElementDocument().addEventListener( 'mouseup', this.onDocumentMouseUpHandler
, true );
2221 // Prevent change of focus unless specifically configured otherwise
2222 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
2228 * Handles document mouse up events.
2231 * @param {MouseEvent} e Mouse up event
2233 OO
.ui
.mixin
.ButtonElement
.prototype.onDocumentMouseUp = function ( e
) {
2234 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
2237 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
2238 // Stop listening for mouseup, since we only needed this once
2239 this.getElementDocument().removeEventListener( 'mouseup', this.onDocumentMouseUpHandler
, true );
2242 // Deprecated alias since 0.28.3
2243 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp = function () {
2244 OO
.ui
.warnDeprecation( 'onMouseUp is deprecated, use onDocumentMouseUp instead' );
2245 this.onDocumentMouseUp
.apply( this, arguments
);
2249 * Handles mouse click events.
2252 * @param {jQuery.Event} e Mouse click event
2255 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
2256 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
2257 if ( this.emit( 'click' ) ) {
2264 * Handles key down events.
2267 * @param {jQuery.Event} e Key down event
2269 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
2270 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2273 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
2274 // Run the keyup handler no matter where the key is when the button is let go, so we can
2275 // reliably remove the pressed class
2276 this.getElementDocument().addEventListener( 'keyup', this.onDocumentKeyUpHandler
, true );
2280 * Handles document key up events.
2283 * @param {KeyboardEvent} e Key up event
2285 OO
.ui
.mixin
.ButtonElement
.prototype.onDocumentKeyUp = function ( e
) {
2286 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2289 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
2290 // Stop listening for keyup, since we only needed this once
2291 this.getElementDocument().removeEventListener( 'keyup', this.onDocumentKeyUpHandler
, true );
2294 // Deprecated alias since 0.28.3
2295 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyUp = function () {
2296 OO
.ui
.warnDeprecation( 'onKeyUp is deprecated, use onDocumentKeyUp instead' );
2297 this.onDocumentKeyUp
.apply( this, arguments
);
2301 * Handles key press events.
2304 * @param {jQuery.Event} e Key press event
2307 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
2308 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
2309 if ( this.emit( 'click' ) ) {
2316 * Check if button has a frame.
2318 * @return {boolean} Button is framed
2320 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
2325 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
2327 * @param {boolean} [framed] Make button framed, omit to toggle
2330 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
2331 framed
= framed
=== undefined ? !this.framed
: !!framed
;
2332 if ( framed
!== this.framed
) {
2333 this.framed
= framed
;
2335 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
2336 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
2337 this.updateThemeClasses();
2344 * Set the button's active state.
2346 * The active state can be set on:
2348 * - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected
2349 * - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on
2350 * - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page
2353 * @param {boolean} value Make button active
2356 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
2357 this.active
= !!value
;
2358 this.$element
.toggleClass( 'oo-ui-buttonElement-active', this.active
);
2359 this.updateThemeClasses();
2364 * Check if the button is active
2367 * @return {boolean} The button is active
2369 OO
.ui
.mixin
.ButtonElement
.prototype.isActive = function () {
2374 * Any OOUI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
2375 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
2376 * items from the group is done through the interface the class provides.
2377 * For more information, please see the [OOUI documentation on MediaWiki] [1].
2379 * [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Groups
2382 * @mixins OO.EmitterList
2386 * @param {Object} [config] Configuration options
2387 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
2388 * is omitted, the group element will use a generated `<div>`.
2390 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
2391 // Configuration initialization
2392 config
= config
|| {};
2394 // Mixin constructors
2395 OO
.EmitterList
.call( this, config
);
2401 this.setGroupElement( config
.$group
|| $( '<div>' ) );
2406 OO
.mixinClass( OO
.ui
.mixin
.GroupElement
, OO
.EmitterList
);
2413 * A change event is emitted when the set of selected items changes.
2415 * @param {OO.ui.Element[]} items Items currently in the group
2421 * Set the group element.
2423 * If an element is already set, items will be moved to the new element.
2425 * @param {jQuery} $group Element to use as group
2427 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
2430 this.$group
= $group
;
2431 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2432 this.$group
.append( this.items
[ i
].$element
);
2437 * Find an item by its data.
2439 * Only the first item with matching data will be returned. To return all matching items,
2440 * use the #findItemsFromData method.
2442 * @param {Object} data Item data to search for
2443 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2445 OO
.ui
.mixin
.GroupElement
.prototype.findItemFromData = function ( data
) {
2447 hash
= OO
.getHash( data
);
2449 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2450 item
= this.items
[ i
];
2451 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2460 * Find items by their data.
2462 * All items with matching data will be returned. To return only the first match, use the #findItemFromData method instead.
2464 * @param {Object} data Item data to search for
2465 * @return {OO.ui.Element[]} Items with equivalent data
2467 OO
.ui
.mixin
.GroupElement
.prototype.findItemsFromData = function ( data
) {
2469 hash
= OO
.getHash( data
),
2472 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2473 item
= this.items
[ i
];
2474 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2483 * Add items to the group.
2485 * Items will be added to the end of the group array unless the optional `index` parameter specifies
2486 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
2488 * @param {OO.ui.Element[]} items An array of items to add to the group
2489 * @param {number} [index] Index of the insertion point
2492 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
2494 OO
.EmitterList
.prototype.addItems
.call( this, items
, index
);
2496 this.emit( 'change', this.getItems() );
2503 OO
.ui
.mixin
.GroupElement
.prototype.moveItem = function ( items
, newIndex
) {
2504 // insertItemElements expects this.items to not have been modified yet, so call before the mixin
2505 this.insertItemElements( items
, newIndex
);
2508 newIndex
= OO
.EmitterList
.prototype.moveItem
.call( this, items
, newIndex
);
2516 OO
.ui
.mixin
.GroupElement
.prototype.insertItem = function ( item
, index
) {
2517 item
.setElementGroup( this );
2518 this.insertItemElements( item
, index
);
2521 index
= OO
.EmitterList
.prototype.insertItem
.call( this, item
, index
);
2527 * Insert elements into the group
2530 * @param {OO.ui.Element} itemWidget Item to insert
2531 * @param {number} index Insertion index
2533 OO
.ui
.mixin
.GroupElement
.prototype.insertItemElements = function ( itemWidget
, index
) {
2534 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
2535 this.$group
.append( itemWidget
.$element
);
2536 } else if ( index
=== 0 ) {
2537 this.$group
.prepend( itemWidget
.$element
);
2539 this.items
[ index
].$element
.before( itemWidget
.$element
);
2544 * Remove the specified items from a group.
2546 * Removed items are detached (not removed) from the DOM so that they may be reused.
2547 * To remove all items from a group, you may wish to use the #clearItems method instead.
2549 * @param {OO.ui.Element[]} items An array of items to remove
2552 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
2553 var i
, len
, item
, index
;
2555 // Remove specific items elements
2556 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
2558 index
= this.items
.indexOf( item
);
2559 if ( index
!== -1 ) {
2560 item
.setElementGroup( null );
2561 item
.$element
.detach();
2566 OO
.EmitterList
.prototype.removeItems
.call( this, items
);
2568 this.emit( 'change', this.getItems() );
2573 * Clear all items from the group.
2575 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2576 * To remove only a subset of items from a group, use the #removeItems method.
2580 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
2583 // Remove all item elements
2584 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2585 this.items
[ i
].setElementGroup( null );
2586 this.items
[ i
].$element
.detach();
2590 OO
.EmitterList
.prototype.clearItems
.call( this );
2592 this.emit( 'change', this.getItems() );
2597 * LabelElement is often mixed into other classes to generate a label, which
2598 * helps identify the function of an interface element.
2599 * See the [OOUI documentation on MediaWiki] [1] for more information.
2601 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
2607 * @param {Object} [config] Configuration options
2608 * @cfg {jQuery} [$label] The label element created by the class. If this
2609 * configuration is omitted, the label element will use a generated `<span>`.
2610 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
2611 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
2612 * in the future. See the [OOUI documentation on MediaWiki] [2] for examples.
2613 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
2614 * @cfg {boolean} [invisibleLabel] Whether the label should be visually hidden (but still accessible
2615 * to screen-readers).
2617 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
2618 // Configuration initialization
2619 config
= config
|| {};
2624 this.invisibleLabel
= null;
2627 this.setLabel( config
.label
|| this.constructor.static.label
);
2628 this.setLabelElement( config
.$label
|| $( '<span>' ) );
2629 this.setInvisibleLabel( config
.invisibleLabel
);
2634 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
2639 * @event labelChange
2640 * @param {string} value
2643 /* Static Properties */
2646 * The label text. The label can be specified as a plaintext string, a function that will
2647 * produce a string in the future, or `null` for no label. The static value will
2648 * be overridden if a label is specified with the #label config option.
2652 * @property {string|Function|null}
2654 OO
.ui
.mixin
.LabelElement
.static.label
= null;
2656 /* Static methods */
2659 * Highlight the first occurrence of the query in the given text
2661 * @param {string} text Text
2662 * @param {string} query Query to find
2663 * @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
2664 * @return {jQuery} Text with the first match of the query
2665 * sub-string wrapped in highlighted span
2667 OO
.ui
.mixin
.LabelElement
.static.highlightQuery = function ( text
, query
, compare
) {
2670 $result
= $( '<span>' );
2674 qLen
= query
.length
;
2675 for ( i
= 0; offset
=== -1 && i
<= tLen
- qLen
; i
++ ) {
2676 if ( compare( query
, text
.slice( i
, i
+ qLen
) ) === 0 ) {
2681 offset
= text
.toLowerCase().indexOf( query
.toLowerCase() );
2684 if ( !query
.length
|| offset
=== -1 ) {
2685 $result
.text( text
);
2688 document
.createTextNode( text
.slice( 0, offset
) ),
2690 .addClass( 'oo-ui-labelElement-label-highlight' )
2691 .text( text
.slice( offset
, offset
+ query
.length
) ),
2692 document
.createTextNode( text
.slice( offset
+ query
.length
) )
2695 return $result
.contents();
2701 * Set the label element.
2703 * If an element is already set, it will be cleaned up before setting up the new element.
2705 * @param {jQuery} $label Element to use as label
2707 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
2708 if ( this.$label
) {
2709 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
2712 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
2713 this.setLabelContent( this.label
);
2719 * An empty string will result in the label being hidden. A string containing only whitespace will
2720 * be converted to a single ` `.
2722 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
2723 * text; or null for no label
2726 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
2727 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
2728 label
= ( ( typeof label
=== 'string' || label
instanceof jQuery
) && label
.length
) || ( label
instanceof OO
.ui
.HtmlSnippet
&& label
.toString().length
) ? label
: null;
2730 if ( this.label
!== label
) {
2731 if ( this.$label
) {
2732 this.setLabelContent( label
);
2735 this.emit( 'labelChange' );
2738 this.$element
.toggleClass( 'oo-ui-labelElement', !!this.label
&& !this.invisibleLabel
);
2744 * Set whether the label should be visually hidden (but still accessible to screen-readers).
2746 * @param {boolean} invisibleLabel
2749 OO
.ui
.mixin
.LabelElement
.prototype.setInvisibleLabel = function ( invisibleLabel
) {
2750 invisibleLabel
= !!invisibleLabel
;
2752 if ( this.invisibleLabel
!== invisibleLabel
) {
2753 this.invisibleLabel
= invisibleLabel
;
2754 this.emit( 'labelChange' );
2757 this.$label
.toggleClass( 'oo-ui-labelElement-invisible', this.invisibleLabel
);
2758 // Pretend that there is no label, a lot of CSS has been written with this assumption
2759 this.$element
.toggleClass( 'oo-ui-labelElement', !!this.label
&& !this.invisibleLabel
);
2765 * Set the label as plain text with a highlighted query
2767 * @param {string} text Text label to set
2768 * @param {string} query Substring of text to highlight
2769 * @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
2772 OO
.ui
.mixin
.LabelElement
.prototype.setHighlightedQuery = function ( text
, query
, compare
) {
2773 return this.setLabel( this.constructor.static.highlightQuery( text
, query
, compare
) );
2779 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
2780 * text; or null for no label
2782 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
2787 * Set the content of the label.
2789 * Do not call this method until after the label element has been set by #setLabelElement.
2792 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
2793 * text; or null for no label
2795 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
2796 if ( typeof label
=== 'string' ) {
2797 if ( label
.match( /^\s*$/ ) ) {
2798 // Convert whitespace only string to a single non-breaking space
2799 this.$label
.html( ' ' );
2801 this.$label
.text( label
);
2803 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
2804 this.$label
.html( label
.toString() );
2805 } else if ( label
instanceof jQuery
) {
2806 this.$label
.empty().append( label
);
2808 this.$label
.empty();
2813 * IconElement is often mixed into other classes to generate an icon.
2814 * Icons are graphics, about the size of normal text. They are used to aid the user
2815 * in locating a control or to convey information in a space-efficient way. See the
2816 * [OOUI documentation on MediaWiki] [1] for a list of icons
2817 * included in the library.
2819 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
2825 * @param {Object} [config] Configuration options
2826 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2827 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2828 * the icon element be set to an existing icon instead of the one generated by this class, set a
2829 * value using a jQuery selection. For example:
2831 * // Use a <div> tag instead of a <span>
2833 * // Use an existing icon element instead of the one generated by the class
2834 * $icon: this.$element
2835 * // Use an icon element from a child widget
2836 * $icon: this.childwidget.$element
2837 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
2838 * symbolic names. A map is used for i18n purposes and contains a `default` icon
2839 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
2840 * by the user's language.
2842 * Example of an i18n map:
2844 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2845 * See the [OOUI documentation on MediaWiki] [2] for a list of icons included in the library.
2846 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
2847 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
2848 * text. The icon title is displayed when users move the mouse over the icon.
2850 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
2851 // Configuration initialization
2852 config
= config
|| {};
2857 this.iconTitle
= null;
2860 this.setIcon( config
.icon
|| this.constructor.static.icon
);
2861 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
2862 this.setIconElement( config
.$icon
|| $( '<span>' ) );
2867 OO
.initClass( OO
.ui
.mixin
.IconElement
);
2869 /* Static Properties */
2872 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
2873 * for i18n purposes and contains a `default` icon name and additional names keyed by
2874 * language code. The `default` name is used when no icon is keyed by the user's language.
2876 * Example of an i18n map:
2878 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2880 * Note: the static property will be overridden if the #icon configuration is used.
2884 * @property {Object|string}
2886 OO
.ui
.mixin
.IconElement
.static.icon
= null;
2889 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2890 * function that returns title text, or `null` for no title.
2892 * The static property will be overridden if the #iconTitle configuration is used.
2896 * @property {string|Function|null}
2898 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
2903 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2904 * applies to the specified icon element instead of the one created by the class. If an icon
2905 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2906 * and mixin methods will no longer affect the element.
2908 * @param {jQuery} $icon Element to use as icon
2910 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
2913 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
2914 .removeAttr( 'title' );
2918 .addClass( 'oo-ui-iconElement-icon' )
2919 .toggleClass( 'oo-ui-iconElement-noIcon', !this.icon
)
2920 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
2921 if ( this.iconTitle
!== null ) {
2922 this.$icon
.attr( 'title', this.iconTitle
);
2925 this.updateThemeClasses();
2929 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
2930 * The icon parameter can also be set to a map of icon names. See the #icon config setting
2933 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
2934 * by language code, or `null` to remove the icon.
2937 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
2938 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
2939 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
2941 if ( this.icon
!== icon
) {
2943 if ( this.icon
!== null ) {
2944 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
2946 if ( icon
!== null ) {
2947 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
2953 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
2955 this.$icon
.toggleClass( 'oo-ui-iconElement-noIcon', !this.icon
);
2957 this.updateThemeClasses();
2963 * Set the icon title. Use `null` to remove the title.
2965 * @param {string|Function|null} iconTitle A text string used as the icon title,
2966 * a function that returns title text, or `null` for no title.
2969 OO
.ui
.mixin
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
2971 ( typeof iconTitle
=== 'function' || ( typeof iconTitle
=== 'string' && iconTitle
.length
) ) ?
2972 OO
.ui
.resolveMsg( iconTitle
) : null;
2974 if ( this.iconTitle
!== iconTitle
) {
2975 this.iconTitle
= iconTitle
;
2977 if ( this.iconTitle
!== null ) {
2978 this.$icon
.attr( 'title', iconTitle
);
2980 this.$icon
.removeAttr( 'title' );
2989 * Get the symbolic name of the icon.
2991 * @return {string} Icon name
2993 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
2998 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
3000 * @return {string} Icon title text
3002 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
3003 return this.iconTitle
;
3007 * IndicatorElement is often mixed into other classes to generate an indicator.
3008 * Indicators are small graphics that are generally used in two ways:
3010 * - To draw attention to the status of an item. For example, an indicator might be
3011 * used to show that an item in a list has errors that need to be resolved.
3012 * - To clarify the function of a control that acts in an exceptional way (a button
3013 * that opens a menu instead of performing an action directly, for example).
3015 * For a list of indicators included in the library, please see the
3016 * [OOUI documentation on MediaWiki] [1].
3018 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3024 * @param {Object} [config] Configuration options
3025 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
3026 * configuration is omitted, the indicator element will use a generated `<span>`.
3027 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3028 * See the [OOUI documentation on MediaWiki][2] for a list of indicators included
3030 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3031 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
3032 * or a function that returns title text. The indicator title is displayed when users move
3033 * the mouse over the indicator.
3035 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
3036 // Configuration initialization
3037 config
= config
|| {};
3040 this.$indicator
= null;
3041 this.indicator
= null;
3042 this.indicatorTitle
= null;
3045 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
3046 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
3047 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
3052 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
3054 /* Static Properties */
3057 * Symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3058 * The static property will be overridden if the #indicator configuration is used.
3062 * @property {string|null}
3064 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
3067 * A text string used as the indicator title, a function that returns title text, or `null`
3068 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
3072 * @property {string|Function|null}
3074 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
3079 * Set the indicator element.
3081 * If an element is already set, it will be cleaned up before setting up the new element.
3083 * @param {jQuery} $indicator Element to use as indicator
3085 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
3086 if ( this.$indicator
) {
3088 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
3089 .removeAttr( 'title' );
3092 this.$indicator
= $indicator
3093 .addClass( 'oo-ui-indicatorElement-indicator' )
3094 .toggleClass( 'oo-ui-indicatorElement-noIndicator', !this.indicator
)
3095 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
3096 if ( this.indicatorTitle
!== null ) {
3097 this.$indicator
.attr( 'title', this.indicatorTitle
);
3100 this.updateThemeClasses();
3104 * Set the indicator by its symbolic name: ‘clear’, ‘down’, ‘required’, ‘search’, ‘up’. Use `null` to remove the indicator.
3106 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
3109 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
3110 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
3112 if ( this.indicator
!== indicator
) {
3113 if ( this.$indicator
) {
3114 if ( this.indicator
!== null ) {
3115 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
3117 if ( indicator
!== null ) {
3118 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
3121 this.indicator
= indicator
;
3124 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
3125 if ( this.$indicator
) {
3126 this.$indicator
.toggleClass( 'oo-ui-indicatorElement-noIndicator', !this.indicator
);
3128 this.updateThemeClasses();
3134 * Set the indicator title.
3136 * The title is displayed when a user moves the mouse over the indicator.
3138 * @param {string|Function|null} indicatorTitle Indicator title text, a function that returns text, or
3139 * `null` for no indicator title
3142 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
3144 ( typeof indicatorTitle
=== 'function' || ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ) ?
3145 OO
.ui
.resolveMsg( indicatorTitle
) : null;
3147 if ( this.indicatorTitle
!== indicatorTitle
) {
3148 this.indicatorTitle
= indicatorTitle
;
3149 if ( this.$indicator
) {
3150 if ( this.indicatorTitle
!== null ) {
3151 this.$indicator
.attr( 'title', indicatorTitle
);
3153 this.$indicator
.removeAttr( 'title' );
3162 * Get the symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3164 * @return {string} Symbolic name of indicator
3166 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
3167 return this.indicator
;
3171 * Get the indicator title.
3173 * The title is displayed when a user moves the mouse over the indicator.
3175 * @return {string} Indicator title text
3177 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
3178 return this.indicatorTitle
;
3182 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
3183 * additional functionality to an element created by another class. The class provides
3184 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
3185 * which are used to customize the look and feel of a widget to better describe its
3186 * importance and functionality.
3188 * The library currently contains the following styling flags for general use:
3190 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
3191 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
3193 * The flags affect the appearance of the buttons:
3196 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
3197 * var button1 = new OO.ui.ButtonWidget( {
3198 * label: 'Progressive',
3199 * flags: 'progressive'
3201 * var button2 = new OO.ui.ButtonWidget( {
3202 * label: 'Destructive',
3203 * flags: 'destructive'
3205 * $( 'body' ).append( button1.$element, button2.$element );
3207 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
3208 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
3210 * [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
3216 * @param {Object} [config] Configuration options
3217 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'progressive' or 'primary') to apply.
3218 * Please see the [OOUI documentation on MediaWiki] [2] for more information about available flags.
3219 * [2]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
3220 * @cfg {jQuery} [$flagged] The flagged element. By default,
3221 * the flagged functionality is applied to the element created by the class ($element).
3222 * If a different element is specified, the flagged functionality will be applied to it instead.
3224 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
3225 // Configuration initialization
3226 config
= config
|| {};
3230 this.$flagged
= null;
3233 this.setFlags( config
.flags
);
3234 this.setFlaggedElement( config
.$flagged
|| this.$element
);
3241 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
3242 * parameter contains the name of each modified flag and indicates whether it was
3245 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
3246 * that the flag was added, `false` that the flag was removed.
3252 * Set the flagged element.
3254 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
3255 * If an element is already set, the method will remove the mixin’s effect on that element.
3257 * @param {jQuery} $flagged Element that should be flagged
3259 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
3260 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
3261 return 'oo-ui-flaggedElement-' + flag
;
3264 if ( this.$flagged
) {
3265 this.$flagged
.removeClass( classNames
);
3268 this.$flagged
= $flagged
.addClass( classNames
);
3272 * Check if the specified flag is set.
3274 * @param {string} flag Name of flag
3275 * @return {boolean} The flag is set
3277 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
3278 // This may be called before the constructor, thus before this.flags is set
3279 return this.flags
&& ( flag
in this.flags
);
3283 * Get the names of all flags set.
3285 * @return {string[]} Flag names
3287 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
3288 // This may be called before the constructor, thus before this.flags is set
3289 return Object
.keys( this.flags
|| {} );
3298 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
3299 var flag
, className
,
3302 classPrefix
= 'oo-ui-flaggedElement-';
3304 for ( flag
in this.flags
) {
3305 className
= classPrefix
+ flag
;
3306 changes
[ flag
] = false;
3307 delete this.flags
[ flag
];
3308 remove
.push( className
);
3311 if ( this.$flagged
) {
3312 this.$flagged
.removeClass( remove
);
3315 this.updateThemeClasses();
3316 this.emit( 'flag', changes
);
3322 * Add one or more flags.
3324 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
3325 * or an object keyed by flag name with a boolean value that indicates whether the flag should
3326 * be added (`true`) or removed (`false`).
3330 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
3331 var i
, len
, flag
, className
,
3335 classPrefix
= 'oo-ui-flaggedElement-';
3337 if ( typeof flags
=== 'string' ) {
3338 className
= classPrefix
+ flags
;
3340 if ( !this.flags
[ flags
] ) {
3341 this.flags
[ flags
] = true;
3342 add
.push( className
);
3344 } else if ( Array
.isArray( flags
) ) {
3345 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
3347 className
= classPrefix
+ flag
;
3349 if ( !this.flags
[ flag
] ) {
3350 changes
[ flag
] = true;
3351 this.flags
[ flag
] = true;
3352 add
.push( className
);
3355 } else if ( OO
.isPlainObject( flags
) ) {
3356 for ( flag
in flags
) {
3357 className
= classPrefix
+ flag
;
3358 if ( flags
[ flag
] ) {
3360 if ( !this.flags
[ flag
] ) {
3361 changes
[ flag
] = true;
3362 this.flags
[ flag
] = true;
3363 add
.push( className
);
3367 if ( this.flags
[ flag
] ) {
3368 changes
[ flag
] = false;
3369 delete this.flags
[ flag
];
3370 remove
.push( className
);
3376 if ( this.$flagged
) {
3379 .removeClass( remove
);
3382 this.updateThemeClasses();
3383 this.emit( 'flag', changes
);
3389 * TitledElement is mixed into other classes to provide a `title` attribute.
3390 * Titles are rendered by the browser and are made visible when the user moves
3391 * the mouse over the element. Titles are not visible on touch devices.
3394 * // TitledElement provides a 'title' attribute to the
3395 * // ButtonWidget class
3396 * var button = new OO.ui.ButtonWidget( {
3397 * label: 'Button with Title',
3398 * title: 'I am a button'
3400 * $( 'body' ).append( button.$element );
3406 * @param {Object} [config] Configuration options
3407 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
3408 * If this config is omitted, the title functionality is applied to $element, the
3409 * element created by the class.
3410 * @cfg {string|Function} [title] The title text or a function that returns text. If
3411 * this config is omitted, the value of the {@link #static-title static title} property is used.
3413 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
3414 // Configuration initialization
3415 config
= config
|| {};
3418 this.$titled
= null;
3422 this.setTitle( config
.title
!== undefined ? config
.title
: this.constructor.static.title
);
3423 this.setTitledElement( config
.$titled
|| this.$element
);
3428 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
3430 /* Static Properties */
3433 * The title text, a function that returns text, or `null` for no title. The value of the static property
3434 * is overridden if the #title config option is used.
3438 * @property {string|Function|null}
3440 OO
.ui
.mixin
.TitledElement
.static.title
= null;
3445 * Set the titled element.
3447 * This method is used to retarget a TitledElement mixin so that its functionality applies to the specified element.
3448 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
3450 * @param {jQuery} $titled Element that should use the 'titled' functionality
3452 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
3453 if ( this.$titled
) {
3454 this.$titled
.removeAttr( 'title' );
3457 this.$titled
= $titled
;
3466 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
3469 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
3470 title
= typeof title
=== 'function' ? OO
.ui
.resolveMsg( title
) : title
;
3471 title
= ( typeof title
=== 'string' && title
.length
) ? title
: null;
3473 if ( this.title
!== title
) {
3482 * Update the title attribute, in case of changes to title or accessKey.
3487 OO
.ui
.mixin
.TitledElement
.prototype.updateTitle = function () {
3488 var title
= this.getTitle();
3489 if ( this.$titled
) {
3490 if ( title
!== null ) {
3491 // Only if this is an AccessKeyedElement
3492 if ( this.formatTitleWithAccessKey
) {
3493 title
= this.formatTitleWithAccessKey( title
);
3495 this.$titled
.attr( 'title', title
);
3497 this.$titled
.removeAttr( 'title' );
3506 * @return {string} Title string
3508 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
3513 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
3514 * Accesskeys allow an user to go to a specific element by using
3515 * a shortcut combination of a browser specific keys + the key
3519 * // AccessKeyedElement provides an 'accesskey' attribute to the
3520 * // ButtonWidget class
3521 * var button = new OO.ui.ButtonWidget( {
3522 * label: 'Button with Accesskey',
3525 * $( 'body' ).append( button.$element );
3531 * @param {Object} [config] Configuration options
3532 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3533 * If this config is omitted, the accesskey functionality is applied to $element, the
3534 * element created by the class.
3535 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3536 * this config is omitted, no accesskey will be added.
3538 OO
.ui
.mixin
.AccessKeyedElement
= function OoUiMixinAccessKeyedElement( config
) {
3539 // Configuration initialization
3540 config
= config
|| {};
3543 this.$accessKeyed
= null;
3544 this.accessKey
= null;
3547 this.setAccessKey( config
.accessKey
|| null );
3548 this.setAccessKeyedElement( config
.$accessKeyed
|| this.$element
);
3550 // If this is also a TitledElement and it initialized before we did, we may have
3551 // to update the title with the access key
3552 if ( this.updateTitle
) {
3559 OO
.initClass( OO
.ui
.mixin
.AccessKeyedElement
);
3561 /* Static Properties */
3564 * The access key, a function that returns a key, or `null` for no accesskey.
3568 * @property {string|Function|null}
3570 OO
.ui
.mixin
.AccessKeyedElement
.static.accessKey
= null;
3575 * Set the accesskeyed element.
3577 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
3578 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
3580 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyed' functionality
3582 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKeyedElement = function ( $accessKeyed
) {
3583 if ( this.$accessKeyed
) {
3584 this.$accessKeyed
.removeAttr( 'accesskey' );
3587 this.$accessKeyed
= $accessKeyed
;
3588 if ( this.accessKey
) {
3589 this.$accessKeyed
.attr( 'accesskey', this.accessKey
);
3596 * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no accesskey
3599 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKey = function ( accessKey
) {
3600 accessKey
= typeof accessKey
=== 'string' ? OO
.ui
.resolveMsg( accessKey
) : null;
3602 if ( this.accessKey
!== accessKey
) {
3603 if ( this.$accessKeyed
) {
3604 if ( accessKey
!== null ) {
3605 this.$accessKeyed
.attr( 'accesskey', accessKey
);
3607 this.$accessKeyed
.removeAttr( 'accesskey' );
3610 this.accessKey
= accessKey
;
3612 // Only if this is a TitledElement
3613 if ( this.updateTitle
) {
3624 * @return {string} accessKey string
3626 OO
.ui
.mixin
.AccessKeyedElement
.prototype.getAccessKey = function () {
3627 return this.accessKey
;
3631 * Add information about the access key to the element's tooltip label.
3632 * (This is only public for hacky usage in FieldLayout.)
3634 * @param {string} title Tooltip label for `title` attribute
3637 OO
.ui
.mixin
.AccessKeyedElement
.prototype.formatTitleWithAccessKey = function ( title
) {
3640 if ( !this.$accessKeyed
) {
3641 // Not initialized yet; the constructor will call updateTitle() which will rerun this function
3644 // Use jquery.accessKeyLabel if available to show modifiers, otherwise just display the single key
3645 if ( $.fn
.updateTooltipAccessKeys
&& $.fn
.updateTooltipAccessKeys
.getAccessKeyLabel
) {
3646 accessKey
= $.fn
.updateTooltipAccessKeys
.getAccessKeyLabel( this.$accessKeyed
[ 0 ] );
3648 accessKey
= this.getAccessKey();
3651 title
+= ' [' + accessKey
+ ']';
3657 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3658 * feels, and functionality can be customized via the class’s configuration options
3659 * and methods. Please see the [OOUI documentation on MediaWiki] [1] for more information
3662 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches
3665 * // A button widget
3666 * var button = new OO.ui.ButtonWidget( {
3667 * label: 'Button with Icon',
3671 * $( 'body' ).append( button.$element );
3673 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3676 * @extends OO.ui.Widget
3677 * @mixins OO.ui.mixin.ButtonElement
3678 * @mixins OO.ui.mixin.IconElement
3679 * @mixins OO.ui.mixin.IndicatorElement
3680 * @mixins OO.ui.mixin.LabelElement
3681 * @mixins OO.ui.mixin.TitledElement
3682 * @mixins OO.ui.mixin.FlaggedElement
3683 * @mixins OO.ui.mixin.TabIndexedElement
3684 * @mixins OO.ui.mixin.AccessKeyedElement
3687 * @param {Object} [config] Configuration options
3688 * @cfg {boolean} [active=false] Whether button should be shown as active
3689 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3690 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3691 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3693 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
3694 // Configuration initialization
3695 config
= config
|| {};
3697 // Parent constructor
3698 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
3700 // Mixin constructors
3701 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
3702 OO
.ui
.mixin
.IconElement
.call( this, config
);
3703 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
3704 OO
.ui
.mixin
.LabelElement
.call( this, config
);
3705 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
3706 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
3707 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
3708 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$button
} ) );
3713 this.noFollow
= false;
3716 this.connect( this, { disable
: 'onDisable' } );
3719 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
3721 .addClass( 'oo-ui-buttonWidget' )
3722 .append( this.$button
);
3723 this.setActive( config
.active
);
3724 this.setHref( config
.href
);
3725 this.setTarget( config
.target
);
3726 this.setNoFollow( config
.noFollow
);
3731 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
3732 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
3733 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
3734 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
3735 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
3736 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
3737 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
3738 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
3739 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
3741 /* Static Properties */
3747 OO
.ui
.ButtonWidget
.static.cancelButtonMouseDownEvents
= false;
3753 OO
.ui
.ButtonWidget
.static.tagName
= 'span';
3758 * Get hyperlink location.
3760 * @return {string} Hyperlink location
3762 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
3767 * Get hyperlink target.
3769 * @return {string} Hyperlink target
3771 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
3776 * Get search engine traversal hint.
3778 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3780 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
3781 return this.noFollow
;
3785 * Set hyperlink location.
3787 * @param {string|null} href Hyperlink location, null to remove
3789 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
3790 href
= typeof href
=== 'string' ? href
: null;
3791 if ( href
!== null && !OO
.ui
.isSafeUrl( href
) ) {
3795 if ( href
!== this.href
) {
3804 * Update the `href` attribute, in case of changes to href or
3810 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
3811 if ( this.href
!== null && !this.isDisabled() ) {
3812 this.$button
.attr( 'href', this.href
);
3814 this.$button
.removeAttr( 'href' );
3821 * Handle disable events.
3824 * @param {boolean} disabled Element is disabled
3826 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
3831 * Set hyperlink target.
3833 * @param {string|null} target Hyperlink target, null to remove
3835 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
3836 target
= typeof target
=== 'string' ? target
: null;
3838 if ( target
!== this.target
) {
3839 this.target
= target
;
3840 if ( target
!== null ) {
3841 this.$button
.attr( 'target', target
);
3843 this.$button
.removeAttr( 'target' );
3851 * Set search engine traversal hint.
3853 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3855 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
3856 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
3858 if ( noFollow
!== this.noFollow
) {
3859 this.noFollow
= noFollow
;
3861 this.$button
.attr( 'rel', 'nofollow' );
3863 this.$button
.removeAttr( 'rel' );
3870 // Override method visibility hints from ButtonElement
3881 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3882 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3883 * removed, and cleared from the group.
3886 * // Example: A ButtonGroupWidget with two buttons
3887 * var button1 = new OO.ui.PopupButtonWidget( {
3888 * label: 'Select a category',
3891 * $content: $( '<p>List of categories...</p>' ),
3896 * var button2 = new OO.ui.ButtonWidget( {
3899 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
3900 * items: [button1, button2]
3902 * $( 'body' ).append( buttonGroup.$element );
3905 * @extends OO.ui.Widget
3906 * @mixins OO.ui.mixin.GroupElement
3909 * @param {Object} [config] Configuration options
3910 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
3912 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
3913 // Configuration initialization
3914 config
= config
|| {};
3916 // Parent constructor
3917 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
3919 // Mixin constructors
3920 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
3923 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
3924 if ( Array
.isArray( config
.items
) ) {
3925 this.addItems( config
.items
);
3931 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
3932 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
3934 /* Static Properties */
3940 OO
.ui
.ButtonGroupWidget
.static.tagName
= 'span';
3949 OO
.ui
.ButtonGroupWidget
.prototype.focus = function () {
3950 if ( !this.isDisabled() ) {
3951 if ( this.items
[ 0 ] ) {
3952 this.items
[ 0 ].focus();
3961 OO
.ui
.ButtonGroupWidget
.prototype.simulateLabelClick = function () {
3966 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
3967 * which creates a label that identifies the icon’s function. See the [OOUI documentation on MediaWiki] [1]
3968 * for a list of icons included in the library.
3971 * // An icon widget with a label
3972 * var myIcon = new OO.ui.IconWidget( {
3976 * // Create a label.
3977 * var iconLabel = new OO.ui.LabelWidget( {
3980 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
3982 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
3985 * @extends OO.ui.Widget
3986 * @mixins OO.ui.mixin.IconElement
3987 * @mixins OO.ui.mixin.TitledElement
3988 * @mixins OO.ui.mixin.LabelElement
3989 * @mixins OO.ui.mixin.FlaggedElement
3992 * @param {Object} [config] Configuration options
3994 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
3995 // Configuration initialization
3996 config
= config
|| {};
3998 // Parent constructor
3999 OO
.ui
.IconWidget
.parent
.call( this, config
);
4001 // Mixin constructors
4002 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
4003 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
4004 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
, invisibleLabel
: true } ) );
4005 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
4008 this.$element
.addClass( 'oo-ui-iconWidget' );
4009 // Remove class added by LabelElement initialization. It causes unexpected CSS to apply when
4010 // nested in other widgets, because this widget used to not mix in LabelElement.
4011 this.$element
.removeClass( 'oo-ui-labelElement-label' );
4016 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
4017 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
4018 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
4019 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.LabelElement
);
4020 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
4022 /* Static Properties */
4028 OO
.ui
.IconWidget
.static.tagName
= 'span';
4031 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
4032 * attention to the status of an item or to clarify the function within a control. For a list of
4033 * indicators included in the library, please see the [OOUI documentation on MediaWiki][1].
4036 * // Example of an indicator widget
4037 * var indicator1 = new OO.ui.IndicatorWidget( {
4038 * indicator: 'required'
4041 * // Create a fieldset layout to add a label
4042 * var fieldset = new OO.ui.FieldsetLayout();
4043 * fieldset.addItems( [
4044 * new OO.ui.FieldLayout( indicator1, { label: 'A required indicator:' } )
4046 * $( 'body' ).append( fieldset.$element );
4048 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
4051 * @extends OO.ui.Widget
4052 * @mixins OO.ui.mixin.IndicatorElement
4053 * @mixins OO.ui.mixin.TitledElement
4054 * @mixins OO.ui.mixin.LabelElement
4057 * @param {Object} [config] Configuration options
4059 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
4060 // Configuration initialization
4061 config
= config
|| {};
4063 // Parent constructor
4064 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
4066 // Mixin constructors
4067 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
4068 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
4069 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
, invisibleLabel
: true } ) );
4072 this.$element
.addClass( 'oo-ui-indicatorWidget' );
4073 // Remove class added by LabelElement initialization. It causes unexpected CSS to apply when
4074 // nested in other widgets, because this widget used to not mix in LabelElement.
4075 this.$element
.removeClass( 'oo-ui-labelElement-label' );
4080 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
4081 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
4082 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
4083 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.LabelElement
);
4085 /* Static Properties */
4091 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
4094 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
4095 * be configured with a `label` option that is set to a string, a label node, or a function:
4097 * - String: a plaintext string
4098 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
4099 * label that includes a link or special styling, such as a gray color or additional graphical elements.
4100 * - Function: a function that will produce a string in the future. Functions are used
4101 * in cases where the value of the label is not currently defined.
4103 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
4104 * will come into focus when the label is clicked.
4107 * // Examples of LabelWidgets
4108 * var label1 = new OO.ui.LabelWidget( {
4109 * label: 'plaintext label'
4111 * var label2 = new OO.ui.LabelWidget( {
4112 * label: $( '<a href="default.html">jQuery label</a>' )
4114 * // Create a fieldset layout with fields for each example
4115 * var fieldset = new OO.ui.FieldsetLayout();
4116 * fieldset.addItems( [
4117 * new OO.ui.FieldLayout( label1 ),
4118 * new OO.ui.FieldLayout( label2 )
4120 * $( 'body' ).append( fieldset.$element );
4123 * @extends OO.ui.Widget
4124 * @mixins OO.ui.mixin.LabelElement
4125 * @mixins OO.ui.mixin.TitledElement
4128 * @param {Object} [config] Configuration options
4129 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
4130 * Clicking the label will focus the specified input field.
4132 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
4133 // Configuration initialization
4134 config
= config
|| {};
4136 // Parent constructor
4137 OO
.ui
.LabelWidget
.parent
.call( this, config
);
4139 // Mixin constructors
4140 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
4141 OO
.ui
.mixin
.TitledElement
.call( this, config
);
4144 this.input
= config
.input
;
4148 if ( this.input
.getInputId() ) {
4149 this.$element
.attr( 'for', this.input
.getInputId() );
4151 this.$label
.on( 'click', function () {
4152 this.input
.simulateLabelClick();
4156 this.$element
.addClass( 'oo-ui-labelWidget' );
4161 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
4162 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
4163 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
4165 /* Static Properties */
4171 OO
.ui
.LabelWidget
.static.tagName
= 'label';
4174 * PendingElement is a mixin that is used to create elements that notify users that something is happening
4175 * and that they should wait before proceeding. The pending state is visually represented with a pending
4176 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
4177 * field of a {@link OO.ui.TextInputWidget text input widget}.
4179 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
4180 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
4181 * in process dialogs.
4184 * function MessageDialog( config ) {
4185 * MessageDialog.parent.call( this, config );
4187 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
4189 * MessageDialog.static.name = 'myMessageDialog';
4190 * MessageDialog.static.actions = [
4191 * { action: 'save', label: 'Done', flags: 'primary' },
4192 * { label: 'Cancel', flags: 'safe' }
4195 * MessageDialog.prototype.initialize = function () {
4196 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
4197 * this.content = new OO.ui.PanelLayout( { padded: true } );
4198 * 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>' );
4199 * this.$body.append( this.content.$element );
4201 * MessageDialog.prototype.getBodyHeight = function () {
4204 * MessageDialog.prototype.getActionProcess = function ( action ) {
4205 * var dialog = this;
4206 * if ( action === 'save' ) {
4207 * dialog.getActions().get({actions: 'save'})[0].pushPending();
4208 * return new OO.ui.Process()
4210 * .next( function () {
4211 * dialog.getActions().get({actions: 'save'})[0].popPending();
4214 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
4217 * var windowManager = new OO.ui.WindowManager();
4218 * $( 'body' ).append( windowManager.$element );
4220 * var dialog = new MessageDialog();
4221 * windowManager.addWindows( [ dialog ] );
4222 * windowManager.openWindow( dialog );
4228 * @param {Object} [config] Configuration options
4229 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
4231 OO
.ui
.mixin
.PendingElement
= function OoUiMixinPendingElement( config
) {
4232 // Configuration initialization
4233 config
= config
|| {};
4237 this.$pending
= null;
4240 this.setPendingElement( config
.$pending
|| this.$element
);
4245 OO
.initClass( OO
.ui
.mixin
.PendingElement
);
4250 * Set the pending element (and clean up any existing one).
4252 * @param {jQuery} $pending The element to set to pending.
4254 OO
.ui
.mixin
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
4255 if ( this.$pending
) {
4256 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
4259 this.$pending
= $pending
;
4260 if ( this.pending
> 0 ) {
4261 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
4266 * Check if an element is pending.
4268 * @return {boolean} Element is pending
4270 OO
.ui
.mixin
.PendingElement
.prototype.isPending = function () {
4271 return !!this.pending
;
4275 * Increase the pending counter. The pending state will remain active until the counter is zero
4276 * (i.e., the number of calls to #pushPending and #popPending is the same).
4280 OO
.ui
.mixin
.PendingElement
.prototype.pushPending = function () {
4281 if ( this.pending
=== 0 ) {
4282 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
4283 this.updateThemeClasses();
4291 * Decrease the pending counter. The pending state will remain active until the counter is zero
4292 * (i.e., the number of calls to #pushPending and #popPending is the same).
4296 OO
.ui
.mixin
.PendingElement
.prototype.popPending = function () {
4297 if ( this.pending
=== 1 ) {
4298 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
4299 this.updateThemeClasses();
4301 this.pending
= Math
.max( 0, this.pending
- 1 );
4307 * Element that will stick adjacent to a specified container, even when it is inserted elsewhere
4308 * in the document (for example, in an OO.ui.Window's $overlay).
4310 * The elements's position is automatically calculated and maintained when window is resized or the
4311 * page is scrolled. If you reposition the container manually, you have to call #position to make
4312 * sure the element is still placed correctly.
4314 * As positioning is only possible when both the element and the container are attached to the DOM
4315 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
4316 * the #toggle method to display a floating popup, for example.
4322 * @param {Object} [config] Configuration options
4323 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
4324 * @cfg {jQuery} [$floatableContainer] Node to position adjacent to
4325 * @cfg {string} [verticalPosition='below'] Where to position $floatable vertically:
4326 * 'below': Directly below $floatableContainer, aligning f's top edge with fC's bottom edge
4327 * 'above': Directly above $floatableContainer, aligning f's bottom edge with fC's top edge
4328 * 'top': Align the top edge with $floatableContainer's top edge
4329 * 'bottom': Align the bottom edge with $floatableContainer's bottom edge
4330 * 'center': Vertically align the center with $floatableContainer's center
4331 * @cfg {string} [horizontalPosition='start'] Where to position $floatable horizontally:
4332 * 'before': Directly before $floatableContainer, aligning f's end edge with fC's start edge
4333 * 'after': Directly after $floatableContainer, aligning f's start edge with fC's end edge
4334 * 'start': Align the start (left in LTR, right in RTL) edge with $floatableContainer's start edge
4335 * 'end': Align the end (right in LTR, left in RTL) edge with $floatableContainer's end edge
4336 * 'center': Horizontally align the center with $floatableContainer's center
4337 * @cfg {boolean} [hideWhenOutOfView=true] Whether to hide the floatable element if the container
4340 OO
.ui
.mixin
.FloatableElement
= function OoUiMixinFloatableElement( config
) {
4341 // Configuration initialization
4342 config
= config
|| {};
4345 this.$floatable
= null;
4346 this.$floatableContainer
= null;
4347 this.$floatableWindow
= null;
4348 this.$floatableClosestScrollable
= null;
4349 this.floatableOutOfView
= false;
4350 this.onFloatableScrollHandler
= this.position
.bind( this );
4351 this.onFloatableWindowResizeHandler
= this.position
.bind( this );
4354 this.setFloatableContainer( config
.$floatableContainer
);
4355 this.setFloatableElement( config
.$floatable
|| this.$element
);
4356 this.setVerticalPosition( config
.verticalPosition
|| 'below' );
4357 this.setHorizontalPosition( config
.horizontalPosition
|| 'start' );
4358 this.hideWhenOutOfView
= config
.hideWhenOutOfView
=== undefined ? true : !!config
.hideWhenOutOfView
;
4364 * Set floatable element.
4366 * If an element is already set, it will be cleaned up before setting up the new element.
4368 * @param {jQuery} $floatable Element to make floatable
4370 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableElement = function ( $floatable
) {
4371 if ( this.$floatable
) {
4372 this.$floatable
.removeClass( 'oo-ui-floatableElement-floatable' );
4373 this.$floatable
.css( { left
: '', top
: '' } );
4376 this.$floatable
= $floatable
.addClass( 'oo-ui-floatableElement-floatable' );
4381 * Set floatable container.
4383 * The element will be positioned relative to the specified container.
4385 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
4387 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableContainer = function ( $floatableContainer
) {
4388 this.$floatableContainer
= $floatableContainer
;
4389 if ( this.$floatable
) {
4395 * Change how the element is positioned vertically.
4397 * @param {string} position 'below', 'above', 'top', 'bottom' or 'center'
4399 OO
.ui
.mixin
.FloatableElement
.prototype.setVerticalPosition = function ( position
) {
4400 if ( [ 'below', 'above', 'top', 'bottom', 'center' ].indexOf( position
) === -1 ) {
4401 throw new Error( 'Invalid value for vertical position: ' + position
);
4403 if ( this.verticalPosition
!== position
) {
4404 this.verticalPosition
= position
;
4405 if ( this.$floatable
) {
4412 * Change how the element is positioned horizontally.
4414 * @param {string} position 'before', 'after', 'start', 'end' or 'center'
4416 OO
.ui
.mixin
.FloatableElement
.prototype.setHorizontalPosition = function ( position
) {
4417 if ( [ 'before', 'after', 'start', 'end', 'center' ].indexOf( position
) === -1 ) {
4418 throw new Error( 'Invalid value for horizontal position: ' + position
);
4420 if ( this.horizontalPosition
!== position
) {
4421 this.horizontalPosition
= position
;
4422 if ( this.$floatable
) {
4429 * Toggle positioning.
4431 * Do not turn positioning on until after the element is attached to the DOM and visible.
4433 * @param {boolean} [positioning] Enable positioning, omit to toggle
4436 OO
.ui
.mixin
.FloatableElement
.prototype.togglePositioning = function ( positioning
) {
4437 var closestScrollableOfContainer
;
4439 if ( !this.$floatable
|| !this.$floatableContainer
) {
4443 positioning
= positioning
=== undefined ? !this.positioning
: !!positioning
;
4445 if ( positioning
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4446 OO
.ui
.warnDeprecation( 'FloatableElement#togglePositioning: Before calling this method, the element must be attached to the DOM.' );
4447 this.warnedUnattached
= true;
4450 if ( this.positioning
!== positioning
) {
4451 this.positioning
= positioning
;
4453 this.needsCustomPosition
=
4454 this.verticalPosition
!== 'below' ||
4455 this.horizontalPosition
!== 'start' ||
4456 !OO
.ui
.contains( this.$floatableContainer
[ 0 ], this.$floatable
[ 0 ] );
4458 closestScrollableOfContainer
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatableContainer
[ 0 ] );
4459 // If the scrollable is the root, we have to listen to scroll events
4460 // on the window because of browser inconsistencies.
4461 if ( $( closestScrollableOfContainer
).is( 'html, body' ) ) {
4462 closestScrollableOfContainer
= OO
.ui
.Element
.static.getWindow( closestScrollableOfContainer
);
4465 if ( positioning
) {
4466 this.$floatableWindow
= $( this.getElementWindow() );
4467 this.$floatableWindow
.on( 'resize', this.onFloatableWindowResizeHandler
);
4469 this.$floatableClosestScrollable
= $( closestScrollableOfContainer
);
4470 this.$floatableClosestScrollable
.on( 'scroll', this.onFloatableScrollHandler
);
4472 // Initial position after visible
4475 if ( this.$floatableWindow
) {
4476 this.$floatableWindow
.off( 'resize', this.onFloatableWindowResizeHandler
);
4477 this.$floatableWindow
= null;
4480 if ( this.$floatableClosestScrollable
) {
4481 this.$floatableClosestScrollable
.off( 'scroll', this.onFloatableScrollHandler
);
4482 this.$floatableClosestScrollable
= null;
4485 this.$floatable
.css( { left
: '', right
: '', top
: '' } );
4493 * Check whether the bottom edge of the given element is within the viewport of the given container.
4496 * @param {jQuery} $element
4497 * @param {jQuery} $container
4500 OO
.ui
.mixin
.FloatableElement
.prototype.isElementInViewport = function ( $element
, $container
) {
4501 var elemRect
, contRect
, topEdgeInBounds
, bottomEdgeInBounds
, leftEdgeInBounds
, rightEdgeInBounds
,
4502 startEdgeInBounds
, endEdgeInBounds
, viewportSpacing
,
4503 direction
= $element
.css( 'direction' );
4505 elemRect
= $element
[ 0 ].getBoundingClientRect();
4506 if ( $container
[ 0 ] === window
) {
4507 viewportSpacing
= OO
.ui
.getViewportSpacing();
4511 right
: document
.documentElement
.clientWidth
,
4512 bottom
: document
.documentElement
.clientHeight
4514 contRect
.top
+= viewportSpacing
.top
;
4515 contRect
.left
+= viewportSpacing
.left
;
4516 contRect
.right
-= viewportSpacing
.right
;
4517 contRect
.bottom
-= viewportSpacing
.bottom
;
4519 contRect
= $container
[ 0 ].getBoundingClientRect();
4522 topEdgeInBounds
= elemRect
.top
>= contRect
.top
&& elemRect
.top
<= contRect
.bottom
;
4523 bottomEdgeInBounds
= elemRect
.bottom
>= contRect
.top
&& elemRect
.bottom
<= contRect
.bottom
;
4524 leftEdgeInBounds
= elemRect
.left
>= contRect
.left
&& elemRect
.left
<= contRect
.right
;
4525 rightEdgeInBounds
= elemRect
.right
>= contRect
.left
&& elemRect
.right
<= contRect
.right
;
4526 if ( direction
=== 'rtl' ) {
4527 startEdgeInBounds
= rightEdgeInBounds
;
4528 endEdgeInBounds
= leftEdgeInBounds
;
4530 startEdgeInBounds
= leftEdgeInBounds
;
4531 endEdgeInBounds
= rightEdgeInBounds
;
4534 if ( this.verticalPosition
=== 'below' && !bottomEdgeInBounds
) {
4537 if ( this.verticalPosition
=== 'above' && !topEdgeInBounds
) {
4540 if ( this.horizontalPosition
=== 'before' && !startEdgeInBounds
) {
4543 if ( this.horizontalPosition
=== 'after' && !endEdgeInBounds
) {
4547 // The other positioning values are all about being inside the container,
4548 // so in those cases all we care about is that any part of the container is visible.
4549 return elemRect
.top
<= contRect
.bottom
&& elemRect
.bottom
>= contRect
.top
&&
4550 elemRect
.left
<= contRect
.right
&& elemRect
.right
>= contRect
.left
;
4554 * Check if the floatable is hidden to the user because it was offscreen.
4556 * @return {boolean} Floatable is out of view
4558 OO
.ui
.mixin
.FloatableElement
.prototype.isFloatableOutOfView = function () {
4559 return this.floatableOutOfView
;
4563 * Position the floatable below its container.
4565 * This should only be done when both of them are attached to the DOM and visible.
4569 OO
.ui
.mixin
.FloatableElement
.prototype.position = function () {
4570 if ( !this.positioning
) {
4575 // To continue, some things need to be true:
4576 // The element must actually be in the DOM
4577 this.isElementAttached() && (
4578 // The closest scrollable is the current window
4579 this.$floatableClosestScrollable
[ 0 ] === this.getElementWindow() ||
4580 // OR is an element in the element's DOM
4581 $.contains( this.getElementDocument(), this.$floatableClosestScrollable
[ 0 ] )
4584 // Abort early if important parts of the widget are no longer attached to the DOM
4588 this.floatableOutOfView
= this.hideWhenOutOfView
&& !this.isElementInViewport( this.$floatableContainer
, this.$floatableClosestScrollable
);
4589 if ( this.floatableOutOfView
) {
4590 this.$floatable
.addClass( 'oo-ui-element-hidden' );
4593 this.$floatable
.removeClass( 'oo-ui-element-hidden' );
4596 if ( !this.needsCustomPosition
) {
4600 this.$floatable
.css( this.computePosition() );
4602 // We updated the position, so re-evaluate the clipping state.
4603 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
4604 // will not notice the need to update itself.)
4605 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
4606 // it not listen to the right events in the right places?
4615 * Compute how #$floatable should be positioned based on the position of #$floatableContainer
4616 * and the positioning settings. This is a helper for #position that shouldn't be called directly,
4617 * but may be overridden by subclasses if they want to change or add to the positioning logic.
4619 * @return {Object} New position to apply with .css(). Keys are 'top', 'left', 'bottom' and 'right'.
4621 OO
.ui
.mixin
.FloatableElement
.prototype.computePosition = function () {
4622 var isBody
, scrollableX
, scrollableY
, containerPos
,
4623 horizScrollbarHeight
, vertScrollbarWidth
, scrollTop
, scrollLeft
,
4624 newPos
= { top
: '', left
: '', bottom
: '', right
: '' },
4625 direction
= this.$floatableContainer
.css( 'direction' ),
4626 $offsetParent
= this.$floatable
.offsetParent();
4628 if ( $offsetParent
.is( 'html' ) ) {
4629 // The innerHeight/Width and clientHeight/Width calculations don't work well on the
4630 // <html> element, but they do work on the <body>
4631 $offsetParent
= $( $offsetParent
[ 0 ].ownerDocument
.body
);
4633 isBody
= $offsetParent
.is( 'body' );
4634 scrollableX
= $offsetParent
.css( 'overflow-x' ) === 'scroll' || $offsetParent
.css( 'overflow-x' ) === 'auto';
4635 scrollableY
= $offsetParent
.css( 'overflow-y' ) === 'scroll' || $offsetParent
.css( 'overflow-y' ) === 'auto';
4637 vertScrollbarWidth
= $offsetParent
.innerWidth() - $offsetParent
.prop( 'clientWidth' );
4638 horizScrollbarHeight
= $offsetParent
.innerHeight() - $offsetParent
.prop( 'clientHeight' );
4639 // We don't need to compute and add scrollTop and scrollLeft if the scrollable container is the body,
4640 // or if it isn't scrollable
4641 scrollTop
= scrollableY
&& !isBody
? $offsetParent
.scrollTop() : 0;
4642 scrollLeft
= scrollableX
&& !isBody
? OO
.ui
.Element
.static.getScrollLeft( $offsetParent
[ 0 ] ) : 0;
4644 // Avoid passing the <body> to getRelativePosition(), because it won't return what we expect
4645 // if the <body> has a margin
4646 containerPos
= isBody
?
4647 this.$floatableContainer
.offset() :
4648 OO
.ui
.Element
.static.getRelativePosition( this.$floatableContainer
, $offsetParent
);
4649 containerPos
.bottom
= containerPos
.top
+ this.$floatableContainer
.outerHeight();
4650 containerPos
.right
= containerPos
.left
+ this.$floatableContainer
.outerWidth();
4651 containerPos
.start
= direction
=== 'rtl' ? containerPos
.right
: containerPos
.left
;
4652 containerPos
.end
= direction
=== 'rtl' ? containerPos
.left
: containerPos
.right
;
4654 if ( this.verticalPosition
=== 'below' ) {
4655 newPos
.top
= containerPos
.bottom
;
4656 } else if ( this.verticalPosition
=== 'above' ) {
4657 newPos
.bottom
= $offsetParent
.outerHeight() - containerPos
.top
;
4658 } else if ( this.verticalPosition
=== 'top' ) {
4659 newPos
.top
= containerPos
.top
;
4660 } else if ( this.verticalPosition
=== 'bottom' ) {
4661 newPos
.bottom
= $offsetParent
.outerHeight() - containerPos
.bottom
;
4662 } else if ( this.verticalPosition
=== 'center' ) {
4663 newPos
.top
= containerPos
.top
+
4664 ( this.$floatableContainer
.height() - this.$floatable
.height() ) / 2;
4667 if ( this.horizontalPosition
=== 'before' ) {
4668 newPos
.end
= containerPos
.start
;
4669 } else if ( this.horizontalPosition
=== 'after' ) {
4670 newPos
.start
= containerPos
.end
;
4671 } else if ( this.horizontalPosition
=== 'start' ) {
4672 newPos
.start
= containerPos
.start
;
4673 } else if ( this.horizontalPosition
=== 'end' ) {
4674 newPos
.end
= containerPos
.end
;
4675 } else if ( this.horizontalPosition
=== 'center' ) {
4676 newPos
.left
= containerPos
.left
+
4677 ( this.$floatableContainer
.width() - this.$floatable
.width() ) / 2;
4680 if ( newPos
.start
!== undefined ) {
4681 if ( direction
=== 'rtl' ) {
4682 newPos
.right
= ( isBody
? $( $offsetParent
[ 0 ].ownerDocument
.documentElement
) : $offsetParent
).outerWidth() - newPos
.start
;
4684 newPos
.left
= newPos
.start
;
4686 delete newPos
.start
;
4688 if ( newPos
.end
!== undefined ) {
4689 if ( direction
=== 'rtl' ) {
4690 newPos
.left
= newPos
.end
;
4692 newPos
.right
= ( isBody
? $( $offsetParent
[ 0 ].ownerDocument
.documentElement
) : $offsetParent
).outerWidth() - newPos
.end
;
4697 // Account for scroll position
4698 if ( newPos
.top
!== '' ) {
4699 newPos
.top
+= scrollTop
;
4701 if ( newPos
.bottom
!== '' ) {
4702 newPos
.bottom
-= scrollTop
;
4704 if ( newPos
.left
!== '' ) {
4705 newPos
.left
+= scrollLeft
;
4707 if ( newPos
.right
!== '' ) {
4708 newPos
.right
-= scrollLeft
;
4711 // Account for scrollbar gutter
4712 if ( newPos
.bottom
!== '' ) {
4713 newPos
.bottom
-= horizScrollbarHeight
;
4715 if ( direction
=== 'rtl' ) {
4716 if ( newPos
.left
!== '' ) {
4717 newPos
.left
-= vertScrollbarWidth
;
4720 if ( newPos
.right
!== '' ) {
4721 newPos
.right
-= vertScrollbarWidth
;
4729 * Element that can be automatically clipped to visible boundaries.
4731 * Whenever the element's natural height changes, you have to call
4732 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
4733 * clipping correctly.
4735 * The dimensions of #$clippableContainer will be compared to the boundaries of the
4736 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
4737 * then #$clippable will be given a fixed reduced height and/or width and will be made
4738 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
4739 * but you can build a static footer by setting #$clippableContainer to an element that contains
4740 * #$clippable and the footer.
4746 * @param {Object} [config] Configuration options
4747 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
4748 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
4749 * omit to use #$clippable
4751 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
4752 // Configuration initialization
4753 config
= config
|| {};
4756 this.$clippable
= null;
4757 this.$clippableContainer
= null;
4758 this.clipping
= false;
4759 this.clippedHorizontally
= false;
4760 this.clippedVertically
= false;
4761 this.$clippableScrollableContainer
= null;
4762 this.$clippableScroller
= null;
4763 this.$clippableWindow
= null;
4764 this.idealWidth
= null;
4765 this.idealHeight
= null;
4766 this.onClippableScrollHandler
= this.clip
.bind( this );
4767 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
4770 if ( config
.$clippableContainer
) {
4771 this.setClippableContainer( config
.$clippableContainer
);
4773 this.setClippableElement( config
.$clippable
|| this.$element
);
4779 * Set clippable element.
4781 * If an element is already set, it will be cleaned up before setting up the new element.
4783 * @param {jQuery} $clippable Element to make clippable
4785 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
4786 if ( this.$clippable
) {
4787 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
4788 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
4789 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4792 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
4797 * Set clippable container.
4799 * This is the container that will be measured when deciding whether to clip. When clipping,
4800 * #$clippable will be resized in order to keep the clippable container fully visible.
4802 * If the clippable container is unset, #$clippable will be used.
4804 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
4806 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableContainer = function ( $clippableContainer
) {
4807 this.$clippableContainer
= $clippableContainer
;
4808 if ( this.$clippable
) {
4816 * Do not turn clipping on until after the element is attached to the DOM and visible.
4818 * @param {boolean} [clipping] Enable clipping, omit to toggle
4821 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
4822 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
4824 if ( clipping
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4825 OO
.ui
.warnDeprecation( 'ClippableElement#toggleClipping: Before calling this method, the element must be attached to the DOM.' );
4826 this.warnedUnattached
= true;
4829 if ( this.clipping
!== clipping
) {
4830 this.clipping
= clipping
;
4832 this.$clippableScrollableContainer
= $( this.getClosestScrollableElementContainer() );
4833 // If the clippable container is the root, we have to listen to scroll events and check
4834 // jQuery.scrollTop on the window because of browser inconsistencies
4835 this.$clippableScroller
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
4836 $( OO
.ui
.Element
.static.getWindow( this.$clippableScrollableContainer
) ) :
4837 this.$clippableScrollableContainer
;
4838 this.$clippableScroller
.on( 'scroll', this.onClippableScrollHandler
);
4839 this.$clippableWindow
= $( this.getElementWindow() )
4840 .on( 'resize', this.onClippableWindowResizeHandler
);
4841 // Initial clip after visible
4844 this.$clippable
.css( {
4852 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4854 this.$clippableScrollableContainer
= null;
4855 this.$clippableScroller
.off( 'scroll', this.onClippableScrollHandler
);
4856 this.$clippableScroller
= null;
4857 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
4858 this.$clippableWindow
= null;
4866 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4868 * @return {boolean} Element will be clipped to the visible area
4870 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
4871 return this.clipping
;
4875 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
4877 * @return {boolean} Part of the element is being clipped
4879 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
4880 return this.clippedHorizontally
|| this.clippedVertically
;
4884 * Check if the right of the element is being clipped by the nearest scrollable container.
4886 * @return {boolean} Part of the element is being clipped
4888 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
4889 return this.clippedHorizontally
;
4893 * Check if the bottom of the element is being clipped by the nearest scrollable container.
4895 * @return {boolean} Part of the element is being clipped
4897 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
4898 return this.clippedVertically
;
4902 * Set the ideal size. These are the dimensions #$clippable will have when it's not being clipped.
4904 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
4905 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
4907 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
4908 this.idealWidth
= width
;
4909 this.idealHeight
= height
;
4911 if ( !this.clipping
) {
4912 // Update dimensions
4913 this.$clippable
.css( { width
: width
, height
: height
} );
4915 // While clipping, idealWidth and idealHeight are not considered
4919 * Return the side of the clippable on which it is "anchored" (aligned to something else).
4920 * ClippableElement will clip the opposite side when reducing element's width.
4922 * Classes that mix in ClippableElement should override this to return 'right' if their
4923 * clippable is absolutely positioned and using 'right: Npx' (and not using 'left').
4924 * If your class also mixes in FloatableElement, this is handled automatically.
4926 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
4927 * always in pixels, even if they were unset or set to 'auto'.)
4929 * When in doubt, 'left' (or 'right' in RTL) is a sane fallback.
4931 * @return {string} 'left' or 'right'
4933 OO
.ui
.mixin
.ClippableElement
.prototype.getHorizontalAnchorEdge = function () {
4934 if ( this.computePosition
&& this.positioning
&& this.computePosition().right
!== '' ) {
4941 * Return the side of the clippable on which it is "anchored" (aligned to something else).
4942 * ClippableElement will clip the opposite side when reducing element's width.
4944 * Classes that mix in ClippableElement should override this to return 'bottom' if their
4945 * clippable is absolutely positioned and using 'bottom: Npx' (and not using 'top').
4946 * If your class also mixes in FloatableElement, this is handled automatically.
4948 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
4949 * always in pixels, even if they were unset or set to 'auto'.)
4951 * When in doubt, 'top' is a sane fallback.
4953 * @return {string} 'top' or 'bottom'
4955 OO
.ui
.mixin
.ClippableElement
.prototype.getVerticalAnchorEdge = function () {
4956 if ( this.computePosition
&& this.positioning
&& this.computePosition().bottom
!== '' ) {
4963 * Clip element to visible boundaries and allow scrolling when needed. You should call this method
4964 * when the element's natural height changes.
4966 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
4967 * overlapped by, the visible area of the nearest scrollable container.
4969 * Because calling clip() when the natural height changes isn't always possible, we also set
4970 * max-height when the element isn't being clipped. This means that if the element tries to grow
4971 * beyond the edge, something reasonable will happen before clip() is called.
4975 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
4976 var extraHeight
, extraWidth
, viewportSpacing
,
4977 desiredWidth
, desiredHeight
, allotedWidth
, allotedHeight
,
4978 naturalWidth
, naturalHeight
, clipWidth
, clipHeight
,
4979 $item
, itemRect
, $viewport
, viewportRect
, availableRect
,
4980 direction
, vertScrollbarWidth
, horizScrollbarHeight
,
4981 // Extra tolerance so that the sloppy code below doesn't result in results that are off
4982 // by one or two pixels. (And also so that we have space to display drop shadows.)
4983 // Chosen by fair dice roll.
4986 if ( !this.clipping
) {
4987 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
4991 function rectIntersection( a
, b
) {
4993 out
.top
= Math
.max( a
.top
, b
.top
);
4994 out
.left
= Math
.max( a
.left
, b
.left
);
4995 out
.bottom
= Math
.min( a
.bottom
, b
.bottom
);
4996 out
.right
= Math
.min( a
.right
, b
.right
);
5000 viewportSpacing
= OO
.ui
.getViewportSpacing();
5002 if ( this.$clippableScrollableContainer
.is( 'html, body' ) ) {
5003 $viewport
= $( this.$clippableScrollableContainer
[ 0 ].ownerDocument
.body
);
5004 // Dimensions of the browser window, rather than the element!
5008 right
: document
.documentElement
.clientWidth
,
5009 bottom
: document
.documentElement
.clientHeight
5011 viewportRect
.top
+= viewportSpacing
.top
;
5012 viewportRect
.left
+= viewportSpacing
.left
;
5013 viewportRect
.right
-= viewportSpacing
.right
;
5014 viewportRect
.bottom
-= viewportSpacing
.bottom
;
5016 $viewport
= this.$clippableScrollableContainer
;
5017 viewportRect
= $viewport
[ 0 ].getBoundingClientRect();
5018 // Convert into a plain object
5019 viewportRect
= $.extend( {}, viewportRect
);
5022 // Account for scrollbar gutter
5023 direction
= $viewport
.css( 'direction' );
5024 vertScrollbarWidth
= $viewport
.innerWidth() - $viewport
.prop( 'clientWidth' );
5025 horizScrollbarHeight
= $viewport
.innerHeight() - $viewport
.prop( 'clientHeight' );
5026 viewportRect
.bottom
-= horizScrollbarHeight
;
5027 if ( direction
=== 'rtl' ) {
5028 viewportRect
.left
+= vertScrollbarWidth
;
5030 viewportRect
.right
-= vertScrollbarWidth
;
5033 // Add arbitrary tolerance
5034 viewportRect
.top
+= buffer
;
5035 viewportRect
.left
+= buffer
;
5036 viewportRect
.right
-= buffer
;
5037 viewportRect
.bottom
-= buffer
;
5039 $item
= this.$clippableContainer
|| this.$clippable
;
5041 extraHeight
= $item
.outerHeight() - this.$clippable
.outerHeight();
5042 extraWidth
= $item
.outerWidth() - this.$clippable
.outerWidth();
5044 itemRect
= $item
[ 0 ].getBoundingClientRect();
5045 // Convert into a plain object
5046 itemRect
= $.extend( {}, itemRect
);
5048 // Item might already be clipped, so we can't just use its dimensions (in case we might need to
5049 // make it larger than before). Extend the rectangle to the maximum size we are allowed to take.
5050 if ( this.getHorizontalAnchorEdge() === 'right' ) {
5051 itemRect
.left
= viewportRect
.left
;
5053 itemRect
.right
= viewportRect
.right
;
5055 if ( this.getVerticalAnchorEdge() === 'bottom' ) {
5056 itemRect
.top
= viewportRect
.top
;
5058 itemRect
.bottom
= viewportRect
.bottom
;
5061 availableRect
= rectIntersection( viewportRect
, itemRect
);
5063 desiredWidth
= Math
.max( 0, availableRect
.right
- availableRect
.left
);
5064 desiredHeight
= Math
.max( 0, availableRect
.bottom
- availableRect
.top
);
5065 // It should never be desirable to exceed the dimensions of the browser viewport... right?
5066 desiredWidth
= Math
.min( desiredWidth
,
5067 document
.documentElement
.clientWidth
- viewportSpacing
.left
- viewportSpacing
.right
);
5068 desiredHeight
= Math
.min( desiredHeight
,
5069 document
.documentElement
.clientHeight
- viewportSpacing
.top
- viewportSpacing
.right
);
5070 allotedWidth
= Math
.ceil( desiredWidth
- extraWidth
);
5071 allotedHeight
= Math
.ceil( desiredHeight
- extraHeight
);
5072 naturalWidth
= this.$clippable
.prop( 'scrollWidth' );
5073 naturalHeight
= this.$clippable
.prop( 'scrollHeight' );
5074 clipWidth
= allotedWidth
< naturalWidth
;
5075 clipHeight
= allotedHeight
< naturalHeight
;
5078 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. See T157672.
5079 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
5080 this.$clippable
.css( 'overflowX', 'scroll' );
5081 void this.$clippable
[ 0 ].offsetHeight
; // Force reflow
5082 this.$clippable
.css( {
5083 width
: Math
.max( 0, allotedWidth
),
5087 this.$clippable
.css( {
5089 width
: this.idealWidth
|| '',
5090 maxWidth
: Math
.max( 0, allotedWidth
)
5094 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. See T157672.
5095 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
5096 this.$clippable
.css( 'overflowY', 'scroll' );
5097 void this.$clippable
[ 0 ].offsetHeight
; // Force reflow
5098 this.$clippable
.css( {
5099 height
: Math
.max( 0, allotedHeight
),
5103 this.$clippable
.css( {
5105 height
: this.idealHeight
|| '',
5106 maxHeight
: Math
.max( 0, allotedHeight
)
5110 // If we stopped clipping in at least one of the dimensions
5111 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
5112 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
5115 this.clippedHorizontally
= clipWidth
;
5116 this.clippedVertically
= clipHeight
;
5122 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
5123 * By default, each popup has an anchor that points toward its origin.
5124 * Please see the [OOUI documentation on MediaWiki.org] [1] for more information and examples.
5126 * Unlike most widgets, PopupWidget is initially hidden and must be shown by calling #toggle.
5129 * // A popup widget.
5130 * var popup = new OO.ui.PopupWidget( {
5131 * $content: $( '<p>Hi there!</p>' ),
5136 * $( 'body' ).append( popup.$element );
5137 * // To display the popup, toggle the visibility to 'true'.
5138 * popup.toggle( true );
5140 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups
5143 * @extends OO.ui.Widget
5144 * @mixins OO.ui.mixin.LabelElement
5145 * @mixins OO.ui.mixin.ClippableElement
5146 * @mixins OO.ui.mixin.FloatableElement
5149 * @param {Object} [config] Configuration options
5150 * @cfg {number|null} [width=320] Width of popup in pixels. Pass `null` to use automatic width.
5151 * @cfg {number|null} [height=null] Height of popup in pixels. Pass `null` to use automatic height.
5152 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
5153 * @cfg {string} [position='below'] Where to position the popup relative to $floatableContainer
5154 * 'above': Put popup above $floatableContainer; anchor points down to the horizontal center
5155 * of $floatableContainer
5156 * 'below': Put popup below $floatableContainer; anchor points up to the horizontal center
5157 * of $floatableContainer
5158 * 'before': Put popup to the left (LTR) / right (RTL) of $floatableContainer; anchor points
5159 * endwards (right/left) to the vertical center of $floatableContainer
5160 * 'after': Put popup to the right (LTR) / left (RTL) of $floatableContainer; anchor points
5161 * startwards (left/right) to the vertical center of $floatableContainer
5162 * @cfg {string} [align='center'] How to align the popup to $floatableContainer
5163 * 'forwards': If position is above/below, move the popup as far endwards (right in LTR, left in RTL)
5164 * as possible while still keeping the anchor within the popup;
5165 * if position is before/after, move the popup as far downwards as possible.
5166 * 'backwards': If position is above/below, move the popup as far startwards (left in LTR, right in RTL)
5167 * as possible while still keeping the anchor within the popup;
5168 * if position in before/after, move the popup as far upwards as possible.
5169 * 'center': Horizontally (if position is above/below) or vertically (before/after) align the center
5170 * of the popup with the center of $floatableContainer.
5171 * 'force-left': Alias for 'forwards' in LTR and 'backwards' in RTL
5172 * 'force-right': Alias for 'backwards' in RTL and 'forwards' in LTR
5173 * @cfg {boolean} [autoFlip=true] Whether to automatically switch the popup's position between
5174 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5175 * desired direction to display the popup without clipping
5176 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
5177 * See the [OOUI docs on MediaWiki][3] for an example.
5178 * [3]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#containerExample
5179 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
5180 * @cfg {jQuery} [$content] Content to append to the popup's body
5181 * @cfg {jQuery} [$footer] Content to append to the popup's footer
5182 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
5183 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
5184 * This config option is only relevant if #autoClose is set to `true`. See the [OOUI documentation on MediaWiki][2]
5186 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#autocloseExample
5187 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
5189 * @cfg {boolean} [padded=false] Add padding to the popup's body
5191 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
5192 // Configuration initialization
5193 config
= config
|| {};
5195 // Parent constructor
5196 OO
.ui
.PopupWidget
.parent
.call( this, config
);
5198 // Properties (must be set before ClippableElement constructor call)
5199 this.$body
= $( '<div>' );
5200 this.$popup
= $( '<div>' );
5202 // Mixin constructors
5203 OO
.ui
.mixin
.LabelElement
.call( this, config
);
5204 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, {
5205 $clippable
: this.$body
,
5206 $clippableContainer
: this.$popup
5208 OO
.ui
.mixin
.FloatableElement
.call( this, config
);
5211 this.$anchor
= $( '<div>' );
5212 // If undefined, will be computed lazily in computePosition()
5213 this.$container
= config
.$container
;
5214 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
5215 this.autoClose
= !!config
.autoClose
;
5216 this.transitionTimeout
= null;
5217 this.anchored
= false;
5218 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
5219 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
5222 this.setSize( config
.width
, config
.height
);
5223 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
5224 this.setAlignment( config
.align
|| 'center' );
5225 this.setPosition( config
.position
|| 'below' );
5226 this.setAutoFlip( config
.autoFlip
=== undefined || config
.autoFlip
);
5227 this.setAutoCloseIgnore( config
.$autoCloseIgnore
);
5228 this.$body
.addClass( 'oo-ui-popupWidget-body' );
5229 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
5231 .addClass( 'oo-ui-popupWidget-popup' )
5232 .append( this.$body
);
5234 .addClass( 'oo-ui-popupWidget' )
5235 .append( this.$popup
, this.$anchor
);
5236 // Move content, which was added to #$element by OO.ui.Widget, to the body
5237 // FIXME This is gross, we should use '$body' or something for the config
5238 if ( config
.$content
instanceof jQuery
) {
5239 this.$body
.append( config
.$content
);
5242 if ( config
.padded
) {
5243 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
5246 if ( config
.head
) {
5247 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
5248 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
5249 this.$head
= $( '<div>' )
5250 .addClass( 'oo-ui-popupWidget-head' )
5251 .append( this.$label
, this.closeButton
.$element
);
5252 this.$popup
.prepend( this.$head
);
5255 if ( config
.$footer
) {
5256 this.$footer
= $( '<div>' )
5257 .addClass( 'oo-ui-popupWidget-footer' )
5258 .append( config
.$footer
);
5259 this.$popup
.append( this.$footer
);
5262 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
5263 // that reference properties not initialized at that time of parent class construction
5264 // TODO: Find a better way to handle post-constructor setup
5265 this.visible
= false;
5266 this.$element
.addClass( 'oo-ui-element-hidden' );
5271 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
5272 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
5273 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
5274 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.FloatableElement
);
5281 * The popup is ready: it is visible and has been positioned and clipped.
5287 * Handles document mouse down events.
5290 * @param {MouseEvent} e Mouse down event
5292 OO
.ui
.PopupWidget
.prototype.onDocumentMouseDown = function ( e
) {
5295 !OO
.ui
.contains( this.$element
.add( this.$autoCloseIgnore
).get(), e
.target
, true )
5297 this.toggle( false );
5301 // Deprecated alias since 0.28.3
5302 OO
.ui
.PopupWidget
.prototype.onMouseDown = function () {
5303 OO
.ui
.warnDeprecation( 'onMouseDown is deprecated, use onDocumentMouseDown instead' );
5304 this.onDocumentMouseDown
.apply( this, arguments
);
5308 * Bind document mouse down listener.
5312 OO
.ui
.PopupWidget
.prototype.bindDocumentMouseDownListener = function () {
5313 // Capture clicks outside popup
5314 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
5315 // We add 'click' event because iOS safari needs to respond to this event.
5316 // We can't use 'touchstart' (as is usually the equivalent to 'mousedown') because
5317 // then it will trigger when scrolling. While iOS Safari has some reported behavior
5318 // of occasionally not emitting 'click' properly, that event seems to be the standard
5319 // that it should be emitting, so we add it to this and will operate the event handler
5320 // on whichever of these events was triggered first
5321 this.getElementDocument().addEventListener( 'click', this.onDocumentMouseDownHandler
, true );
5324 // Deprecated alias since 0.28.3
5325 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
5326 OO
.ui
.warnDeprecation( 'bindMouseDownListener is deprecated, use bindDocumentMouseDownListener instead' );
5327 this.bindDocumentMouseDownListener
.apply( this, arguments
);
5331 * Handles close button click events.
5335 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
5336 if ( this.isVisible() ) {
5337 this.toggle( false );
5342 * Unbind document mouse down listener.
5346 OO
.ui
.PopupWidget
.prototype.unbindDocumentMouseDownListener = function () {
5347 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
5348 this.getElementDocument().removeEventListener( 'click', this.onDocumentMouseDownHandler
, true );
5351 // Deprecated alias since 0.28.3
5352 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
5353 OO
.ui
.warnDeprecation( 'unbindMouseDownListener is deprecated, use unbindDocumentMouseDownListener instead' );
5354 this.unbindDocumentMouseDownListener
.apply( this, arguments
);
5358 * Handles document key down events.
5361 * @param {KeyboardEvent} e Key down event
5363 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
5365 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
5368 this.toggle( false );
5370 e
.stopPropagation();
5375 * Bind document key down listener.
5379 OO
.ui
.PopupWidget
.prototype.bindDocumentKeyDownListener = function () {
5380 this.getElementDocument().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
5383 // Deprecated alias since 0.28.3
5384 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
5385 OO
.ui
.warnDeprecation( 'bindKeyDownListener is deprecated, use bindDocumentKeyDownListener instead' );
5386 this.bindDocumentKeyDownListener
.apply( this, arguments
);
5390 * Unbind document key down listener.
5394 OO
.ui
.PopupWidget
.prototype.unbindDocumentKeyDownListener = function () {
5395 this.getElementDocument().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
5398 // Deprecated alias since 0.28.3
5399 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
5400 OO
.ui
.warnDeprecation( 'unbindKeyDownListener is deprecated, use unbindDocumentKeyDownListener instead' );
5401 this.unbindDocumentKeyDownListener
.apply( this, arguments
);
5405 * Show, hide, or toggle the visibility of the anchor.
5407 * @param {boolean} [show] Show anchor, omit to toggle
5409 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
5410 show
= show
=== undefined ? !this.anchored
: !!show
;
5412 if ( this.anchored
!== show
) {
5414 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
5415 this.$element
.addClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5417 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
5418 this.$element
.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5420 this.anchored
= show
;
5425 * Change which edge the anchor appears on.
5427 * @param {string} edge 'top', 'bottom', 'start' or 'end'
5429 OO
.ui
.PopupWidget
.prototype.setAnchorEdge = function ( edge
) {
5430 if ( [ 'top', 'bottom', 'start', 'end' ].indexOf( edge
) === -1 ) {
5431 throw new Error( 'Invalid value for edge: ' + edge
);
5433 if ( this.anchorEdge
!== null ) {
5434 this.$element
.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5436 this.anchorEdge
= edge
;
5437 if ( this.anchored
) {
5438 this.$element
.addClass( 'oo-ui-popupWidget-anchored-' + edge
);
5443 * Check if the anchor is visible.
5445 * @return {boolean} Anchor is visible
5447 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
5448 return this.anchored
;
5452 * Toggle visibility of the popup. The popup is initially hidden and must be shown by calling
5453 * `.toggle( true )` after its #$element is attached to the DOM.
5455 * Do not show the popup while it is not attached to the DOM. The calculations required to display
5456 * it in the right place and with the right dimensions only work correctly while it is attached.
5457 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
5458 * strictly enforced, so currently it only generates a warning in the browser console.
5463 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
5464 var change
, normalHeight
, oppositeHeight
, normalWidth
, oppositeWidth
;
5465 show
= show
=== undefined ? !this.isVisible() : !!show
;
5467 change
= show
!== this.isVisible();
5469 if ( show
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
5470 OO
.ui
.warnDeprecation( 'PopupWidget#toggle: Before calling this method, the popup must be attached to the DOM.' );
5471 this.warnedUnattached
= true;
5473 if ( show
&& !this.$floatableContainer
&& this.isElementAttached() ) {
5474 // Fall back to the parent node if the floatableContainer is not set
5475 this.setFloatableContainer( this.$element
.parent() );
5478 if ( change
&& show
&& this.autoFlip
) {
5479 // Reset auto-flipping before showing the popup again. It's possible we no longer need to flip
5480 // (e.g. if the user scrolled).
5481 this.isAutoFlipped
= false;
5485 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
5488 this.togglePositioning( show
&& !!this.$floatableContainer
);
5491 if ( this.autoClose
) {
5492 this.bindDocumentMouseDownListener();
5493 this.bindDocumentKeyDownListener();
5495 this.updateDimensions();
5496 this.toggleClipping( true );
5498 if ( this.autoFlip
) {
5499 if ( this.popupPosition
=== 'above' || this.popupPosition
=== 'below' ) {
5500 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5501 // If opening the popup in the normal direction causes it to be clipped, open
5502 // in the opposite one instead
5503 normalHeight
= this.$element
.height();
5504 this.isAutoFlipped
= !this.isAutoFlipped
;
5506 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5507 // If that also causes it to be clipped, open in whichever direction
5508 // we have more space
5509 oppositeHeight
= this.$element
.height();
5510 if ( oppositeHeight
< normalHeight
) {
5511 this.isAutoFlipped
= !this.isAutoFlipped
;
5517 if ( this.popupPosition
=== 'before' || this.popupPosition
=== 'after' ) {
5518 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5519 // If opening the popup in the normal direction causes it to be clipped, open
5520 // in the opposite one instead
5521 normalWidth
= this.$element
.width();
5522 this.isAutoFlipped
= !this.isAutoFlipped
;
5523 // Due to T180173 horizontally clipped PopupWidgets have messed up dimensions,
5524 // which causes positioning to be off. Toggle clipping back and fort to work around.
5525 this.toggleClipping( false );
5527 this.toggleClipping( true );
5528 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5529 // If that also causes it to be clipped, open in whichever direction
5530 // we have more space
5531 oppositeWidth
= this.$element
.width();
5532 if ( oppositeWidth
< normalWidth
) {
5533 this.isAutoFlipped
= !this.isAutoFlipped
;
5534 // Due to T180173 horizontally clipped PopupWidgets have messed up dimensions,
5535 // which causes positioning to be off. Toggle clipping back and fort to work around.
5536 this.toggleClipping( false );
5538 this.toggleClipping( true );
5545 this.emit( 'ready' );
5547 this.toggleClipping( false );
5548 if ( this.autoClose
) {
5549 this.unbindDocumentMouseDownListener();
5550 this.unbindDocumentKeyDownListener();
5559 * Set the size of the popup.
5561 * Changing the size may also change the popup's position depending on the alignment.
5563 * @param {number|null} [width=320] Width in pixels. Pass `null` to use automatic width.
5564 * @param {number|null} [height=null] Height in pixels. Pass `null` to use automatic height.
5565 * @param {boolean} [transition=false] Use a smooth transition
5568 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
5569 this.width
= width
!== undefined ? width
: 320;
5570 this.height
= height
!== undefined ? height
: null;
5571 if ( this.isVisible() ) {
5572 this.updateDimensions( transition
);
5577 * Update the size and position.
5579 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
5580 * be called automatically.
5582 * @param {boolean} [transition=false] Use a smooth transition
5585 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
5588 // Prevent transition from being interrupted
5589 clearTimeout( this.transitionTimeout
);
5591 // Enable transition
5592 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
5598 // Prevent transitioning after transition is complete
5599 this.transitionTimeout
= setTimeout( function () {
5600 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
5603 // Prevent transitioning immediately
5604 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
5611 OO
.ui
.PopupWidget
.prototype.computePosition = function () {
5612 var direction
, align
, vertical
, start
, end
, near
, far
, sizeProp
, popupSize
, anchorSize
, anchorPos
,
5613 anchorOffset
, anchorMargin
, parentPosition
, positionProp
, positionAdjustment
, floatablePos
,
5614 offsetParentPos
, containerPos
, popupPosition
, viewportSpacing
,
5616 anchorCss
= { left
: '', right
: '', top
: '', bottom
: '' },
5617 popupPositionOppositeMap
= {
5625 'force-left': 'backwards',
5626 'force-right': 'forwards'
5629 'force-left': 'forwards',
5630 'force-right': 'backwards'
5642 backwards
: this.anchored
? 'before' : 'end'
5650 if ( !this.$container
) {
5651 // Lazy-initialize $container if not specified in constructor
5652 this.$container
= $( this.getClosestScrollableElementContainer() );
5654 direction
= this.$container
.css( 'direction' );
5656 // Set height and width before we do anything else, since it might cause our measurements
5657 // to change (e.g. due to scrollbars appearing or disappearing), and it also affects centering
5659 width
: this.width
!== null ? this.width
: 'auto',
5660 height
: this.height
!== null ? this.height
: 'auto'
5663 align
= alignMap
[ direction
][ this.align
] || this.align
;
5664 popupPosition
= this.popupPosition
;
5665 if ( this.isAutoFlipped
) {
5666 popupPosition
= popupPositionOppositeMap
[ popupPosition
];
5669 // If the popup is positioned before or after, then the anchor positioning is vertical, otherwise horizontal
5670 vertical
= popupPosition
=== 'before' || popupPosition
=== 'after';
5671 start
= vertical
? 'top' : ( direction
=== 'rtl' ? 'right' : 'left' );
5672 end
= vertical
? 'bottom' : ( direction
=== 'rtl' ? 'left' : 'right' );
5673 near
= vertical
? 'top' : 'left';
5674 far
= vertical
? 'bottom' : 'right';
5675 sizeProp
= vertical
? 'Height' : 'Width';
5676 popupSize
= vertical
? ( this.height
|| this.$popup
.height() ) : ( this.width
|| this.$popup
.width() );
5678 this.setAnchorEdge( anchorEdgeMap
[ popupPosition
] );
5679 this.horizontalPosition
= vertical
? popupPosition
: hPosMap
[ align
];
5680 this.verticalPosition
= vertical
? vPosMap
[ align
] : popupPosition
;
5683 parentPosition
= OO
.ui
.mixin
.FloatableElement
.prototype.computePosition
.call( this );
5684 // Find out which property FloatableElement used for positioning, and adjust that value
5685 positionProp
= vertical
?
5686 ( parentPosition
.top
!== '' ? 'top' : 'bottom' ) :
5687 ( parentPosition
.left
!== '' ? 'left' : 'right' );
5689 // Figure out where the near and far edges of the popup and $floatableContainer are
5690 floatablePos
= this.$floatableContainer
.offset();
5691 floatablePos
[ far
] = floatablePos
[ near
] + this.$floatableContainer
[ 'outer' + sizeProp
]();
5692 // Measure where the offsetParent is and compute our position based on that and parentPosition
5693 offsetParentPos
= this.$element
.offsetParent()[ 0 ] === document
.documentElement
?
5694 { top
: 0, left
: 0 } :
5695 this.$element
.offsetParent().offset();
5697 if ( positionProp
=== near
) {
5698 popupPos
[ near
] = offsetParentPos
[ near
] + parentPosition
[ near
];
5699 popupPos
[ far
] = popupPos
[ near
] + popupSize
;
5701 popupPos
[ far
] = offsetParentPos
[ near
] +
5702 this.$element
.offsetParent()[ 'inner' + sizeProp
]() - parentPosition
[ far
];
5703 popupPos
[ near
] = popupPos
[ far
] - popupSize
;
5706 if ( this.anchored
) {
5707 // Position the anchor (which is positioned relative to the popup) to point to $floatableContainer
5708 anchorPos
= ( floatablePos
[ start
] + floatablePos
[ end
] ) / 2;
5709 anchorOffset
= ( start
=== far
? -1 : 1 ) * ( anchorPos
- popupPos
[ start
] );
5711 // If the anchor is less than 2*anchorSize from either edge, move the popup to make more space
5712 // this.$anchor.width()/height() returns 0 because of the CSS trickery we use, so use scrollWidth/Height
5713 anchorSize
= this.$anchor
[ 0 ][ 'scroll' + sizeProp
];
5714 anchorMargin
= parseFloat( this.$anchor
.css( 'margin-' + start
) );
5715 if ( anchorOffset
+ anchorMargin
< 2 * anchorSize
) {
5716 // Not enough space for the anchor on the start side; pull the popup startwards
5717 positionAdjustment
= ( positionProp
=== start
? -1 : 1 ) *
5718 ( 2 * anchorSize
- ( anchorOffset
+ anchorMargin
) );
5719 } else if ( anchorOffset
+ anchorMargin
> popupSize
- 2 * anchorSize
) {
5720 // Not enough space for the anchor on the end side; pull the popup endwards
5721 positionAdjustment
= ( positionProp
=== end
? -1 : 1 ) *
5722 ( anchorOffset
+ anchorMargin
- ( popupSize
- 2 * anchorSize
) );
5724 positionAdjustment
= 0;
5727 positionAdjustment
= 0;
5730 // Check if the popup will go beyond the edge of this.$container
5731 containerPos
= this.$container
[ 0 ] === document
.documentElement
?
5732 { top
: 0, left
: 0 } :
5733 this.$container
.offset();
5734 containerPos
[ far
] = containerPos
[ near
] + this.$container
[ 'inner' + sizeProp
]();
5735 if ( this.$container
[ 0 ] === document
.documentElement
) {
5736 viewportSpacing
= OO
.ui
.getViewportSpacing();
5737 containerPos
[ near
] += viewportSpacing
[ near
];
5738 containerPos
[ far
] -= viewportSpacing
[ far
];
5740 // Take into account how much the popup will move because of the adjustments we're going to make
5741 popupPos
[ near
] += ( positionProp
=== near
? 1 : -1 ) * positionAdjustment
;
5742 popupPos
[ far
] += ( positionProp
=== near
? 1 : -1 ) * positionAdjustment
;
5743 if ( containerPos
[ near
] + this.containerPadding
> popupPos
[ near
] ) {
5744 // Popup goes beyond the near (left/top) edge, move it to the right/bottom
5745 positionAdjustment
+= ( positionProp
=== near
? 1 : -1 ) *
5746 ( containerPos
[ near
] + this.containerPadding
- popupPos
[ near
] );
5747 } else if ( containerPos
[ far
] - this.containerPadding
< popupPos
[ far
] ) {
5748 // Popup goes beyond the far (right/bottom) edge, move it to the left/top
5749 positionAdjustment
+= ( positionProp
=== far
? 1 : -1 ) *
5750 ( popupPos
[ far
] - ( containerPos
[ far
] - this.containerPadding
) );
5753 if ( this.anchored
) {
5754 // Adjust anchorOffset for positionAdjustment
5755 anchorOffset
+= ( positionProp
=== start
? -1 : 1 ) * positionAdjustment
;
5757 // Position the anchor
5758 anchorCss
[ start
] = anchorOffset
;
5759 this.$anchor
.css( anchorCss
);
5762 // Move the popup if needed
5763 parentPosition
[ positionProp
] += positionAdjustment
;
5765 return parentPosition
;
5769 * Set popup alignment
5771 * @param {string} [align=center] Alignment of the popup, `center`, `force-left`, `force-right`,
5772 * `backwards` or `forwards`.
5774 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
5775 // Validate alignment
5776 if ( [ 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
5779 this.align
= 'center';
5785 * Get popup alignment
5787 * @return {string} Alignment of the popup, `center`, `force-left`, `force-right`,
5788 * `backwards` or `forwards`.
5790 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
5795 * Change the positioning of the popup.
5797 * @param {string} position 'above', 'below', 'before' or 'after'
5799 OO
.ui
.PopupWidget
.prototype.setPosition = function ( position
) {
5800 if ( [ 'above', 'below', 'before', 'after' ].indexOf( position
) === -1 ) {
5803 this.popupPosition
= position
;
5808 * Get popup positioning.
5810 * @return {string} 'above', 'below', 'before' or 'after'
5812 OO
.ui
.PopupWidget
.prototype.getPosition = function () {
5813 return this.popupPosition
;
5817 * Set popup auto-flipping.
5819 * @param {boolean} autoFlip Whether to automatically switch the popup's position between
5820 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5821 * desired direction to display the popup without clipping
5823 OO
.ui
.PopupWidget
.prototype.setAutoFlip = function ( autoFlip
) {
5824 autoFlip
= !!autoFlip
;
5826 if ( this.autoFlip
!== autoFlip
) {
5827 this.autoFlip
= autoFlip
;
5832 * Set which elements will not close the popup when clicked.
5834 * For auto-closing popups, clicks on these elements will not cause the popup to auto-close.
5836 * @param {jQuery} $autoCloseIgnore Elements to ignore for auto-closing
5838 OO
.ui
.PopupWidget
.prototype.setAutoCloseIgnore = function ( $autoCloseIgnore
) {
5839 this.$autoCloseIgnore
= $autoCloseIgnore
;
5843 * Get an ID of the body element, this can be used as the
5844 * `aria-describedby` attribute for an input field.
5846 * @return {string} The ID of the body element
5848 OO
.ui
.PopupWidget
.prototype.getBodyId = function () {
5849 var id
= this.$body
.attr( 'id' );
5850 if ( id
=== undefined ) {
5851 id
= OO
.ui
.generateElementId();
5852 this.$body
.attr( 'id', id
);
5858 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5859 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5860 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5861 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5867 * @param {Object} [config] Configuration options
5868 * @cfg {Object} [popup] Configuration to pass to popup
5869 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5871 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
5872 // Configuration initialization
5873 config
= config
|| {};
5876 this.popup
= new OO
.ui
.PopupWidget( $.extend(
5879 $floatableContainer
: this.$element
5883 $autoCloseIgnore
: this.$element
.add( config
.popup
&& config
.popup
.$autoCloseIgnore
)
5893 * @return {OO.ui.PopupWidget} Popup widget
5895 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
5900 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
5901 * which is used to display additional information or options.
5904 * // Example of a popup button.
5905 * var popupButton = new OO.ui.PopupButtonWidget( {
5906 * label: 'Popup button with options',
5909 * $content: $( '<p>Additional options here.</p>' ),
5911 * align: 'force-left'
5914 * // Append the button to the DOM.
5915 * $( 'body' ).append( popupButton.$element );
5918 * @extends OO.ui.ButtonWidget
5919 * @mixins OO.ui.mixin.PopupElement
5922 * @param {Object} [config] Configuration options
5923 * @cfg {jQuery} [$overlay] Render the popup into a separate layer. This configuration is useful in cases where
5924 * the expanded popup is larger than its containing `<div>`. The specified overlay layer is usually on top of the
5925 * containing `<div>` and has a larger area. By default, the popup uses relative positioning.
5926 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
5928 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
5929 // Configuration initialization
5930 config
= config
|| {};
5932 // Parent constructor
5933 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
5935 // Mixin constructors
5936 OO
.ui
.mixin
.PopupElement
.call( this, config
);
5939 this.$overlay
= ( config
.$overlay
=== true ? OO
.ui
.getDefaultOverlay() : config
.$overlay
) || this.$element
;
5942 this.connect( this, { click
: 'onAction' } );
5946 .addClass( 'oo-ui-popupButtonWidget' );
5948 .addClass( 'oo-ui-popupButtonWidget-popup' )
5949 .toggleClass( 'oo-ui-popupButtonWidget-framed-popup', this.isFramed() )
5950 .toggleClass( 'oo-ui-popupButtonWidget-frameless-popup', !this.isFramed() );
5951 this.$overlay
.append( this.popup
.$element
);
5956 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
5957 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
5962 * Handle the button action being triggered.
5966 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
5967 this.popup
.toggle();
5971 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
5973 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
5978 * @mixins OO.ui.mixin.GroupElement
5981 * @param {Object} [config] Configuration options
5983 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
5984 // Mixin constructors
5985 OO
.ui
.mixin
.GroupElement
.call( this, config
);
5990 OO
.mixinClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
5995 * Set the disabled state of the widget.
5997 * This will also update the disabled state of child widgets.
5999 * @param {boolean} disabled Disable widget
6002 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
6006 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
6007 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
6009 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
6011 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6012 this.items
[ i
].updateDisabled();
6020 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
6022 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
6023 * allows bidirectional communication.
6025 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
6033 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
6040 * Check if widget is disabled.
6042 * Checks parent if present, making disabled state inheritable.
6044 * @return {boolean} Widget is disabled
6046 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
6047 return this.disabled
||
6048 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
6052 * Set group element is in.
6054 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
6057 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
6059 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
6060 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
6062 // Initialize item disabled states
6063 this.updateDisabled();
6069 * OptionWidgets are special elements that can be selected and configured with data. The
6070 * data is often unique for each option, but it does not have to be. OptionWidgets are used
6071 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
6072 * and examples, please see the [OOUI documentation on MediaWiki][1].
6074 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6077 * @extends OO.ui.Widget
6078 * @mixins OO.ui.mixin.ItemWidget
6079 * @mixins OO.ui.mixin.LabelElement
6080 * @mixins OO.ui.mixin.FlaggedElement
6081 * @mixins OO.ui.mixin.AccessKeyedElement
6084 * @param {Object} [config] Configuration options
6086 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
6087 // Configuration initialization
6088 config
= config
|| {};
6090 // Parent constructor
6091 OO
.ui
.OptionWidget
.parent
.call( this, config
);
6093 // Mixin constructors
6094 OO
.ui
.mixin
.ItemWidget
.call( this );
6095 OO
.ui
.mixin
.LabelElement
.call( this, config
);
6096 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
6097 OO
.ui
.mixin
.AccessKeyedElement
.call( this, config
);
6100 this.selected
= false;
6101 this.highlighted
= false;
6102 this.pressed
= false;
6106 .data( 'oo-ui-optionWidget', this )
6107 // Allow programmatic focussing (and by accesskey), but not tabbing
6108 .attr( 'tabindex', '-1' )
6109 .attr( 'role', 'option' )
6110 .attr( 'aria-selected', 'false' )
6111 .addClass( 'oo-ui-optionWidget' )
6112 .append( this.$label
);
6117 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
6118 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
6119 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
6120 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
6121 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
6123 /* Static Properties */
6126 * Whether this option can be selected. See #setSelected.
6130 * @property {boolean}
6132 OO
.ui
.OptionWidget
.static.selectable
= true;
6135 * Whether this option can be highlighted. See #setHighlighted.
6139 * @property {boolean}
6141 OO
.ui
.OptionWidget
.static.highlightable
= true;
6144 * Whether this option can be pressed. See #setPressed.
6148 * @property {boolean}
6150 OO
.ui
.OptionWidget
.static.pressable
= true;
6153 * Whether this option will be scrolled into view when it is selected.
6157 * @property {boolean}
6159 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
6164 * Check if the option can be selected.
6166 * @return {boolean} Item is selectable
6168 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
6169 return this.constructor.static.selectable
&& !this.disabled
&& this.isVisible();
6173 * Check if the option can be highlighted. A highlight indicates that the option
6174 * may be selected when a user presses enter or clicks. Disabled items cannot
6177 * @return {boolean} Item is highlightable
6179 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
6180 return this.constructor.static.highlightable
&& !this.disabled
&& this.isVisible();
6184 * Check if the option can be pressed. The pressed state occurs when a user mouses
6185 * down on an item, but has not yet let go of the mouse.
6187 * @return {boolean} Item is pressable
6189 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
6190 return this.constructor.static.pressable
&& !this.disabled
&& this.isVisible();
6194 * Check if the option is selected.
6196 * @return {boolean} Item is selected
6198 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
6199 return this.selected
;
6203 * Check if the option is highlighted. A highlight indicates that the
6204 * item may be selected when a user presses enter or clicks.
6206 * @return {boolean} Item is highlighted
6208 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
6209 return this.highlighted
;
6213 * Check if the option is pressed. The pressed state occurs when a user mouses
6214 * down on an item, but has not yet let go of the mouse. The item may appear
6215 * selected, but it will not be selected until the user releases the mouse.
6217 * @return {boolean} Item is pressed
6219 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
6220 return this.pressed
;
6224 * Set the option’s selected state. In general, all modifications to the selection
6225 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
6226 * method instead of this method.
6228 * @param {boolean} [state=false] Select option
6231 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
6232 if ( this.constructor.static.selectable
) {
6233 this.selected
= !!state
;
6235 .toggleClass( 'oo-ui-optionWidget-selected', state
)
6236 .attr( 'aria-selected', state
.toString() );
6237 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
6238 this.scrollElementIntoView();
6240 this.updateThemeClasses();
6246 * Set the option’s highlighted state. In general, all programmatic
6247 * modifications to the highlight should be handled by the
6248 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
6249 * method instead of this method.
6251 * @param {boolean} [state=false] Highlight option
6254 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
6255 if ( this.constructor.static.highlightable
) {
6256 this.highlighted
= !!state
;
6257 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
6258 this.updateThemeClasses();
6264 * Set the option’s pressed state. In general, all
6265 * programmatic modifications to the pressed state should be handled by the
6266 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
6267 * method instead of this method.
6269 * @param {boolean} [state=false] Press option
6272 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
6273 if ( this.constructor.static.pressable
) {
6274 this.pressed
= !!state
;
6275 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
6276 this.updateThemeClasses();
6282 * Get text to match search strings against.
6284 * The default implementation returns the label text, but subclasses
6285 * can override this to provide more complex behavior.
6287 * @return {string|boolean} String to match search string against
6289 OO
.ui
.OptionWidget
.prototype.getMatchText = function () {
6290 var label
= this.getLabel();
6291 return typeof label
=== 'string' ? label
: this.$label
.text();
6295 * A SelectWidget is of a generic selection of options. The OOUI library contains several types of
6296 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
6297 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
6300 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
6301 * information, please see the [OOUI documentation on MediaWiki][1].
6304 * // Example of a select widget with three options
6305 * var select = new OO.ui.SelectWidget( {
6307 * new OO.ui.OptionWidget( {
6309 * label: 'Option One',
6311 * new OO.ui.OptionWidget( {
6313 * label: 'Option Two',
6315 * new OO.ui.OptionWidget( {
6317 * label: 'Option Three',
6321 * $( 'body' ).append( select.$element );
6323 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6327 * @extends OO.ui.Widget
6328 * @mixins OO.ui.mixin.GroupWidget
6331 * @param {Object} [config] Configuration options
6332 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
6333 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
6334 * the [OOUI documentation on MediaWiki] [2] for examples.
6335 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6337 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
6338 // Configuration initialization
6339 config
= config
|| {};
6341 // Parent constructor
6342 OO
.ui
.SelectWidget
.parent
.call( this, config
);
6344 // Mixin constructors
6345 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
6348 this.pressed
= false;
6349 this.selecting
= null;
6350 this.onDocumentMouseUpHandler
= this.onDocumentMouseUp
.bind( this );
6351 this.onDocumentMouseMoveHandler
= this.onDocumentMouseMove
.bind( this );
6352 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
6353 this.onDocumentKeyPressHandler
= this.onDocumentKeyPress
.bind( this );
6354 this.keyPressBuffer
= '';
6355 this.keyPressBufferTimer
= null;
6356 this.blockMouseOverEvents
= 0;
6359 this.connect( this, {
6363 focusin
: this.onFocus
.bind( this ),
6364 mousedown
: this.onMouseDown
.bind( this ),
6365 mouseover
: this.onMouseOver
.bind( this ),
6366 mouseleave
: this.onMouseLeave
.bind( this )
6371 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
6372 .attr( 'role', 'listbox' );
6373 this.setFocusOwner( this.$element
);
6374 if ( Array
.isArray( config
.items
) ) {
6375 this.addItems( config
.items
);
6381 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
6382 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
6389 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
6391 * @param {OO.ui.OptionWidget|null} item Highlighted item
6397 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
6398 * pressed state of an option.
6400 * @param {OO.ui.OptionWidget|null} item Pressed item
6406 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
6408 * @param {OO.ui.OptionWidget|null} item Selected item
6413 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
6414 * @param {OO.ui.OptionWidget} item Chosen item
6420 * An `add` event is emitted when options are added to the select with the #addItems method.
6422 * @param {OO.ui.OptionWidget[]} items Added items
6423 * @param {number} index Index of insertion point
6429 * A `remove` event is emitted when options are removed from the select with the #clearItems
6430 * or #removeItems methods.
6432 * @param {OO.ui.OptionWidget[]} items Removed items
6438 * Handle focus events
6441 * @param {jQuery.Event} event
6443 OO
.ui
.SelectWidget
.prototype.onFocus = function ( event
) {
6445 if ( event
.target
=== this.$element
[ 0 ] ) {
6446 // This widget was focussed, e.g. by the user tabbing to it.
6447 // The styles for focus state depend on one of the items being selected.
6448 if ( !this.findSelectedItem() ) {
6449 item
= this.findFirstSelectableItem();
6452 if ( event
.target
.tabIndex
=== -1 ) {
6453 // One of the options got focussed (and the event bubbled up here).
6454 // They can't be tabbed to, but they can be activated using accesskeys.
6455 // OptionWidgets and focusable UI elements inside them have tabindex="-1" set.
6456 item
= this.findTargetItem( event
);
6458 // There is something actually user-focusable in one of the labels of the options, and the
6459 // user focussed it (e.g. by tabbing to it). Do nothing (especially, don't change the focus).
6465 if ( item
.constructor.static.highlightable
) {
6466 this.highlightItem( item
);
6468 this.selectItem( item
);
6472 if ( event
.target
!== this.$element
[ 0 ] ) {
6473 this.$focusOwner
.focus();
6478 * Handle mouse down events.
6481 * @param {jQuery.Event} e Mouse down event
6483 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
6486 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
6487 this.togglePressed( true );
6488 item
= this.findTargetItem( e
);
6489 if ( item
&& item
.isSelectable() ) {
6490 this.pressItem( item
);
6491 this.selecting
= item
;
6492 this.getElementDocument().addEventListener( 'mouseup', this.onDocumentMouseUpHandler
, true );
6493 this.getElementDocument().addEventListener( 'mousemove', this.onDocumentMouseMoveHandler
, true );
6500 * Handle document mouse up events.
6503 * @param {MouseEvent} e Mouse up event
6505 OO
.ui
.SelectWidget
.prototype.onDocumentMouseUp = function ( e
) {
6508 this.togglePressed( false );
6509 if ( !this.selecting
) {
6510 item
= this.findTargetItem( e
);
6511 if ( item
&& item
.isSelectable() ) {
6512 this.selecting
= item
;
6515 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
&& this.selecting
) {
6516 this.pressItem( null );
6517 this.chooseItem( this.selecting
);
6518 this.selecting
= null;
6521 this.getElementDocument().removeEventListener( 'mouseup', this.onDocumentMouseUpHandler
, true );
6522 this.getElementDocument().removeEventListener( 'mousemove', this.onDocumentMouseMoveHandler
, true );
6527 // Deprecated alias since 0.28.3
6528 OO
.ui
.SelectWidget
.prototype.onMouseUp = function () {
6529 OO
.ui
.warnDeprecation( 'onMouseUp is deprecated, use onDocumentMouseUp instead' );
6530 this.onDocumentMouseUp
.apply( this, arguments
);
6534 * Handle document mouse move events.
6537 * @param {MouseEvent} e Mouse move event
6539 OO
.ui
.SelectWidget
.prototype.onDocumentMouseMove = function ( e
) {
6542 if ( !this.isDisabled() && this.pressed
) {
6543 item
= this.findTargetItem( e
);
6544 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
6545 this.pressItem( item
);
6546 this.selecting
= item
;
6551 // Deprecated alias since 0.28.3
6552 OO
.ui
.SelectWidget
.prototype.onMouseMove = function () {
6553 OO
.ui
.warnDeprecation( 'onMouseMove is deprecated, use onDocumentMouseMove instead' );
6554 this.onDocumentMouseMove
.apply( this, arguments
);
6558 * Handle mouse over events.
6561 * @param {jQuery.Event} e Mouse over event
6563 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
6565 if ( this.blockMouseOverEvents
) {
6568 if ( !this.isDisabled() ) {
6569 item
= this.findTargetItem( e
);
6570 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
6576 * Handle mouse leave events.
6579 * @param {jQuery.Event} e Mouse over event
6581 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
6582 if ( !this.isDisabled() ) {
6583 this.highlightItem( null );
6589 * Handle document key down events.
6592 * @param {KeyboardEvent} e Key down event
6594 OO
.ui
.SelectWidget
.prototype.onDocumentKeyDown = function ( e
) {
6597 currentItem
= this.findHighlightedItem() || this.findSelectedItem();
6599 if ( !this.isDisabled() && this.isVisible() ) {
6600 switch ( e
.keyCode
) {
6601 case OO
.ui
.Keys
.ENTER
:
6602 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
6603 // Was only highlighted, now let's select it. No-op if already selected.
6604 this.chooseItem( currentItem
);
6609 case OO
.ui
.Keys
.LEFT
:
6610 this.clearKeyPressBuffer();
6611 nextItem
= this.findRelativeSelectableItem( currentItem
, -1 );
6614 case OO
.ui
.Keys
.DOWN
:
6615 case OO
.ui
.Keys
.RIGHT
:
6616 this.clearKeyPressBuffer();
6617 nextItem
= this.findRelativeSelectableItem( currentItem
, 1 );
6620 case OO
.ui
.Keys
.ESCAPE
:
6621 case OO
.ui
.Keys
.TAB
:
6622 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
6623 currentItem
.setHighlighted( false );
6625 this.unbindDocumentKeyDownListener();
6626 this.unbindDocumentKeyPressListener();
6627 // Don't prevent tabbing away / defocusing
6633 if ( nextItem
.constructor.static.highlightable
) {
6634 this.highlightItem( nextItem
);
6636 this.chooseItem( nextItem
);
6638 this.scrollItemIntoView( nextItem
);
6643 e
.stopPropagation();
6648 // Deprecated alias since 0.28.3
6649 OO
.ui
.SelectWidget
.prototype.onKeyDown = function () {
6650 OO
.ui
.warnDeprecation( 'onKeyDown is deprecated, use onDocumentKeyDown instead' );
6651 this.onDocumentKeyDown
.apply( this, arguments
);
6655 * Bind document key down listener.
6659 OO
.ui
.SelectWidget
.prototype.bindDocumentKeyDownListener = function () {
6660 this.getElementDocument().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
6663 // Deprecated alias since 0.28.3
6664 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
6665 OO
.ui
.warnDeprecation( 'bindKeyDownListener is deprecated, use bindDocumentKeyDownListener instead' );
6666 this.bindDocumentKeyDownListener
.apply( this, arguments
);
6670 * Unbind document key down listener.
6674 OO
.ui
.SelectWidget
.prototype.unbindDocumentKeyDownListener = function () {
6675 this.getElementDocument().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
6678 // Deprecated alias since 0.28.3
6679 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
6680 OO
.ui
.warnDeprecation( 'unbindKeyDownListener is deprecated, use unbindDocumentKeyDownListener instead' );
6681 this.unbindDocumentKeyDownListener
.apply( this, arguments
);
6685 * Scroll item into view, preventing spurious mouse highlight actions from happening.
6687 * @param {OO.ui.OptionWidget} item Item to scroll into view
6689 OO
.ui
.SelectWidget
.prototype.scrollItemIntoView = function ( item
) {
6691 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling
6692 // and around 100-150 ms after it is finished.
6693 this.blockMouseOverEvents
++;
6694 item
.scrollElementIntoView().done( function () {
6695 setTimeout( function () {
6696 widget
.blockMouseOverEvents
--;
6702 * Clear the key-press buffer
6706 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
6707 if ( this.keyPressBufferTimer
) {
6708 clearTimeout( this.keyPressBufferTimer
);
6709 this.keyPressBufferTimer
= null;
6711 this.keyPressBuffer
= '';
6715 * Handle key press events.
6718 * @param {KeyboardEvent} e Key press event
6720 OO
.ui
.SelectWidget
.prototype.onDocumentKeyPress = function ( e
) {
6721 var c
, filter
, item
;
6723 if ( !e
.charCode
) {
6724 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
6725 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
6730 if ( String
.fromCodePoint
) {
6731 c
= String
.fromCodePoint( e
.charCode
);
6733 c
= String
.fromCharCode( e
.charCode
);
6736 if ( this.keyPressBufferTimer
) {
6737 clearTimeout( this.keyPressBufferTimer
);
6739 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
6741 item
= this.findHighlightedItem() || this.findSelectedItem();
6743 if ( this.keyPressBuffer
=== c
) {
6744 // Common (if weird) special case: typing "xxxx" will cycle through all
6745 // the items beginning with "x".
6747 item
= this.findRelativeSelectableItem( item
, 1 );
6750 this.keyPressBuffer
+= c
;
6753 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
6754 if ( !item
|| !filter( item
) ) {
6755 item
= this.findRelativeSelectableItem( item
, 1, filter
);
6758 if ( this.isVisible() && item
.constructor.static.highlightable
) {
6759 this.highlightItem( item
);
6761 this.chooseItem( item
);
6763 this.scrollItemIntoView( item
);
6767 e
.stopPropagation();
6770 // Deprecated alias since 0.28.3
6771 OO
.ui
.SelectWidget
.prototype.onKeyPress = function () {
6772 OO
.ui
.warnDeprecation( 'onKeyPress is deprecated, use onDocumentKeyPress instead' );
6773 this.onDocumentKeyPress
.apply( this, arguments
);
6777 * Get a matcher for the specific string
6780 * @param {string} s String to match against items
6781 * @param {boolean} [exact=false] Only accept exact matches
6782 * @return {Function} function ( OO.ui.OptionWidget ) => boolean
6784 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
, exact
) {
6787 if ( s
.normalize
) {
6790 s
= exact
? s
.trim() : s
.replace( /^\s+/, '' );
6791 re
= '^\\s*' + s
.replace( /([\\{}()|.?*+\-^$[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
6795 re
= new RegExp( re
, 'i' );
6796 return function ( item
) {
6797 var matchText
= item
.getMatchText();
6798 if ( matchText
.normalize
) {
6799 matchText
= matchText
.normalize();
6801 return re
.test( matchText
);
6806 * Bind document key press listener.
6810 OO
.ui
.SelectWidget
.prototype.bindDocumentKeyPressListener = function () {
6811 this.getElementDocument().addEventListener( 'keypress', this.onDocumentKeyPressHandler
, true );
6814 // Deprecated alias since 0.28.3
6815 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
6816 OO
.ui
.warnDeprecation( 'bindKeyPressListener is deprecated, use bindDocumentKeyPressListener instead' );
6817 this.bindDocumentKeyPressListener
.apply( this, arguments
);
6821 * Unbind document key down listener.
6823 * If you override this, be sure to call this.clearKeyPressBuffer() from your
6828 OO
.ui
.SelectWidget
.prototype.unbindDocumentKeyPressListener = function () {
6829 this.getElementDocument().removeEventListener( 'keypress', this.onDocumentKeyPressHandler
, true );
6830 this.clearKeyPressBuffer();
6833 // Deprecated alias since 0.28.3
6834 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
6835 OO
.ui
.warnDeprecation( 'unbindKeyPressListener is deprecated, use unbindDocumentKeyPressListener instead' );
6836 this.unbindDocumentKeyPressListener
.apply( this, arguments
);
6840 * Visibility change handler
6843 * @param {boolean} visible
6845 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
6847 this.clearKeyPressBuffer();
6852 * Get the closest item to a jQuery.Event.
6855 * @param {jQuery.Event} e
6856 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
6858 OO
.ui
.SelectWidget
.prototype.findTargetItem = function ( e
) {
6859 var $option
= $( e
.target
).closest( '.oo-ui-optionWidget' );
6860 if ( !$option
.closest( '.oo-ui-selectWidget' ).is( this.$element
) ) {
6863 return $option
.data( 'oo-ui-optionWidget' ) || null;
6867 * Find selected item.
6869 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
6871 OO
.ui
.SelectWidget
.prototype.findSelectedItem = function () {
6874 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6875 if ( this.items
[ i
].isSelected() ) {
6876 return this.items
[ i
];
6883 * Find highlighted item.
6885 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
6887 OO
.ui
.SelectWidget
.prototype.findHighlightedItem = function () {
6890 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6891 if ( this.items
[ i
].isHighlighted() ) {
6892 return this.items
[ i
];
6899 * Toggle pressed state.
6901 * Press is a state that occurs when a user mouses down on an item, but
6902 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
6903 * until the user releases the mouse.
6905 * @param {boolean} pressed An option is being pressed
6907 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
6908 if ( pressed
=== undefined ) {
6909 pressed
= !this.pressed
;
6911 if ( pressed
!== this.pressed
) {
6913 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
6914 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
6915 this.pressed
= pressed
;
6920 * Highlight an option. If the `item` param is omitted, no options will be highlighted
6921 * and any existing highlight will be removed. The highlight is mutually exclusive.
6923 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
6927 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
6928 var i
, len
, highlighted
,
6931 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6932 highlighted
= this.items
[ i
] === item
;
6933 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
6934 this.items
[ i
].setHighlighted( highlighted
);
6940 this.$focusOwner
.attr( 'aria-activedescendant', item
.getElementId() );
6942 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
6944 this.emit( 'highlight', item
);
6951 * Fetch an item by its label.
6953 * @param {string} label Label of the item to select.
6954 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
6955 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
6957 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
6959 len
= this.items
.length
,
6960 filter
= this.getItemMatcher( label
, true );
6962 for ( i
= 0; i
< len
; i
++ ) {
6963 item
= this.items
[ i
];
6964 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
6971 filter
= this.getItemMatcher( label
, false );
6972 for ( i
= 0; i
< len
; i
++ ) {
6973 item
= this.items
[ i
];
6974 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
6990 * Programmatically select an option by its label. If the item does not exist,
6991 * all options will be deselected.
6993 * @param {string} [label] Label of the item to select.
6994 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
6998 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
6999 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
7000 if ( label
=== undefined || !itemFromLabel
) {
7001 return this.selectItem();
7003 return this.selectItem( itemFromLabel
);
7007 * Programmatically select an option by its data. If the `data` parameter is omitted,
7008 * or if the item does not exist, all options will be deselected.
7010 * @param {Object|string} [data] Value of the item to select, omit to deselect all
7014 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
7015 var itemFromData
= this.findItemFromData( data
);
7016 if ( data
=== undefined || !itemFromData
) {
7017 return this.selectItem();
7019 return this.selectItem( itemFromData
);
7023 * Programmatically select an option by its reference. If the `item` parameter is omitted,
7024 * all options will be deselected.
7026 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
7030 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
7031 var i
, len
, selected
,
7034 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
7035 selected
= this.items
[ i
] === item
;
7036 if ( this.items
[ i
].isSelected() !== selected
) {
7037 this.items
[ i
].setSelected( selected
);
7042 if ( item
&& !item
.constructor.static.highlightable
) {
7044 this.$focusOwner
.attr( 'aria-activedescendant', item
.getElementId() );
7046 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
7049 this.emit( 'select', item
);
7058 * Press is a state that occurs when a user mouses down on an item, but has not
7059 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
7060 * releases the mouse.
7062 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
7066 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
7067 var i
, len
, pressed
,
7070 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
7071 pressed
= this.items
[ i
] === item
;
7072 if ( this.items
[ i
].isPressed() !== pressed
) {
7073 this.items
[ i
].setPressed( pressed
);
7078 this.emit( 'press', item
);
7087 * Note that ‘choose’ should never be modified programmatically. A user can choose
7088 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
7089 * use the #selectItem method.
7091 * This method is identical to #selectItem, but may vary in subclasses that take additional action
7092 * when users choose an item with the keyboard or mouse.
7094 * @param {OO.ui.OptionWidget} item Item to choose
7098 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
7100 this.selectItem( item
);
7101 this.emit( 'choose', item
);
7108 * Find an option by its position relative to the specified item (or to the start of the option array,
7109 * if item is `null`). The direction in which to search through the option array is specified with a
7110 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
7111 * `null` if there are no options in the array.
7113 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
7114 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
7115 * @param {Function} [filter] Only consider items for which this function returns
7116 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
7117 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
7119 OO
.ui
.SelectWidget
.prototype.findRelativeSelectableItem = function ( item
, direction
, filter
) {
7120 var currentIndex
, nextIndex
, i
,
7121 increase
= direction
> 0 ? 1 : -1,
7122 len
= this.items
.length
;
7124 if ( item
instanceof OO
.ui
.OptionWidget
) {
7125 currentIndex
= this.items
.indexOf( item
);
7126 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
7128 // If no item is selected and moving forward, start at the beginning.
7129 // If moving backward, start at the end.
7130 nextIndex
= direction
> 0 ? 0 : len
- 1;
7133 for ( i
= 0; i
< len
; i
++ ) {
7134 item
= this.items
[ nextIndex
];
7136 item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() &&
7137 ( !filter
|| filter( item
) )
7141 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
7147 * Find the next selectable item or `null` if there are no selectable items.
7148 * Disabled options and menu-section markers and breaks are not selectable.
7150 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
7152 OO
.ui
.SelectWidget
.prototype.findFirstSelectableItem = function () {
7153 return this.findRelativeSelectableItem( null, 1 );
7157 * Add an array of options to the select. Optionally, an index number can be used to
7158 * specify an insertion point.
7160 * @param {OO.ui.OptionWidget[]} items Items to add
7161 * @param {number} [index] Index to insert items after
7165 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
7167 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
7169 // Always provide an index, even if it was omitted
7170 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
7176 * Remove the specified array of options from the select. Options will be detached
7177 * from the DOM, not removed, so they can be reused later. To remove all options from
7178 * the select, you may wish to use the #clearItems method instead.
7180 * @param {OO.ui.OptionWidget[]} items Items to remove
7184 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
7187 // Deselect items being removed
7188 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
7190 if ( item
.isSelected() ) {
7191 this.selectItem( null );
7196 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
7198 this.emit( 'remove', items
);
7204 * Clear all options from the select. Options will be detached from the DOM, not removed,
7205 * so that they can be reused later. To remove a subset of options from the select, use
7206 * the #removeItems method.
7211 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
7212 var items
= this.items
.slice();
7215 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
7218 this.selectItem( null );
7220 this.emit( 'remove', items
);
7226 * Set the DOM element which has focus while the user is interacting with this SelectWidget.
7228 * Currently this is just used to set `aria-activedescendant` on it.
7231 * @param {jQuery} $focusOwner
7233 OO
.ui
.SelectWidget
.prototype.setFocusOwner = function ( $focusOwner
) {
7234 this.$focusOwner
= $focusOwner
;
7238 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
7239 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
7240 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
7241 * options. For more information about options and selects, please see the
7242 * [OOUI documentation on MediaWiki][1].
7245 * // Decorated options in a select widget
7246 * var select = new OO.ui.SelectWidget( {
7248 * new OO.ui.DecoratedOptionWidget( {
7250 * label: 'Option with icon',
7253 * new OO.ui.DecoratedOptionWidget( {
7255 * label: 'Option with indicator',
7260 * $( 'body' ).append( select.$element );
7262 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7265 * @extends OO.ui.OptionWidget
7266 * @mixins OO.ui.mixin.IconElement
7267 * @mixins OO.ui.mixin.IndicatorElement
7270 * @param {Object} [config] Configuration options
7272 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
7273 // Parent constructor
7274 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
7276 // Mixin constructors
7277 OO
.ui
.mixin
.IconElement
.call( this, config
);
7278 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
7282 .addClass( 'oo-ui-decoratedOptionWidget' )
7283 .prepend( this.$icon
)
7284 .append( this.$indicator
);
7289 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
7290 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
7291 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
7294 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
7295 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
7296 * the [OOUI documentation on MediaWiki] [1] for more information.
7298 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
7301 * @extends OO.ui.DecoratedOptionWidget
7304 * @param {Object} [config] Configuration options
7306 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
7307 // Parent constructor
7308 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
7311 this.checkIcon
= new OO
.ui
.IconWidget( {
7313 classes
: [ 'oo-ui-menuOptionWidget-checkIcon' ]
7318 .prepend( this.checkIcon
.$element
)
7319 .addClass( 'oo-ui-menuOptionWidget' );
7324 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
7326 /* Static Properties */
7332 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
7335 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
7336 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
7339 * var myDropdown = new OO.ui.DropdownWidget( {
7342 * new OO.ui.MenuSectionOptionWidget( {
7345 * new OO.ui.MenuOptionWidget( {
7347 * label: 'Welsh Corgi'
7349 * new OO.ui.MenuOptionWidget( {
7351 * label: 'Standard Poodle'
7353 * new OO.ui.MenuSectionOptionWidget( {
7356 * new OO.ui.MenuOptionWidget( {
7363 * $( 'body' ).append( myDropdown.$element );
7366 * @extends OO.ui.DecoratedOptionWidget
7369 * @param {Object} [config] Configuration options
7371 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
7372 // Parent constructor
7373 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
7376 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' )
7377 .removeAttr( 'role aria-selected' );
7382 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
7384 /* Static Properties */
7390 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
7396 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
7399 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
7400 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
7401 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
7402 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
7403 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
7404 * and customized to be opened, closed, and displayed as needed.
7406 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
7407 * mouse outside the menu.
7409 * Menus also have support for keyboard interaction:
7411 * - Enter/Return key: choose and select a menu option
7412 * - Up-arrow key: highlight the previous menu option
7413 * - Down-arrow key: highlight the next menu option
7414 * - Esc key: hide the menu
7416 * Unlike most widgets, MenuSelectWidget is initially hidden and must be shown by calling #toggle.
7418 * Please see the [OOUI documentation on MediaWiki][1] for more information.
7419 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7422 * @extends OO.ui.SelectWidget
7423 * @mixins OO.ui.mixin.ClippableElement
7424 * @mixins OO.ui.mixin.FloatableElement
7427 * @param {Object} [config] Configuration options
7428 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
7429 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
7430 * and {@link OO.ui.mixin.LookupElement LookupElement}
7431 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
7432 * the text the user types. This config is used by {@link OO.ui.TagMultiselectWidget TagMultiselectWidget}
7433 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
7434 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
7435 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
7436 * that button, unless the button (or its parent widget) is passed in here.
7437 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
7438 * @cfg {jQuery} [$autoCloseIgnore] If these elements are clicked, don't auto-hide the menu.
7439 * @cfg {boolean} [hideOnChoose=true] Hide the menu when the user chooses an option.
7440 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
7441 * @cfg {boolean} [highlightOnFilter] Highlight the first result when filtering
7442 * @cfg {number} [width] Width of the menu
7444 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
7445 // Configuration initialization
7446 config
= config
|| {};
7448 // Parent constructor
7449 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
7451 // Mixin constructors
7452 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
7453 OO
.ui
.mixin
.FloatableElement
.call( this, config
);
7455 // Initial vertical positions other than 'center' will result in
7456 // the menu being flipped if there is not enough space in the container.
7457 // Store the original position so we know what to reset to.
7458 this.originalVerticalPosition
= this.verticalPosition
;
7461 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
7462 this.hideOnChoose
= config
.hideOnChoose
=== undefined || !!config
.hideOnChoose
;
7463 this.filterFromInput
= !!config
.filterFromInput
;
7464 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
7465 this.$widget
= config
.widget
? config
.widget
.$element
: null;
7466 this.$autoCloseIgnore
= config
.$autoCloseIgnore
|| $( [] );
7467 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
7468 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
7469 this.highlightOnFilter
= !!config
.highlightOnFilter
;
7470 this.width
= config
.width
;
7473 this.$element
.addClass( 'oo-ui-menuSelectWidget' );
7474 if ( config
.widget
) {
7475 this.setFocusOwner( config
.widget
.$tabIndexed
);
7478 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
7479 // that reference properties not initialized at that time of parent class construction
7480 // TODO: Find a better way to handle post-constructor setup
7481 this.visible
= false;
7482 this.$element
.addClass( 'oo-ui-element-hidden' );
7487 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
7488 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
7489 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.FloatableElement
);
7496 * The menu is ready: it is visible and has been positioned and clipped.
7499 /* Static properties */
7502 * Positions to flip to if there isn't room in the container for the
7503 * menu in a specific direction.
7505 * @property {Object.<string,string>}
7507 OO
.ui
.MenuSelectWidget
.static.flippedPositions
= {
7517 * Handles document mouse down events.
7520 * @param {MouseEvent} e Mouse down event
7522 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
7526 this.$element
.add( this.$widget
).add( this.$autoCloseIgnore
).get(),
7531 this.toggle( false );
7538 OO
.ui
.MenuSelectWidget
.prototype.onDocumentKeyDown = function ( e
) {
7539 var currentItem
= this.findHighlightedItem() || this.findSelectedItem();
7541 if ( !this.isDisabled() && this.isVisible() ) {
7542 switch ( e
.keyCode
) {
7543 case OO
.ui
.Keys
.LEFT
:
7544 case OO
.ui
.Keys
.RIGHT
:
7545 // Do nothing if a text field is associated, arrow keys will be handled natively
7546 if ( !this.$input
) {
7547 OO
.ui
.MenuSelectWidget
.parent
.prototype.onDocumentKeyDown
.call( this, e
);
7550 case OO
.ui
.Keys
.ESCAPE
:
7551 case OO
.ui
.Keys
.TAB
:
7552 if ( currentItem
) {
7553 currentItem
.setHighlighted( false );
7555 this.toggle( false );
7556 // Don't prevent tabbing away, prevent defocusing
7557 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
7559 e
.stopPropagation();
7563 OO
.ui
.MenuSelectWidget
.parent
.prototype.onDocumentKeyDown
.call( this, e
);
7570 * Update menu item visibility and clipping after input changes (if filterFromInput is enabled)
7571 * or after items were added/removed (always).
7575 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
7576 var i
, item
, items
, visible
, section
, sectionEmpty
, filter
, exactFilter
,
7578 len
= this.items
.length
,
7579 showAll
= !this.isVisible(),
7582 if ( this.$input
&& this.filterFromInput
) {
7583 filter
= showAll
? null : this.getItemMatcher( this.$input
.val() );
7584 exactFilter
= this.getItemMatcher( this.$input
.val(), true );
7585 // Hide non-matching options, and also hide section headers if all options
7586 // in their section are hidden.
7587 for ( i
= 0; i
< len
; i
++ ) {
7588 item
= this.items
[ i
];
7589 if ( item
instanceof OO
.ui
.MenuSectionOptionWidget
) {
7591 // If the previous section was empty, hide its header
7592 section
.toggle( showAll
|| !sectionEmpty
);
7595 sectionEmpty
= true;
7596 } else if ( item
instanceof OO
.ui
.OptionWidget
) {
7597 visible
= showAll
|| filter( item
);
7598 exactMatch
= exactMatch
|| exactFilter( item
);
7599 anyVisible
= anyVisible
|| visible
;
7600 sectionEmpty
= sectionEmpty
&& !visible
;
7601 item
.toggle( visible
);
7604 // Process the final section
7606 section
.toggle( showAll
|| !sectionEmpty
);
7609 if ( anyVisible
&& this.items
.length
&& !exactMatch
) {
7610 this.scrollItemIntoView( this.items
[ 0 ] );
7613 this.$element
.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible
);
7615 if ( this.highlightOnFilter
) {
7616 // Highlight the first item on the list
7618 items
= this.getItems();
7619 for ( i
= 0; i
< items
.length
; i
++ ) {
7620 if ( items
[ i
].isVisible() ) {
7625 this.highlightItem( item
);
7630 // Reevaluate clipping
7637 OO
.ui
.MenuSelectWidget
.prototype.bindDocumentKeyDownListener = function () {
7638 if ( this.$input
) {
7639 this.$input
.on( 'keydown', this.onDocumentKeyDownHandler
);
7641 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindDocumentKeyDownListener
.call( this );
7648 OO
.ui
.MenuSelectWidget
.prototype.unbindDocumentKeyDownListener = function () {
7649 if ( this.$input
) {
7650 this.$input
.off( 'keydown', this.onDocumentKeyDownHandler
);
7652 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindDocumentKeyDownListener
.call( this );
7659 OO
.ui
.MenuSelectWidget
.prototype.bindDocumentKeyPressListener = function () {
7660 if ( this.$input
) {
7661 if ( this.filterFromInput
) {
7662 this.$input
.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
7663 this.updateItemVisibility();
7666 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindDocumentKeyPressListener
.call( this );
7673 OO
.ui
.MenuSelectWidget
.prototype.unbindDocumentKeyPressListener = function () {
7674 if ( this.$input
) {
7675 if ( this.filterFromInput
) {
7676 this.$input
.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
7677 this.updateItemVisibility();
7680 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindDocumentKeyPressListener
.call( this );
7687 * When a user chooses an item, the menu is closed, unless the hideOnChoose config option is set to false.
7689 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
7690 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
7692 * @param {OO.ui.OptionWidget} item Item to choose
7695 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
7696 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
7697 if ( this.hideOnChoose
) {
7698 this.toggle( false );
7706 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
7708 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
7710 this.updateItemVisibility();
7718 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
7720 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
7722 this.updateItemVisibility();
7730 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
7732 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
7734 this.updateItemVisibility();
7740 * Toggle visibility of the menu. The menu is initially hidden and must be shown by calling
7741 * `.toggle( true )` after its #$element is attached to the DOM.
7743 * Do not show the menu while it is not attached to the DOM. The calculations required to display
7744 * it in the right place and with the right dimensions only work correctly while it is attached.
7745 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
7746 * strictly enforced, so currently it only generates a warning in the browser console.
7751 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
7752 var change
, originalHeight
, flippedHeight
;
7754 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
7755 change
= visible
!== this.isVisible();
7757 if ( visible
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
7758 OO
.ui
.warnDeprecation( 'MenuSelectWidget#toggle: Before calling this method, the menu must be attached to the DOM.' );
7759 this.warnedUnattached
= true;
7762 if ( change
&& visible
) {
7763 // Reset position before showing the popup again. It's possible we no longer need to flip
7764 // (e.g. if the user scrolled).
7765 this.setVerticalPosition( this.originalVerticalPosition
);
7769 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
7775 this.setIdealSize( this.width
);
7776 } else if ( this.$floatableContainer
) {
7777 this.$clippable
.css( 'width', 'auto' );
7779 this.$floatableContainer
[ 0 ].offsetWidth
> this.$clippable
[ 0 ].offsetWidth
?
7780 // Dropdown is smaller than handle so expand to width
7781 this.$floatableContainer
[ 0 ].offsetWidth
:
7782 // Dropdown is larger than handle so auto size
7785 this.$clippable
.css( 'width', '' );
7788 this.togglePositioning( !!this.$floatableContainer
);
7789 this.toggleClipping( true );
7791 this.bindDocumentKeyDownListener();
7792 this.bindDocumentKeyPressListener();
7795 ( this.isClippedVertically() || this.isFloatableOutOfView() ) &&
7796 this.originalVerticalPosition
!== 'center'
7798 // If opening the menu in one direction causes it to be clipped, flip it
7799 originalHeight
= this.$element
.height();
7800 this.setVerticalPosition(
7801 this.constructor.static.flippedPositions
[ this.originalVerticalPosition
]
7803 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
7804 // If flipping also causes it to be clipped, open in whichever direction
7805 // we have more space
7806 flippedHeight
= this.$element
.height();
7807 if ( originalHeight
> flippedHeight
) {
7808 this.setVerticalPosition( this.originalVerticalPosition
);
7812 // Note that we do not flip the menu's opening direction if the clipping changes
7813 // later (e.g. after the user scrolls), that seems like it would be annoying
7815 this.$focusOwner
.attr( 'aria-expanded', 'true' );
7817 if ( this.findSelectedItem() ) {
7818 this.$focusOwner
.attr( 'aria-activedescendant', this.findSelectedItem().getElementId() );
7819 this.findSelectedItem().scrollElementIntoView( { duration
: 0 } );
7823 if ( this.autoHide
) {
7824 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
7827 this.emit( 'ready' );
7829 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
7830 this.unbindDocumentKeyDownListener();
7831 this.unbindDocumentKeyPressListener();
7832 this.$focusOwner
.attr( 'aria-expanded', 'false' );
7833 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
7834 this.togglePositioning( false );
7835 this.toggleClipping( false );
7843 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
7844 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
7845 * users can interact with it.
7847 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7848 * OO.ui.DropdownInputWidget instead.
7851 * // Example: A DropdownWidget with a menu that contains three options
7852 * var dropDown = new OO.ui.DropdownWidget( {
7853 * label: 'Dropdown menu: Select a menu option',
7856 * new OO.ui.MenuOptionWidget( {
7860 * new OO.ui.MenuOptionWidget( {
7864 * new OO.ui.MenuOptionWidget( {
7872 * $( 'body' ).append( dropDown.$element );
7874 * dropDown.getMenu().selectItemByData( 'b' );
7876 * dropDown.getMenu().findSelectedItem().getData(); // returns 'b'
7878 * For more information, please see the [OOUI documentation on MediaWiki] [1].
7880 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
7883 * @extends OO.ui.Widget
7884 * @mixins OO.ui.mixin.IconElement
7885 * @mixins OO.ui.mixin.IndicatorElement
7886 * @mixins OO.ui.mixin.LabelElement
7887 * @mixins OO.ui.mixin.TitledElement
7888 * @mixins OO.ui.mixin.TabIndexedElement
7891 * @param {Object} [config] Configuration options
7892 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.MenuSelectWidget menu select widget}
7893 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
7894 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
7895 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
7896 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
7898 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
7899 // Configuration initialization
7900 config
= $.extend( { indicator
: 'down' }, config
);
7902 // Parent constructor
7903 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
7905 // Properties (must be set before TabIndexedElement constructor call)
7906 this.$handle
= $( '<span>' );
7907 this.$overlay
= ( config
.$overlay
=== true ? OO
.ui
.getDefaultOverlay() : config
.$overlay
) || this.$element
;
7909 // Mixin constructors
7910 OO
.ui
.mixin
.IconElement
.call( this, config
);
7911 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
7912 OO
.ui
.mixin
.LabelElement
.call( this, config
);
7913 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
7914 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
7917 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend( {
7919 $floatableContainer
: this.$element
7924 click
: this.onClick
.bind( this ),
7925 keydown
: this.onKeyDown
.bind( this ),
7926 // Hack? Handle type-to-search when menu is not expanded and not handling its own events
7927 keypress
: this.menu
.onDocumentKeyPressHandler
,
7928 blur
: this.menu
.clearKeyPressBuffer
.bind( this.menu
)
7930 this.menu
.connect( this, {
7931 select
: 'onMenuSelect',
7932 toggle
: 'onMenuToggle'
7937 .addClass( 'oo-ui-dropdownWidget-handle' )
7940 'aria-owns': this.menu
.getElementId(),
7941 'aria-autocomplete': 'list'
7943 .append( this.$icon
, this.$label
, this.$indicator
);
7945 .addClass( 'oo-ui-dropdownWidget' )
7946 .append( this.$handle
);
7947 this.$overlay
.append( this.menu
.$element
);
7952 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
7953 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
7954 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
7955 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
7956 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
7957 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
7964 * @return {OO.ui.MenuSelectWidget} Menu of widget
7966 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
7971 * Handles menu select events.
7974 * @param {OO.ui.MenuOptionWidget} item Selected menu item
7976 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
7980 this.setLabel( null );
7984 selectedLabel
= item
.getLabel();
7986 // If the label is a DOM element, clone it, because setLabel will append() it
7987 if ( selectedLabel
instanceof jQuery
) {
7988 selectedLabel
= selectedLabel
.clone();
7991 this.setLabel( selectedLabel
);
7995 * Handle menu toggle events.
7998 * @param {boolean} isVisible Open state of the menu
8000 OO
.ui
.DropdownWidget
.prototype.onMenuToggle = function ( isVisible
) {
8001 this.$element
.toggleClass( 'oo-ui-dropdownWidget-open', isVisible
);
8004 this.$element
.hasClass( 'oo-ui-dropdownWidget-open' ).toString()
8009 * Handle mouse click events.
8012 * @param {jQuery.Event} e Mouse click event
8014 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
8015 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
8022 * Handle key down events.
8025 * @param {jQuery.Event} e Key down event
8027 OO
.ui
.DropdownWidget
.prototype.onKeyDown = function ( e
) {
8029 !this.isDisabled() &&
8031 e
.which
=== OO
.ui
.Keys
.ENTER
||
8033 e
.which
=== OO
.ui
.Keys
.SPACE
&&
8034 // Avoid conflicts with type-to-search, see SelectWidget#onKeyPress.
8035 // Space only closes the menu is the user is not typing to search.
8036 this.menu
.keyPressBuffer
=== ''
8039 !this.menu
.isVisible() &&
8041 e
.which
=== OO
.ui
.Keys
.UP
||
8042 e
.which
=== OO
.ui
.Keys
.DOWN
8053 * RadioOptionWidget is an option widget that looks like a radio button.
8054 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
8055 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8057 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8060 * @extends OO.ui.OptionWidget
8063 * @param {Object} [config] Configuration options
8065 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
8066 // Configuration initialization
8067 config
= config
|| {};
8069 // Properties (must be done before parent constructor which calls #setDisabled)
8070 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
8072 // Parent constructor
8073 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
8076 // Remove implicit role, we're handling it ourselves
8077 this.radio
.$input
.attr( 'role', 'presentation' );
8079 .addClass( 'oo-ui-radioOptionWidget' )
8080 .attr( 'role', 'radio' )
8081 .attr( 'aria-checked', 'false' )
8082 .removeAttr( 'aria-selected' )
8083 .prepend( this.radio
.$element
);
8088 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
8090 /* Static Properties */
8096 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
8102 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
8108 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
8114 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
8121 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
8122 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
8124 this.radio
.setSelected( state
);
8126 .attr( 'aria-checked', state
.toString() )
8127 .removeAttr( 'aria-selected' );
8135 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
8136 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
8138 this.radio
.setDisabled( this.isDisabled() );
8144 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
8145 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
8146 * an interface for adding, removing and selecting options.
8147 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8149 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8150 * OO.ui.RadioSelectInputWidget instead.
8153 * // A RadioSelectWidget with RadioOptions.
8154 * var option1 = new OO.ui.RadioOptionWidget( {
8156 * label: 'Selected radio option'
8159 * var option2 = new OO.ui.RadioOptionWidget( {
8161 * label: 'Unselected radio option'
8164 * var radioSelect=new OO.ui.RadioSelectWidget( {
8165 * items: [ option1, option2 ]
8168 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
8169 * radioSelect.selectItem( option1 );
8171 * $( 'body' ).append( radioSelect.$element );
8173 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8177 * @extends OO.ui.SelectWidget
8178 * @mixins OO.ui.mixin.TabIndexedElement
8181 * @param {Object} [config] Configuration options
8183 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
8184 // Parent constructor
8185 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
8187 // Mixin constructors
8188 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
8192 focus
: this.bindDocumentKeyDownListener
.bind( this ),
8193 blur
: this.unbindDocumentKeyDownListener
.bind( this )
8198 .addClass( 'oo-ui-radioSelectWidget' )
8199 .attr( 'role', 'radiogroup' );
8204 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
8205 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
8208 * MultioptionWidgets are special elements that can be selected and configured with data. The
8209 * data is often unique for each option, but it does not have to be. MultioptionWidgets are used
8210 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
8211 * and examples, please see the [OOUI documentation on MediaWiki][1].
8213 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Multioptions
8216 * @extends OO.ui.Widget
8217 * @mixins OO.ui.mixin.ItemWidget
8218 * @mixins OO.ui.mixin.LabelElement
8221 * @param {Object} [config] Configuration options
8222 * @cfg {boolean} [selected=false] Whether the option is initially selected
8224 OO
.ui
.MultioptionWidget
= function OoUiMultioptionWidget( config
) {
8225 // Configuration initialization
8226 config
= config
|| {};
8228 // Parent constructor
8229 OO
.ui
.MultioptionWidget
.parent
.call( this, config
);
8231 // Mixin constructors
8232 OO
.ui
.mixin
.ItemWidget
.call( this );
8233 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8236 this.selected
= null;
8240 .addClass( 'oo-ui-multioptionWidget' )
8241 .append( this.$label
);
8242 this.setSelected( config
.selected
);
8247 OO
.inheritClass( OO
.ui
.MultioptionWidget
, OO
.ui
.Widget
);
8248 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.ItemWidget
);
8249 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.LabelElement
);
8256 * A change event is emitted when the selected state of the option changes.
8258 * @param {boolean} selected Whether the option is now selected
8264 * Check if the option is selected.
8266 * @return {boolean} Item is selected
8268 OO
.ui
.MultioptionWidget
.prototype.isSelected = function () {
8269 return this.selected
;
8273 * Set the option’s selected state. In general, all modifications to the selection
8274 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
8275 * method instead of this method.
8277 * @param {boolean} [state=false] Select option
8280 OO
.ui
.MultioptionWidget
.prototype.setSelected = function ( state
) {
8282 if ( this.selected
!== state
) {
8283 this.selected
= state
;
8284 this.emit( 'change', state
);
8285 this.$element
.toggleClass( 'oo-ui-multioptionWidget-selected', state
);
8291 * MultiselectWidget allows selecting multiple options from a list.
8293 * For more information about menus and options, please see the [OOUI documentation on MediaWiki][1].
8295 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
8299 * @extends OO.ui.Widget
8300 * @mixins OO.ui.mixin.GroupWidget
8303 * @param {Object} [config] Configuration options
8304 * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
8306 OO
.ui
.MultiselectWidget
= function OoUiMultiselectWidget( config
) {
8307 // Parent constructor
8308 OO
.ui
.MultiselectWidget
.parent
.call( this, config
);
8310 // Configuration initialization
8311 config
= config
|| {};
8313 // Mixin constructors
8314 OO
.ui
.mixin
.GroupWidget
.call( this, config
);
8317 this.aggregate( { change
: 'select' } );
8318 // This is mostly for compatibility with TagMultiselectWidget... normally, 'change' is emitted
8319 // by GroupElement only when items are added/removed
8320 this.connect( this, { select
: [ 'emit', 'change' ] } );
8323 if ( config
.items
) {
8324 this.addItems( config
.items
);
8326 this.$group
.addClass( 'oo-ui-multiselectWidget-group' );
8327 this.$element
.addClass( 'oo-ui-multiselectWidget' )
8328 .append( this.$group
);
8333 OO
.inheritClass( OO
.ui
.MultiselectWidget
, OO
.ui
.Widget
);
8334 OO
.mixinClass( OO
.ui
.MultiselectWidget
, OO
.ui
.mixin
.GroupWidget
);
8341 * A change event is emitted when the set of items changes, or an item is selected or deselected.
8347 * A select event is emitted when an item is selected or deselected.
8353 * Find options that are selected.
8355 * @return {OO.ui.MultioptionWidget[]} Selected options
8357 OO
.ui
.MultiselectWidget
.prototype.findSelectedItems = function () {
8358 return this.items
.filter( function ( item
) {
8359 return item
.isSelected();
8364 * Find the data of options that are selected.
8366 * @return {Object[]|string[]} Values of selected options
8368 OO
.ui
.MultiselectWidget
.prototype.findSelectedItemsData = function () {
8369 return this.findSelectedItems().map( function ( item
) {
8375 * Select options by reference. Options not mentioned in the `items` array will be deselected.
8377 * @param {OO.ui.MultioptionWidget[]} items Items to select
8380 OO
.ui
.MultiselectWidget
.prototype.selectItems = function ( items
) {
8381 this.items
.forEach( function ( item
) {
8382 var selected
= items
.indexOf( item
) !== -1;
8383 item
.setSelected( selected
);
8389 * Select items by their data. Options not mentioned in the `datas` array will be deselected.
8391 * @param {Object[]|string[]} datas Values of items to select
8394 OO
.ui
.MultiselectWidget
.prototype.selectItemsByData = function ( datas
) {
8397 items
= datas
.map( function ( data
) {
8398 return widget
.findItemFromData( data
);
8400 this.selectItems( items
);
8405 * CheckboxMultioptionWidget is an option widget that looks like a checkbox.
8406 * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
8407 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8409 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8412 * @extends OO.ui.MultioptionWidget
8415 * @param {Object} [config] Configuration options
8417 OO
.ui
.CheckboxMultioptionWidget
= function OoUiCheckboxMultioptionWidget( config
) {
8418 // Configuration initialization
8419 config
= config
|| {};
8421 // Properties (must be done before parent constructor which calls #setDisabled)
8422 this.checkbox
= new OO
.ui
.CheckboxInputWidget();
8424 // Parent constructor
8425 OO
.ui
.CheckboxMultioptionWidget
.parent
.call( this, config
);
8428 this.checkbox
.on( 'change', this.onCheckboxChange
.bind( this ) );
8429 this.$element
.on( 'keydown', this.onKeyDown
.bind( this ) );
8433 .addClass( 'oo-ui-checkboxMultioptionWidget' )
8434 .prepend( this.checkbox
.$element
);
8439 OO
.inheritClass( OO
.ui
.CheckboxMultioptionWidget
, OO
.ui
.MultioptionWidget
);
8441 /* Static Properties */
8447 OO
.ui
.CheckboxMultioptionWidget
.static.tagName
= 'label';
8452 * Handle checkbox selected state change.
8456 OO
.ui
.CheckboxMultioptionWidget
.prototype.onCheckboxChange = function () {
8457 this.setSelected( this.checkbox
.isSelected() );
8463 OO
.ui
.CheckboxMultioptionWidget
.prototype.setSelected = function ( state
) {
8464 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setSelected
.call( this, state
);
8465 this.checkbox
.setSelected( state
);
8472 OO
.ui
.CheckboxMultioptionWidget
.prototype.setDisabled = function ( disabled
) {
8473 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
8474 this.checkbox
.setDisabled( this.isDisabled() );
8481 OO
.ui
.CheckboxMultioptionWidget
.prototype.focus = function () {
8482 this.checkbox
.focus();
8486 * Handle key down events.
8489 * @param {jQuery.Event} e
8491 OO
.ui
.CheckboxMultioptionWidget
.prototype.onKeyDown = function ( e
) {
8493 element
= this.getElementGroup(),
8496 if ( e
.keyCode
=== OO
.ui
.Keys
.LEFT
|| e
.keyCode
=== OO
.ui
.Keys
.UP
) {
8497 nextItem
= element
.getRelativeFocusableItem( this, -1 );
8498 } else if ( e
.keyCode
=== OO
.ui
.Keys
.RIGHT
|| e
.keyCode
=== OO
.ui
.Keys
.DOWN
) {
8499 nextItem
= element
.getRelativeFocusableItem( this, 1 );
8509 * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
8510 * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
8511 * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
8512 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8514 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8515 * OO.ui.CheckboxMultiselectInputWidget instead.
8518 * // A CheckboxMultiselectWidget with CheckboxMultioptions.
8519 * var option1 = new OO.ui.CheckboxMultioptionWidget( {
8522 * label: 'Selected checkbox'
8525 * var option2 = new OO.ui.CheckboxMultioptionWidget( {
8527 * label: 'Unselected checkbox'
8530 * var multiselect=new OO.ui.CheckboxMultiselectWidget( {
8531 * items: [ option1, option2 ]
8534 * $( 'body' ).append( multiselect.$element );
8536 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8539 * @extends OO.ui.MultiselectWidget
8542 * @param {Object} [config] Configuration options
8544 OO
.ui
.CheckboxMultiselectWidget
= function OoUiCheckboxMultiselectWidget( config
) {
8545 // Parent constructor
8546 OO
.ui
.CheckboxMultiselectWidget
.parent
.call( this, config
);
8549 this.$lastClicked
= null;
8552 this.$group
.on( 'click', this.onClick
.bind( this ) );
8556 .addClass( 'oo-ui-checkboxMultiselectWidget' );
8561 OO
.inheritClass( OO
.ui
.CheckboxMultiselectWidget
, OO
.ui
.MultiselectWidget
);
8566 * Get an option by its position relative to the specified item (or to the start of the option array,
8567 * if item is `null`). The direction in which to search through the option array is specified with a
8568 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
8569 * `null` if there are no options in the array.
8571 * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
8572 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
8573 * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items in the select
8575 OO
.ui
.CheckboxMultiselectWidget
.prototype.getRelativeFocusableItem = function ( item
, direction
) {
8576 var currentIndex
, nextIndex
, i
,
8577 increase
= direction
> 0 ? 1 : -1,
8578 len
= this.items
.length
;
8581 currentIndex
= this.items
.indexOf( item
);
8582 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
8584 // If no item is selected and moving forward, start at the beginning.
8585 // If moving backward, start at the end.
8586 nextIndex
= direction
> 0 ? 0 : len
- 1;
8589 for ( i
= 0; i
< len
; i
++ ) {
8590 item
= this.items
[ nextIndex
];
8591 if ( item
&& !item
.isDisabled() ) {
8594 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
8600 * Handle click events on checkboxes.
8602 * @param {jQuery.Event} e
8604 OO
.ui
.CheckboxMultiselectWidget
.prototype.onClick = function ( e
) {
8605 var $options
, lastClickedIndex
, nowClickedIndex
, i
, direction
, wasSelected
, items
,
8606 $lastClicked
= this.$lastClicked
,
8607 $nowClicked
= $( e
.target
).closest( '.oo-ui-checkboxMultioptionWidget' )
8608 .not( '.oo-ui-widget-disabled' );
8610 // Allow selecting multiple options at once by Shift-clicking them
8611 if ( $lastClicked
&& $nowClicked
.length
&& e
.shiftKey
) {
8612 $options
= this.$group
.find( '.oo-ui-checkboxMultioptionWidget' );
8613 lastClickedIndex
= $options
.index( $lastClicked
);
8614 nowClickedIndex
= $options
.index( $nowClicked
);
8615 // If it's the same item, either the user is being silly, or it's a fake event generated by the
8616 // browser. In either case we don't need custom handling.
8617 if ( nowClickedIndex
!== lastClickedIndex
) {
8619 wasSelected
= items
[ nowClickedIndex
].isSelected();
8620 direction
= nowClickedIndex
> lastClickedIndex
? 1 : -1;
8622 // This depends on the DOM order of the items and the order of the .items array being the same.
8623 for ( i
= lastClickedIndex
; i
!== nowClickedIndex
; i
+= direction
) {
8624 if ( !items
[ i
].isDisabled() ) {
8625 items
[ i
].setSelected( !wasSelected
);
8628 // For the now-clicked element, use immediate timeout to allow the browser to do its own
8629 // handling first, then set our value. The order in which events happen is different for
8630 // clicks on the <input> and on the <label> and there are additional fake clicks fired for
8631 // non-click actions that change the checkboxes.
8633 setTimeout( function () {
8634 if ( !items
[ nowClickedIndex
].isDisabled() ) {
8635 items
[ nowClickedIndex
].setSelected( !wasSelected
);
8641 if ( $nowClicked
.length
) {
8642 this.$lastClicked
= $nowClicked
;
8651 OO
.ui
.CheckboxMultiselectWidget
.prototype.focus = function () {
8653 if ( !this.isDisabled() ) {
8654 item
= this.getRelativeFocusableItem( null, 1 );
8665 OO
.ui
.CheckboxMultiselectWidget
.prototype.simulateLabelClick = function () {
8670 * Progress bars visually display the status of an operation, such as a download,
8671 * and can be either determinate or indeterminate:
8673 * - **determinate** process bars show the percent of an operation that is complete.
8675 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
8676 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
8677 * not use percentages.
8679 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
8682 * // Examples of determinate and indeterminate progress bars.
8683 * var progressBar1 = new OO.ui.ProgressBarWidget( {
8686 * var progressBar2 = new OO.ui.ProgressBarWidget();
8688 * // Create a FieldsetLayout to layout progress bars
8689 * var fieldset = new OO.ui.FieldsetLayout;
8690 * fieldset.addItems( [
8691 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
8692 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
8694 * $( 'body' ).append( fieldset.$element );
8697 * @extends OO.ui.Widget
8700 * @param {Object} [config] Configuration options
8701 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
8702 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
8703 * By default, the progress bar is indeterminate.
8705 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
8706 // Configuration initialization
8707 config
= config
|| {};
8709 // Parent constructor
8710 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
8713 this.$bar
= $( '<div>' );
8714 this.progress
= null;
8717 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
8718 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
8721 role
: 'progressbar',
8723 'aria-valuemax': 100
8725 .addClass( 'oo-ui-progressBarWidget' )
8726 .append( this.$bar
);
8731 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
8733 /* Static Properties */
8739 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
8744 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
8746 * @return {number|boolean} Progress percent
8748 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
8749 return this.progress
;
8753 * Set the percent of the process completed or `false` for an indeterminate process.
8755 * @param {number|boolean} progress Progress percent or `false` for indeterminate
8757 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
8758 this.progress
= progress
;
8760 if ( progress
!== false ) {
8761 this.$bar
.css( 'width', this.progress
+ '%' );
8762 this.$element
.attr( 'aria-valuenow', this.progress
);
8764 this.$bar
.css( 'width', '' );
8765 this.$element
.removeAttr( 'aria-valuenow' );
8767 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress
=== false );
8771 * InputWidget is the base class for all input widgets, which
8772 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
8773 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
8774 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
8776 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
8780 * @extends OO.ui.Widget
8781 * @mixins OO.ui.mixin.FlaggedElement
8782 * @mixins OO.ui.mixin.TabIndexedElement
8783 * @mixins OO.ui.mixin.TitledElement
8784 * @mixins OO.ui.mixin.AccessKeyedElement
8787 * @param {Object} [config] Configuration options
8788 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
8789 * @cfg {string} [value=''] The value of the input.
8790 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
8791 * @cfg {string} [inputId] The value of the input’s HTML `id` attribute.
8792 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
8793 * before it is accepted.
8795 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
8796 // Configuration initialization
8797 config
= config
|| {};
8799 // Parent constructor
8800 OO
.ui
.InputWidget
.parent
.call( this, config
);
8803 // See #reusePreInfuseDOM about config.$input
8804 this.$input
= config
.$input
|| this.getInputElement( config
);
8806 this.inputFilter
= config
.inputFilter
;
8808 // Mixin constructors
8809 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
8810 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
8811 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
8812 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$input
} ) );
8815 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
8819 .addClass( 'oo-ui-inputWidget-input' )
8820 .attr( 'name', config
.name
)
8821 .prop( 'disabled', this.isDisabled() );
8823 .addClass( 'oo-ui-inputWidget' )
8824 .append( this.$input
);
8825 this.setValue( config
.value
);
8827 this.setDir( config
.dir
);
8829 if ( config
.inputId
!== undefined ) {
8830 this.setInputId( config
.inputId
);
8836 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
8837 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
8838 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
8839 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
8840 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
8842 /* Static Methods */
8847 OO
.ui
.InputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
8848 config
= OO
.ui
.InputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
8849 // Reusing `$input` lets browsers preserve inputted values across page reloads, see T114134.
8850 config
.$input
= $( node
).find( '.oo-ui-inputWidget-input' );
8857 OO
.ui
.InputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8858 var state
= OO
.ui
.InputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8859 if ( config
.$input
&& config
.$input
.length
) {
8860 state
.value
= config
.$input
.val();
8861 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
8862 state
.focus
= config
.$input
.is( ':focus' );
8872 * A change event is emitted when the value of the input changes.
8874 * @param {string} value
8880 * Get input element.
8882 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
8883 * different circumstances. The element must have a `value` property (like form elements).
8886 * @param {Object} config Configuration options
8887 * @return {jQuery} Input element
8889 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
8890 return $( '<input>' );
8894 * Handle potentially value-changing events.
8897 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
8899 OO
.ui
.InputWidget
.prototype.onEdit = function () {
8901 if ( !this.isDisabled() ) {
8902 // Allow the stack to clear so the value will be updated
8903 setTimeout( function () {
8904 widget
.setValue( widget
.$input
.val() );
8910 * Get the value of the input.
8912 * @return {string} Input value
8914 OO
.ui
.InputWidget
.prototype.getValue = function () {
8915 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
8916 // it, and we won't know unless they're kind enough to trigger a 'change' event.
8917 var value
= this.$input
.val();
8918 if ( this.value
!== value
) {
8919 this.setValue( value
);
8925 * Set the directionality of the input.
8927 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
8930 OO
.ui
.InputWidget
.prototype.setDir = function ( dir
) {
8931 this.$input
.prop( 'dir', dir
);
8936 * Set the value of the input.
8938 * @param {string} value New value
8942 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
8943 value
= this.cleanUpValue( value
);
8944 // Update the DOM if it has changed. Note that with cleanUpValue, it
8945 // is possible for the DOM value to change without this.value changing.
8946 if ( this.$input
.val() !== value
) {
8947 this.$input
.val( value
);
8949 if ( this.value
!== value
) {
8951 this.emit( 'change', this.value
);
8953 // The first time that the value is set (probably while constructing the widget),
8954 // remember it in defaultValue. This property can be later used to check whether
8955 // the value of the input has been changed since it was created.
8956 if ( this.defaultValue
=== undefined ) {
8957 this.defaultValue
= this.value
;
8958 this.$input
[ 0 ].defaultValue
= this.defaultValue
;
8964 * Clean up incoming value.
8966 * Ensures value is a string, and converts undefined and null to empty string.
8969 * @param {string} value Original value
8970 * @return {string} Cleaned up value
8972 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
8973 if ( value
=== undefined || value
=== null ) {
8975 } else if ( this.inputFilter
) {
8976 return this.inputFilter( String( value
) );
8978 return String( value
);
8985 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
8986 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
8987 if ( this.$input
) {
8988 this.$input
.prop( 'disabled', this.isDisabled() );
8994 * Set the 'id' attribute of the `<input>` element.
8996 * @param {string} id
8999 OO
.ui
.InputWidget
.prototype.setInputId = function ( id
) {
9000 this.$input
.attr( 'id', id
);
9007 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
9008 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
9009 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
9010 this.setValue( state
.value
);
9012 if ( state
.focus
) {
9018 * Data widget intended for creating 'hidden'-type inputs.
9021 * @extends OO.ui.Widget
9024 * @param {Object} [config] Configuration options
9025 * @cfg {string} [value=''] The value of the input.
9026 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
9028 OO
.ui
.HiddenInputWidget
= function OoUiHiddenInputWidget( config
) {
9029 // Configuration initialization
9030 config
= $.extend( { value
: '', name
: '' }, config
);
9032 // Parent constructor
9033 OO
.ui
.HiddenInputWidget
.parent
.call( this, config
);
9036 this.$element
.attr( {
9038 value
: config
.value
,
9041 this.$element
.removeAttr( 'aria-disabled' );
9046 OO
.inheritClass( OO
.ui
.HiddenInputWidget
, OO
.ui
.Widget
);
9048 /* Static Properties */
9054 OO
.ui
.HiddenInputWidget
.static.tagName
= 'input';
9057 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
9058 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
9059 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
9060 * HTML `<button>` (the default) or an HTML `<input>` tags. See the
9061 * [OOUI documentation on MediaWiki] [1] for more information.
9064 * // A ButtonInputWidget rendered as an HTML button, the default.
9065 * var button = new OO.ui.ButtonInputWidget( {
9066 * label: 'Input button',
9070 * $( 'body' ).append( button.$element );
9072 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#Button_inputs
9075 * @extends OO.ui.InputWidget
9076 * @mixins OO.ui.mixin.ButtonElement
9077 * @mixins OO.ui.mixin.IconElement
9078 * @mixins OO.ui.mixin.IndicatorElement
9079 * @mixins OO.ui.mixin.LabelElement
9080 * @mixins OO.ui.mixin.TitledElement
9083 * @param {Object} [config] Configuration options
9084 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
9085 * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
9086 * Widgets configured to be an `<input>` do not support {@link #icon icons} and {@link #indicator indicators},
9087 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
9088 * be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
9090 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
9091 // Configuration initialization
9092 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
9094 // See InputWidget#reusePreInfuseDOM about config.$input
9095 if ( config
.$input
) {
9096 config
.$input
.empty();
9099 // Properties (must be set before parent constructor, which calls #setValue)
9100 this.useInputTag
= config
.useInputTag
;
9102 // Parent constructor
9103 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
9105 // Mixin constructors
9106 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
9107 OO
.ui
.mixin
.IconElement
.call( this, config
);
9108 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
9109 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9110 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
9113 if ( !config
.useInputTag
) {
9114 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
9116 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
9121 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
9122 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
9123 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
9124 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
9125 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
9126 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
9128 /* Static Properties */
9134 OO
.ui
.ButtonInputWidget
.static.tagName
= 'span';
9142 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
9144 type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ? config
.type
: 'button';
9145 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
9151 * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
9153 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
9154 * text, or `null` for no label
9157 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
9158 if ( typeof label
=== 'function' ) {
9159 label
= OO
.ui
.resolveMsg( label
);
9162 if ( this.useInputTag
) {
9163 // Discard non-plaintext labels
9164 if ( typeof label
!== 'string' ) {
9168 this.$input
.val( label
);
9171 return OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
9175 * Set the value of the input.
9177 * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
9178 * they do not support {@link #value values}.
9180 * @param {string} value New value
9183 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
9184 if ( !this.useInputTag
) {
9185 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
9193 OO
.ui
.ButtonInputWidget
.prototype.getInputId = function () {
9194 // Disable generating `<label>` elements for buttons. One would very rarely need additional label
9195 // for a button, and it's already a big clickable target, and it causes unexpected rendering.
9200 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
9201 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
9202 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
9203 * alignment. For more information, please see the [OOUI documentation on MediaWiki][1].
9205 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9208 * // An example of selected, unselected, and disabled checkbox inputs
9209 * var checkbox1=new OO.ui.CheckboxInputWidget( {
9213 * var checkbox2=new OO.ui.CheckboxInputWidget( {
9216 * var checkbox3=new OO.ui.CheckboxInputWidget( {
9220 * // Create a fieldset layout with fields for each checkbox.
9221 * var fieldset = new OO.ui.FieldsetLayout( {
9222 * label: 'Checkboxes'
9224 * fieldset.addItems( [
9225 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
9226 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
9227 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
9229 * $( 'body' ).append( fieldset.$element );
9231 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9234 * @extends OO.ui.InputWidget
9237 * @param {Object} [config] Configuration options
9238 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
9240 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
9241 // Configuration initialization
9242 config
= config
|| {};
9244 // Parent constructor
9245 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
9248 this.checkIcon
= new OO
.ui
.IconWidget( {
9250 classes
: [ 'oo-ui-checkboxInputWidget-checkIcon' ]
9255 .addClass( 'oo-ui-checkboxInputWidget' )
9256 // Required for pretty styling in WikimediaUI theme
9257 .append( this.checkIcon
.$element
);
9258 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
9263 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
9265 /* Static Properties */
9271 OO
.ui
.CheckboxInputWidget
.static.tagName
= 'span';
9273 /* Static Methods */
9278 OO
.ui
.CheckboxInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9279 var state
= OO
.ui
.CheckboxInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9280 state
.checked
= config
.$input
.prop( 'checked' );
9290 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
9291 return $( '<input>' ).attr( 'type', 'checkbox' );
9297 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
9299 if ( !this.isDisabled() ) {
9300 // Allow the stack to clear so the value will be updated
9301 setTimeout( function () {
9302 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
9308 * Set selection state of this checkbox.
9310 * @param {boolean} state `true` for selected
9313 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
9315 if ( this.selected
!== state
) {
9316 this.selected
= state
;
9317 this.$input
.prop( 'checked', this.selected
);
9318 this.emit( 'change', this.selected
);
9320 // The first time that the selection state is set (probably while constructing the widget),
9321 // remember it in defaultSelected. This property can be later used to check whether
9322 // the selection state of the input has been changed since it was created.
9323 if ( this.defaultSelected
=== undefined ) {
9324 this.defaultSelected
= this.selected
;
9325 this.$input
[ 0 ].defaultChecked
= this.defaultSelected
;
9331 * Check if this checkbox is selected.
9333 * @return {boolean} Checkbox is selected
9335 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
9336 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
9337 // it, and we won't know unless they're kind enough to trigger a 'change' event.
9338 var selected
= this.$input
.prop( 'checked' );
9339 if ( this.selected
!== selected
) {
9340 this.setSelected( selected
);
9342 return this.selected
;
9348 OO
.ui
.CheckboxInputWidget
.prototype.simulateLabelClick = function () {
9349 if ( !this.isDisabled() ) {
9350 this.$input
.click();
9358 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
9359 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
9360 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
9361 this.setSelected( state
.checked
);
9366 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
9367 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
9368 * of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9369 * more information about input widgets.
9371 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
9372 * are no options. If no `value` configuration option is provided, the first option is selected.
9373 * If you need a state representing no value (no option being selected), use a DropdownWidget.
9375 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
9378 * // Example: A DropdownInputWidget with three options
9379 * var dropdownInput = new OO.ui.DropdownInputWidget( {
9381 * { data: 'a', label: 'First' },
9382 * { data: 'b', label: 'Second'},
9383 * { data: 'c', label: 'Third' }
9386 * $( 'body' ).append( dropdownInput.$element );
9388 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9391 * @extends OO.ui.InputWidget
9394 * @param {Object} [config] Configuration options
9395 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9396 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
9397 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
9398 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
9399 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
9400 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
9402 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
9403 // Configuration initialization
9404 config
= config
|| {};
9406 // Properties (must be done before parent constructor which calls #setDisabled)
9407 this.dropdownWidget
= new OO
.ui
.DropdownWidget( $.extend(
9409 $overlay
: config
.$overlay
9413 // Set up the options before parent constructor, which uses them to validate config.value.
9414 // Use this instead of setOptions() because this.$input is not set up yet.
9415 this.setOptionsData( config
.options
|| [] );
9417 // Parent constructor
9418 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
9421 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
9425 .addClass( 'oo-ui-dropdownInputWidget' )
9426 .append( this.dropdownWidget
.$element
);
9427 this.setTabIndexedElement( this.dropdownWidget
.$tabIndexed
);
9432 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
9440 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
9441 return $( '<select>' );
9445 * Handles menu select events.
9448 * @param {OO.ui.MenuOptionWidget|null} item Selected menu item
9450 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
9451 this.setValue( item
? item
.getData() : '' );
9457 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
9459 value
= this.cleanUpValue( value
);
9460 // Only allow setting values that are actually present in the dropdown
9461 selected
= this.dropdownWidget
.getMenu().findItemFromData( value
) ||
9462 this.dropdownWidget
.getMenu().findFirstSelectableItem();
9463 this.dropdownWidget
.getMenu().selectItem( selected
);
9464 value
= selected
? selected
.getData() : '';
9465 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
9466 if ( this.optionsDirty
) {
9467 // We reached this from the constructor or from #setOptions.
9468 // We have to update the <select> element.
9469 this.updateOptionsInterface();
9477 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
9478 this.dropdownWidget
.setDisabled( state
);
9479 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9484 * Set the options available for this input.
9486 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9489 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
9490 var value
= this.getValue();
9492 this.setOptionsData( options
);
9494 // Re-set the value to update the visible interface (DropdownWidget and <select>).
9495 // In case the previous value is no longer an available option, select the first valid one.
9496 this.setValue( value
);
9502 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
9504 * This method may be called before the parent constructor, so various properties may not be
9507 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9510 OO
.ui
.DropdownInputWidget
.prototype.setOptionsData = function ( options
) {
9515 this.optionsDirty
= true;
9517 optionWidgets
= options
.map( function ( opt
) {
9520 if ( opt
.optgroup
!== undefined ) {
9521 return widget
.createMenuSectionOptionWidget( opt
.optgroup
);
9524 optValue
= widget
.cleanUpValue( opt
.data
);
9525 return widget
.createMenuOptionWidget(
9527 opt
.label
!== undefined ? opt
.label
: optValue
9532 this.dropdownWidget
.getMenu().clearItems().addItems( optionWidgets
);
9536 * Create a menu option widget.
9539 * @param {string} data Item data
9540 * @param {string} label Item label
9541 * @return {OO.ui.MenuOptionWidget} Option widget
9543 OO
.ui
.DropdownInputWidget
.prototype.createMenuOptionWidget = function ( data
, label
) {
9544 return new OO
.ui
.MenuOptionWidget( {
9551 * Create a menu section option widget.
9554 * @param {string} label Section item label
9555 * @return {OO.ui.MenuSectionOptionWidget} Menu section option widget
9557 OO
.ui
.DropdownInputWidget
.prototype.createMenuSectionOptionWidget = function ( label
) {
9558 return new OO
.ui
.MenuSectionOptionWidget( {
9564 * Update the user-visible interface to match the internal list of options and value.
9566 * This method must only be called after the parent constructor.
9570 OO
.ui
.DropdownInputWidget
.prototype.updateOptionsInterface = function () {
9572 $optionsContainer
= this.$input
,
9573 defaultValue
= this.defaultValue
,
9576 this.$input
.empty();
9578 this.dropdownWidget
.getMenu().getItems().forEach( function ( optionWidget
) {
9581 if ( !( optionWidget
instanceof OO
.ui
.MenuSectionOptionWidget
) ) {
9582 $optionNode
= $( '<option>' )
9583 .attr( 'value', optionWidget
.getData() )
9584 .text( optionWidget
.getLabel() );
9586 // Remember original selection state. This property can be later used to check whether
9587 // the selection state of the input has been changed since it was created.
9588 $optionNode
[ 0 ].defaultSelected
= ( optionWidget
.getData() === defaultValue
);
9590 $optionsContainer
.append( $optionNode
);
9592 $optionNode
= $( '<optgroup>' )
9593 .attr( 'label', optionWidget
.getLabel() );
9594 widget
.$input
.append( $optionNode
);
9595 $optionsContainer
= $optionNode
;
9599 this.optionsDirty
= false;
9605 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
9606 this.dropdownWidget
.focus();
9613 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
9614 this.dropdownWidget
.blur();
9619 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
9620 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
9621 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
9622 * please see the [OOUI documentation on MediaWiki][1].
9624 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9627 * // An example of selected, unselected, and disabled radio inputs
9628 * var radio1 = new OO.ui.RadioInputWidget( {
9632 * var radio2 = new OO.ui.RadioInputWidget( {
9635 * var radio3 = new OO.ui.RadioInputWidget( {
9639 * // Create a fieldset layout with fields for each radio button.
9640 * var fieldset = new OO.ui.FieldsetLayout( {
9641 * label: 'Radio inputs'
9643 * fieldset.addItems( [
9644 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
9645 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
9646 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
9648 * $( 'body' ).append( fieldset.$element );
9650 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9653 * @extends OO.ui.InputWidget
9656 * @param {Object} [config] Configuration options
9657 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
9659 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
9660 // Configuration initialization
9661 config
= config
|| {};
9663 // Parent constructor
9664 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
9668 .addClass( 'oo-ui-radioInputWidget' )
9669 // Required for pretty styling in WikimediaUI theme
9670 .append( $( '<span>' ) );
9671 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
9676 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
9678 /* Static Properties */
9684 OO
.ui
.RadioInputWidget
.static.tagName
= 'span';
9686 /* Static Methods */
9691 OO
.ui
.RadioInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9692 var state
= OO
.ui
.RadioInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9693 state
.checked
= config
.$input
.prop( 'checked' );
9703 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
9704 return $( '<input>' ).attr( 'type', 'radio' );
9710 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
9711 // RadioInputWidget doesn't track its state.
9715 * Set selection state of this radio button.
9717 * @param {boolean} state `true` for selected
9720 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
9721 // RadioInputWidget doesn't track its state.
9722 this.$input
.prop( 'checked', state
);
9723 // The first time that the selection state is set (probably while constructing the widget),
9724 // remember it in defaultSelected. This property can be later used to check whether
9725 // the selection state of the input has been changed since it was created.
9726 if ( this.defaultSelected
=== undefined ) {
9727 this.defaultSelected
= state
;
9728 this.$input
[ 0 ].defaultChecked
= this.defaultSelected
;
9734 * Check if this radio button is selected.
9736 * @return {boolean} Radio is selected
9738 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
9739 return this.$input
.prop( 'checked' );
9745 OO
.ui
.RadioInputWidget
.prototype.simulateLabelClick = function () {
9746 if ( !this.isDisabled() ) {
9747 this.$input
.click();
9755 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
9756 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
9757 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
9758 this.setSelected( state
.checked
);
9763 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
9764 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
9765 * of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9766 * more information about input widgets.
9768 * This and OO.ui.DropdownInputWidget support the same configuration options.
9771 * // Example: A RadioSelectInputWidget with three options
9772 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
9774 * { data: 'a', label: 'First' },
9775 * { data: 'b', label: 'Second'},
9776 * { data: 'c', label: 'Third' }
9779 * $( 'body' ).append( radioSelectInput.$element );
9781 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9784 * @extends OO.ui.InputWidget
9787 * @param {Object} [config] Configuration options
9788 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9790 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
9791 // Configuration initialization
9792 config
= config
|| {};
9794 // Properties (must be done before parent constructor which calls #setDisabled)
9795 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
9796 // Set up the options before parent constructor, which uses them to validate config.value.
9797 // Use this instead of setOptions() because this.$input is not set up yet
9798 this.setOptionsData( config
.options
|| [] );
9800 // Parent constructor
9801 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
9804 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
9808 .addClass( 'oo-ui-radioSelectInputWidget' )
9809 .append( this.radioSelectWidget
.$element
);
9810 this.setTabIndexedElement( this.radioSelectWidget
.$tabIndexed
);
9815 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
9817 /* Static Methods */
9822 OO
.ui
.RadioSelectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9823 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9824 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
9831 OO
.ui
.RadioSelectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
9832 config
= OO
.ui
.RadioSelectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
9833 // Cannot reuse the `<input type=radio>` set
9834 delete config
.$input
;
9844 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
9845 // Use this instead of <input type="hidden">, because hidden inputs do not have separate
9846 // 'value' and 'defaultValue' properties, and InputWidget wants to handle 'defaultValue'.
9847 return $( '<input>' ).addClass( 'oo-ui-element-hidden' );
9851 * Handles menu select events.
9854 * @param {OO.ui.RadioOptionWidget} item Selected menu item
9856 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
9857 this.setValue( item
.getData() );
9863 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
9865 value
= this.cleanUpValue( value
);
9866 // Only allow setting values that are actually present in the dropdown
9867 selected
= this.radioSelectWidget
.findItemFromData( value
) ||
9868 this.radioSelectWidget
.findFirstSelectableItem();
9869 this.radioSelectWidget
.selectItem( selected
);
9870 value
= selected
? selected
.getData() : '';
9871 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
9878 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
9879 this.radioSelectWidget
.setDisabled( state
);
9880 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9885 * Set the options available for this input.
9887 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9890 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
9891 var value
= this.getValue();
9893 this.setOptionsData( options
);
9895 // Re-set the value to update the visible interface (RadioSelectWidget).
9896 // In case the previous value is no longer an available option, select the first valid one.
9897 this.setValue( value
);
9903 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
9905 * This method may be called before the parent constructor, so various properties may not be
9908 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9911 OO
.ui
.RadioSelectInputWidget
.prototype.setOptionsData = function ( options
) {
9914 this.radioSelectWidget
9916 .addItems( options
.map( function ( opt
) {
9917 var optValue
= widget
.cleanUpValue( opt
.data
);
9918 return new OO
.ui
.RadioOptionWidget( {
9920 label
: opt
.label
!== undefined ? opt
.label
: optValue
9928 OO
.ui
.RadioSelectInputWidget
.prototype.focus = function () {
9929 this.radioSelectWidget
.focus();
9936 OO
.ui
.RadioSelectInputWidget
.prototype.blur = function () {
9937 this.radioSelectWidget
.blur();
9942 * CheckboxMultiselectInputWidget is a
9943 * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
9944 * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
9945 * HTML `<input type=checkbox>` tags. Please see the [OOUI documentation on MediaWiki][1] for
9946 * more information about input widgets.
9949 * // Example: A CheckboxMultiselectInputWidget with three options
9950 * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
9952 * { data: 'a', label: 'First' },
9953 * { data: 'b', label: 'Second'},
9954 * { data: 'c', label: 'Third' }
9957 * $( 'body' ).append( multiselectInput.$element );
9959 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9962 * @extends OO.ui.InputWidget
9965 * @param {Object} [config] Configuration options
9966 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: …, disabled: … }`
9968 OO
.ui
.CheckboxMultiselectInputWidget
= function OoUiCheckboxMultiselectInputWidget( config
) {
9969 // Configuration initialization
9970 config
= config
|| {};
9972 // Properties (must be done before parent constructor which calls #setDisabled)
9973 this.checkboxMultiselectWidget
= new OO
.ui
.CheckboxMultiselectWidget();
9974 // Must be set before the #setOptionsData call below
9975 this.inputName
= config
.name
;
9976 // Set up the options before parent constructor, which uses them to validate config.value.
9977 // Use this instead of setOptions() because this.$input is not set up yet
9978 this.setOptionsData( config
.options
|| [] );
9980 // Parent constructor
9981 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.call( this, config
);
9984 this.checkboxMultiselectWidget
.connect( this, { select
: 'onCheckboxesSelect' } );
9988 .addClass( 'oo-ui-checkboxMultiselectInputWidget' )
9989 .append( this.checkboxMultiselectWidget
.$element
);
9990 // We don't use this.$input, but rather the CheckboxInputWidgets inside each option
9991 this.$input
.detach();
9996 OO
.inheritClass( OO
.ui
.CheckboxMultiselectInputWidget
, OO
.ui
.InputWidget
);
9998 /* Static Methods */
10003 OO
.ui
.CheckboxMultiselectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
10004 var state
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
10005 state
.value
= $( node
).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
10006 .toArray().map( function ( el
) { return el
.value
; } );
10013 OO
.ui
.CheckboxMultiselectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
10014 config
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
10015 // Cannot reuse the `<input type=checkbox>` set
10016 delete config
.$input
;
10026 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getInputElement = function () {
10028 return $( '<unused>' );
10032 * Handles CheckboxMultiselectWidget select events.
10036 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.onCheckboxesSelect = function () {
10037 this.setValue( this.checkboxMultiselectWidget
.findSelectedItemsData() );
10043 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getValue = function () {
10044 var value
= this.$element
.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
10045 .toArray().map( function ( el
) { return el
.value
; } );
10046 if ( this.value
!== value
) {
10047 this.setValue( value
);
10055 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setValue = function ( value
) {
10056 value
= this.cleanUpValue( value
);
10057 this.checkboxMultiselectWidget
.selectItemsByData( value
);
10058 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setValue
.call( this, value
);
10059 if ( this.optionsDirty
) {
10060 // We reached this from the constructor or from #setOptions.
10061 // We have to update the <select> element.
10062 this.updateOptionsInterface();
10068 * Clean up incoming value.
10070 * @param {string[]} value Original value
10071 * @return {string[]} Cleaned up value
10073 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.cleanUpValue = function ( value
) {
10074 var i
, singleValue
,
10076 if ( !Array
.isArray( value
) ) {
10079 for ( i
= 0; i
< value
.length
; i
++ ) {
10081 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( this, value
[ i
] );
10082 // Remove options that we don't have here
10083 if ( !this.checkboxMultiselectWidget
.findItemFromData( singleValue
) ) {
10086 cleanValue
.push( singleValue
);
10094 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setDisabled = function ( state
) {
10095 this.checkboxMultiselectWidget
.setDisabled( state
);
10096 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
10101 * Set the options available for this input.
10103 * @param {Object[]} options Array of menu options in the format `{ data: …, label: …, disabled: … }`
10106 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setOptions = function ( options
) {
10107 var value
= this.getValue();
10109 this.setOptionsData( options
);
10111 // Re-set the value to update the visible interface (CheckboxMultiselectWidget).
10112 // This will also get rid of any stale options that we just removed.
10113 this.setValue( value
);
10119 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
10121 * This method may be called before the parent constructor, so various properties may not be
10124 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10127 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setOptionsData = function ( options
) {
10130 this.optionsDirty
= true;
10132 this.checkboxMultiselectWidget
10134 .addItems( options
.map( function ( opt
) {
10135 var optValue
, item
, optDisabled
;
10137 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( widget
, opt
.data
);
10138 optDisabled
= opt
.disabled
!== undefined ? opt
.disabled
: false;
10139 item
= new OO
.ui
.CheckboxMultioptionWidget( {
10141 label
: opt
.label
!== undefined ? opt
.label
: optValue
,
10142 disabled
: optDisabled
10144 // Set the 'name' and 'value' for form submission
10145 item
.checkbox
.$input
.attr( 'name', widget
.inputName
);
10146 item
.checkbox
.setValue( optValue
);
10152 * Update the user-visible interface to match the internal list of options and value.
10154 * This method must only be called after the parent constructor.
10158 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.updateOptionsInterface = function () {
10159 var defaultValue
= this.defaultValue
;
10161 this.checkboxMultiselectWidget
.getItems().forEach( function ( item
) {
10162 // Remember original selection state. This property can be later used to check whether
10163 // the selection state of the input has been changed since it was created.
10164 var isDefault
= defaultValue
.indexOf( item
.getData() ) !== -1;
10165 item
.checkbox
.defaultSelected
= isDefault
;
10166 item
.checkbox
.$input
[ 0 ].defaultChecked
= isDefault
;
10169 this.optionsDirty
= false;
10175 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.focus = function () {
10176 this.checkboxMultiselectWidget
.focus();
10181 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
10182 * size of the field as well as its presentation. In addition, these widgets can be configured
10183 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
10184 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
10185 * which modifies incoming values rather than validating them.
10186 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
10188 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
10191 * // Example of a text input widget
10192 * var textInput = new OO.ui.TextInputWidget( {
10193 * value: 'Text input'
10195 * $( 'body' ).append( textInput.$element );
10197 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
10200 * @extends OO.ui.InputWidget
10201 * @mixins OO.ui.mixin.IconElement
10202 * @mixins OO.ui.mixin.IndicatorElement
10203 * @mixins OO.ui.mixin.PendingElement
10204 * @mixins OO.ui.mixin.LabelElement
10207 * @param {Object} [config] Configuration options
10208 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password'
10209 * 'email', 'url' or 'number'.
10210 * @cfg {string} [placeholder] Placeholder text
10211 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
10212 * instruct the browser to focus this widget.
10213 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
10214 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
10216 * For unfortunate historical reasons, this counts the number of UTF-16 code units rather than
10217 * Unicode codepoints, which means that codepoints outside the Basic Multilingual Plane (e.g.
10218 * many emojis) count as 2 characters each.
10219 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
10220 * the value or placeholder text: `'before'` or `'after'`
10221 * @cfg {boolean} [required=false] Mark the field as required with `true`. Implies `indicator: 'required'`.
10222 * Note that `false` & setting `indicator: 'required' will result in no indicator shown.
10223 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
10224 * @cfg {boolean} [spellcheck] Should the browser support spellcheck for this field (`undefined` means
10225 * leaving it up to the browser).
10226 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
10227 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
10228 * (the value must contain only numbers); when RegExp, a regular expression that must match the
10229 * value for it to be considered valid; when Function, a function receiving the value as parameter
10230 * that must return true, or promise resolving to true, for it to be considered valid.
10232 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
10233 // Configuration initialization
10234 config
= $.extend( {
10236 labelPosition
: 'after'
10239 // Parent constructor
10240 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
10242 // Mixin constructors
10243 OO
.ui
.mixin
.IconElement
.call( this, config
);
10244 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
10245 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
10246 OO
.ui
.mixin
.LabelElement
.call( this, config
);
10249 this.type
= this.getSaneType( config
);
10250 this.readOnly
= false;
10251 this.required
= false;
10252 this.validate
= null;
10253 this.styleHeight
= null;
10254 this.scrollWidth
= null;
10256 this.setValidation( config
.validate
);
10257 this.setLabelPosition( config
.labelPosition
);
10261 keypress
: this.onKeyPress
.bind( this ),
10262 blur
: this.onBlur
.bind( this ),
10263 focus
: this.onFocus
.bind( this )
10265 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
10266 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
10267 this.on( 'labelChange', this.updatePosition
.bind( this ) );
10268 this.on( 'change', OO
.ui
.debounce( this.onDebouncedChange
.bind( this ), 250 ) );
10272 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
10273 .append( this.$icon
, this.$indicator
);
10274 this.setReadOnly( !!config
.readOnly
);
10275 this.setRequired( !!config
.required
);
10276 if ( config
.placeholder
!== undefined ) {
10277 this.$input
.attr( 'placeholder', config
.placeholder
);
10279 if ( config
.maxLength
!== undefined ) {
10280 this.$input
.attr( 'maxlength', config
.maxLength
);
10282 if ( config
.autofocus
) {
10283 this.$input
.attr( 'autofocus', 'autofocus' );
10285 if ( config
.autocomplete
=== false ) {
10286 this.$input
.attr( 'autocomplete', 'off' );
10287 // Turning off autocompletion also disables "form caching" when the user navigates to a
10288 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
10290 beforeunload: function () {
10291 this.$input
.removeAttr( 'autocomplete' );
10293 pageshow: function () {
10294 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
10295 // whole page... it shouldn't hurt, though.
10296 this.$input
.attr( 'autocomplete', 'off' );
10300 if ( config
.spellcheck
!== undefined ) {
10301 this.$input
.attr( 'spellcheck', config
.spellcheck
? 'true' : 'false' );
10303 if ( this.label
) {
10304 this.isWaitingToBeAttached
= true;
10305 this.installParentChangeDetector();
10311 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
10312 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
10313 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
10314 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
10315 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
10317 /* Static Properties */
10319 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
10327 * An `enter` event is emitted when the user presses 'enter' inside the text box.
10335 * Handle icon mouse down events.
10338 * @param {jQuery.Event} e Mouse down event
10340 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
10341 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
10348 * Handle indicator mouse down events.
10351 * @param {jQuery.Event} e Mouse down event
10353 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
10354 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
10361 * Handle key press events.
10364 * @param {jQuery.Event} e Key press event
10365 * @fires enter If enter key is pressed
10367 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
10368 if ( e
.which
=== OO
.ui
.Keys
.ENTER
) {
10369 this.emit( 'enter', e
);
10374 * Handle blur events.
10377 * @param {jQuery.Event} e Blur event
10379 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
10380 this.setValidityFlag();
10384 * Handle focus events.
10387 * @param {jQuery.Event} e Focus event
10389 OO
.ui
.TextInputWidget
.prototype.onFocus = function () {
10390 if ( this.isWaitingToBeAttached
) {
10391 // If we've received focus, then we must be attached to the document, and if
10392 // isWaitingToBeAttached is still true, that means the handler never fired. Fire it now.
10393 this.onElementAttach();
10395 this.setValidityFlag( true );
10399 * Handle element attach events.
10402 * @param {jQuery.Event} e Element attach event
10404 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
10405 this.isWaitingToBeAttached
= false;
10406 // Any previously calculated size is now probably invalid if we reattached elsewhere
10407 this.valCache
= null;
10408 this.positionLabel();
10412 * Handle debounced change events.
10414 * @param {string} value
10417 OO
.ui
.TextInputWidget
.prototype.onDebouncedChange = function () {
10418 this.setValidityFlag();
10422 * Check if the input is {@link #readOnly read-only}.
10424 * @return {boolean}
10426 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
10427 return this.readOnly
;
10431 * Set the {@link #readOnly read-only} state of the input.
10433 * @param {boolean} state Make input read-only
10436 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
10437 this.readOnly
= !!state
;
10438 this.$input
.prop( 'readOnly', this.readOnly
);
10443 * Check if the input is {@link #required required}.
10445 * @return {boolean}
10447 OO
.ui
.TextInputWidget
.prototype.isRequired = function () {
10448 return this.required
;
10452 * Set the {@link #required required} state of the input.
10454 * @param {boolean} state Make input required
10457 OO
.ui
.TextInputWidget
.prototype.setRequired = function ( state
) {
10458 this.required
= !!state
;
10459 if ( this.required
) {
10461 .prop( 'required', true )
10462 .attr( 'aria-required', 'true' );
10463 if ( this.getIndicator() === null ) {
10464 this.setIndicator( 'required' );
10468 .prop( 'required', false )
10469 .removeAttr( 'aria-required' );
10470 if ( this.getIndicator() === 'required' ) {
10471 this.setIndicator( null );
10478 * Support function for making #onElementAttach work across browsers.
10480 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
10481 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
10483 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
10484 * first time that the element gets attached to the documented.
10486 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
10487 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
10488 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
10491 if ( MutationObserver
) {
10492 // The new way. If only it wasn't so ugly.
10494 if ( this.isElementAttached() ) {
10495 // Widget is attached already, do nothing. This breaks the functionality of this function when
10496 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
10497 // would require observation of the whole document, which would hurt performance of other,
10498 // more important code.
10502 // Find topmost node in the tree
10503 topmostNode
= this.$element
[ 0 ];
10504 while ( topmostNode
.parentNode
) {
10505 topmostNode
= topmostNode
.parentNode
;
10508 // We have no way to detect the $element being attached somewhere without observing the entire
10509 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
10510 // parent node of $element, and instead detect when $element is removed from it (and thus
10511 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
10512 // doesn't get attached, we end up back here and create the parent.
10514 mutationObserver
= new MutationObserver( function ( mutations
) {
10515 var i
, j
, removedNodes
;
10516 for ( i
= 0; i
< mutations
.length
; i
++ ) {
10517 removedNodes
= mutations
[ i
].removedNodes
;
10518 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
10519 if ( removedNodes
[ j
] === topmostNode
) {
10520 setTimeout( onRemove
, 0 );
10527 onRemove = function () {
10528 // If the node was attached somewhere else, report it
10529 if ( widget
.isElementAttached() ) {
10530 widget
.onElementAttach();
10532 mutationObserver
.disconnect();
10533 widget
.installParentChangeDetector();
10536 // Create a fake parent and observe it
10537 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
10538 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
10540 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
10541 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
10542 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
10550 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
10551 if ( this.getSaneType( config
) === 'number' ) {
10552 return $( '<input>' )
10553 .attr( 'step', 'any' )
10554 .attr( 'type', 'number' );
10556 return $( '<input>' ).attr( 'type', this.getSaneType( config
) );
10561 * Get sanitized value for 'type' for given config.
10563 * @param {Object} config Configuration options
10564 * @return {string|null}
10567 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
10568 var allowedTypes
= [
10575 return allowedTypes
.indexOf( config
.type
) !== -1 ? config
.type
: 'text';
10579 * Focus the input and select a specified range within the text.
10581 * @param {number} from Select from offset
10582 * @param {number} [to] Select to offset, defaults to from
10585 OO
.ui
.TextInputWidget
.prototype.selectRange = function ( from, to
) {
10586 var isBackwards
, start
, end
,
10587 input
= this.$input
[ 0 ];
10591 isBackwards
= to
< from;
10592 start
= isBackwards
? to
: from;
10593 end
= isBackwards
? from : to
;
10598 input
.setSelectionRange( start
, end
, isBackwards
? 'backward' : 'forward' );
10600 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
10601 // Rather than expensively check if the input is attached every time, just check
10602 // if it was the cause of an error being thrown. If not, rethrow the error.
10603 if ( this.getElementDocument().body
.contains( input
) ) {
10611 * Get an object describing the current selection range in a directional manner
10613 * @return {Object} Object containing 'from' and 'to' offsets
10615 OO
.ui
.TextInputWidget
.prototype.getRange = function () {
10616 var input
= this.$input
[ 0 ],
10617 start
= input
.selectionStart
,
10618 end
= input
.selectionEnd
,
10619 isBackwards
= input
.selectionDirection
=== 'backward';
10622 from: isBackwards
? end
: start
,
10623 to
: isBackwards
? start
: end
10628 * Get the length of the text input value.
10630 * This could differ from the length of #getValue if the
10631 * value gets filtered
10633 * @return {number} Input length
10635 OO
.ui
.TextInputWidget
.prototype.getInputLength = function () {
10636 return this.$input
[ 0 ].value
.length
;
10640 * Focus the input and select the entire text.
10644 OO
.ui
.TextInputWidget
.prototype.select = function () {
10645 return this.selectRange( 0, this.getInputLength() );
10649 * Focus the input and move the cursor to the start.
10653 OO
.ui
.TextInputWidget
.prototype.moveCursorToStart = function () {
10654 return this.selectRange( 0 );
10658 * Focus the input and move the cursor to the end.
10662 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
10663 return this.selectRange( this.getInputLength() );
10667 * Insert new content into the input.
10669 * @param {string} content Content to be inserted
10672 OO
.ui
.TextInputWidget
.prototype.insertContent = function ( content
) {
10674 range
= this.getRange(),
10675 value
= this.getValue();
10677 start
= Math
.min( range
.from, range
.to
);
10678 end
= Math
.max( range
.from, range
.to
);
10680 this.setValue( value
.slice( 0, start
) + content
+ value
.slice( end
) );
10681 this.selectRange( start
+ content
.length
);
10686 * Insert new content either side of a selection.
10688 * @param {string} pre Content to be inserted before the selection
10689 * @param {string} post Content to be inserted after the selection
10692 OO
.ui
.TextInputWidget
.prototype.encapsulateContent = function ( pre
, post
) {
10694 range
= this.getRange(),
10695 offset
= pre
.length
;
10697 start
= Math
.min( range
.from, range
.to
);
10698 end
= Math
.max( range
.from, range
.to
);
10700 this.selectRange( start
).insertContent( pre
);
10701 this.selectRange( offset
+ end
).insertContent( post
);
10703 this.selectRange( offset
+ start
, offset
+ end
);
10708 * Set the validation pattern.
10710 * The validation pattern is either a regular expression, a function, or the symbolic name of a
10711 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
10712 * value must contain only numbers).
10714 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
10715 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
10717 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
10718 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
10719 this.validate
= validate
;
10721 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
10726 * Sets the 'invalid' flag appropriately.
10728 * @param {boolean} [isValid] Optionally override validation result
10730 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
10732 setFlag = function ( valid
) {
10734 widget
.$input
.attr( 'aria-invalid', 'true' );
10736 widget
.$input
.removeAttr( 'aria-invalid' );
10738 widget
.setFlags( { invalid
: !valid
} );
10741 if ( isValid
!== undefined ) {
10742 setFlag( isValid
);
10744 this.getValidity().then( function () {
10753 * Get the validity of current value.
10755 * This method returns a promise that resolves if the value is valid and rejects if
10756 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
10758 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
10760 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
10763 function rejectOrResolve( valid
) {
10765 return $.Deferred().resolve().promise();
10767 return $.Deferred().reject().promise();
10771 // Check browser validity and reject if it is invalid
10773 this.$input
[ 0 ].checkValidity
!== undefined &&
10774 this.$input
[ 0 ].checkValidity() === false
10776 return rejectOrResolve( false );
10779 // Run our checks if the browser thinks the field is valid
10780 if ( this.validate
instanceof Function
) {
10781 result
= this.validate( this.getValue() );
10782 if ( result
&& $.isFunction( result
.promise
) ) {
10783 return result
.promise().then( function ( valid
) {
10784 return rejectOrResolve( valid
);
10787 return rejectOrResolve( result
);
10790 return rejectOrResolve( this.getValue().match( this.validate
) );
10795 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
10797 * @param {string} labelPosition Label position, 'before' or 'after'
10800 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
10801 this.labelPosition
= labelPosition
;
10802 if ( this.label
) {
10803 // If there is no label and we only change the position, #updatePosition is a no-op,
10804 // but it takes really a lot of work to do nothing.
10805 this.updatePosition();
10811 * Update the position of the inline label.
10813 * This method is called by #setLabelPosition, and can also be called on its own if
10814 * something causes the label to be mispositioned.
10818 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
10819 var after
= this.labelPosition
=== 'after';
10822 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
10823 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
10825 this.valCache
= null;
10826 this.scrollWidth
= null;
10827 this.positionLabel();
10833 * Position the label by setting the correct padding on the input.
10838 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
10839 var after
, rtl
, property
, newCss
;
10841 if ( this.isWaitingToBeAttached
) {
10842 // #onElementAttach will be called soon, which calls this method
10847 'padding-right': '',
10851 if ( this.label
) {
10852 this.$element
.append( this.$label
);
10854 this.$label
.detach();
10855 // Clear old values if present
10856 this.$input
.css( newCss
);
10860 after
= this.labelPosition
=== 'after';
10861 rtl
= this.$element
.css( 'direction' ) === 'rtl';
10862 property
= after
=== rtl
? 'padding-left' : 'padding-right';
10864 newCss
[ property
] = this.$label
.outerWidth( true ) + ( after
? this.scrollWidth
: 0 );
10865 // We have to clear the padding on the other side, in case the element direction changed
10866 this.$input
.css( newCss
);
10873 * @extends OO.ui.TextInputWidget
10876 * @param {Object} [config] Configuration options
10878 OO
.ui
.SearchInputWidget
= function OoUiSearchInputWidget( config
) {
10879 config
= $.extend( {
10883 // Parent constructor
10884 OO
.ui
.SearchInputWidget
.parent
.call( this, config
);
10887 this.connect( this, {
10892 this.updateSearchIndicator();
10893 this.connect( this, {
10894 disable
: 'onDisable'
10900 OO
.inheritClass( OO
.ui
.SearchInputWidget
, OO
.ui
.TextInputWidget
);
10908 OO
.ui
.SearchInputWidget
.prototype.getSaneType = function () {
10915 OO
.ui
.SearchInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
10916 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
10917 // Clear the text field
10918 this.setValue( '' );
10925 * Update the 'clear' indicator displayed on type: 'search' text
10926 * fields, hiding it when the field is already empty or when it's not
10929 OO
.ui
.SearchInputWidget
.prototype.updateSearchIndicator = function () {
10930 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
10931 this.setIndicator( null );
10933 this.setIndicator( 'clear' );
10938 * Handle change events.
10942 OO
.ui
.SearchInputWidget
.prototype.onChange = function () {
10943 this.updateSearchIndicator();
10947 * Handle disable events.
10949 * @param {boolean} disabled Element is disabled
10952 OO
.ui
.SearchInputWidget
.prototype.onDisable = function () {
10953 this.updateSearchIndicator();
10959 OO
.ui
.SearchInputWidget
.prototype.setReadOnly = function ( state
) {
10960 OO
.ui
.SearchInputWidget
.parent
.prototype.setReadOnly
.call( this, state
);
10961 this.updateSearchIndicator();
10967 * @extends OO.ui.TextInputWidget
10970 * @param {Object} [config] Configuration options
10971 * @cfg {number} [rows] Number of visible lines in textarea. If used with `autosize`,
10972 * specifies minimum number of rows to display.
10973 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
10974 * Use the #maxRows config to specify a maximum number of displayed rows.
10975 * @cfg {number} [maxRows] Maximum number of rows to display when #autosize is set to true.
10976 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
10978 OO
.ui
.MultilineTextInputWidget
= function OoUiMultilineTextInputWidget( config
) {
10979 config
= $.extend( {
10982 // Parent constructor
10983 OO
.ui
.MultilineTextInputWidget
.parent
.call( this, config
);
10986 this.autosize
= !!config
.autosize
;
10987 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
10988 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
10990 // Clone for resizing
10991 if ( this.autosize
) {
10992 this.$clone
= this.$input
10994 .removeAttr( 'id' )
10995 .removeAttr( 'name' )
10996 .insertAfter( this.$input
)
10997 .attr( 'aria-hidden', 'true' )
10998 .addClass( 'oo-ui-element-hidden' );
11002 this.connect( this, {
11007 if ( config
.rows
) {
11008 this.$input
.attr( 'rows', config
.rows
);
11010 if ( this.autosize
) {
11011 this.$input
.addClass( 'oo-ui-textInputWidget-autosized' );
11012 this.isWaitingToBeAttached
= true;
11013 this.installParentChangeDetector();
11019 OO
.inheritClass( OO
.ui
.MultilineTextInputWidget
, OO
.ui
.TextInputWidget
);
11021 /* Static Methods */
11026 OO
.ui
.MultilineTextInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
11027 var state
= OO
.ui
.MultilineTextInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
11028 state
.scrollTop
= config
.$input
.scrollTop();
11037 OO
.ui
.MultilineTextInputWidget
.prototype.onElementAttach = function () {
11038 OO
.ui
.MultilineTextInputWidget
.parent
.prototype.onElementAttach
.call( this );
11043 * Handle change events.
11047 OO
.ui
.MultilineTextInputWidget
.prototype.onChange = function () {
11054 OO
.ui
.MultilineTextInputWidget
.prototype.updatePosition = function () {
11055 OO
.ui
.MultilineTextInputWidget
.parent
.prototype.updatePosition
.call( this );
11062 * Modify to emit 'enter' on Ctrl/Meta+Enter, instead of plain Enter
11064 OO
.ui
.MultilineTextInputWidget
.prototype.onKeyPress = function ( e
) {
11066 ( e
.which
=== OO
.ui
.Keys
.ENTER
&& ( e
.ctrlKey
|| e
.metaKey
) ) ||
11067 // Some platforms emit keycode 10 for ctrl+enter in a textarea
11070 this.emit( 'enter', e
);
11075 * Automatically adjust the size of the text input.
11077 * This only affects multiline inputs that are {@link #autosize autosized}.
11082 OO
.ui
.MultilineTextInputWidget
.prototype.adjustSize = function () {
11083 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
,
11084 idealHeight
, newHeight
, scrollWidth
, property
;
11086 if ( this.$input
.val() !== this.valCache
) {
11087 if ( this.autosize
) {
11089 .val( this.$input
.val() )
11090 .attr( 'rows', this.minRows
)
11091 // Set inline height property to 0 to measure scroll height
11092 .css( 'height', 0 );
11094 this.$clone
.removeClass( 'oo-ui-element-hidden' );
11096 this.valCache
= this.$input
.val();
11098 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
11100 // Remove inline height property to measure natural heights
11101 this.$clone
.css( 'height', '' );
11102 innerHeight
= this.$clone
.innerHeight();
11103 outerHeight
= this.$clone
.outerHeight();
11105 // Measure max rows height
11107 .attr( 'rows', this.maxRows
)
11108 .css( 'height', 'auto' )
11110 maxInnerHeight
= this.$clone
.innerHeight();
11112 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
11113 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
11114 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
11115 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
11117 this.$clone
.addClass( 'oo-ui-element-hidden' );
11119 // Only apply inline height when expansion beyond natural height is needed
11120 // Use the difference between the inner and outer height as a buffer
11121 newHeight
= idealHeight
> innerHeight
? idealHeight
+ ( outerHeight
- innerHeight
) : '';
11122 if ( newHeight
!== this.styleHeight
) {
11123 this.$input
.css( 'height', newHeight
);
11124 this.styleHeight
= newHeight
;
11125 this.emit( 'resize' );
11128 scrollWidth
= this.$input
[ 0 ].offsetWidth
- this.$input
[ 0 ].clientWidth
;
11129 if ( scrollWidth
!== this.scrollWidth
) {
11130 property
= this.$element
.css( 'direction' ) === 'rtl' ? 'left' : 'right';
11132 this.$label
.css( { right
: '', left
: '' } );
11133 this.$indicator
.css( { right
: '', left
: '' } );
11135 if ( scrollWidth
) {
11136 this.$indicator
.css( property
, scrollWidth
);
11137 if ( this.labelPosition
=== 'after' ) {
11138 this.$label
.css( property
, scrollWidth
);
11142 this.scrollWidth
= scrollWidth
;
11143 this.positionLabel();
11153 OO
.ui
.MultilineTextInputWidget
.prototype.getInputElement = function () {
11154 return $( '<textarea>' );
11158 * Check if the input automatically adjusts its size.
11160 * @return {boolean}
11162 OO
.ui
.MultilineTextInputWidget
.prototype.isAutosizing = function () {
11163 return !!this.autosize
;
11169 OO
.ui
.MultilineTextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
11170 OO
.ui
.MultilineTextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
11171 if ( state
.scrollTop
!== undefined ) {
11172 this.$input
.scrollTop( state
.scrollTop
);
11177 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
11178 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
11179 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
11181 * - by typing a value in the text input field. If the value exactly matches the value of a menu
11182 * option, that option will appear to be selected.
11183 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
11186 * After the user chooses an option, its `data` will be used as a new value for the widget.
11187 * A `label` also can be specified for each option: if given, it will be shown instead of the
11188 * `data` in the dropdown menu.
11190 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
11192 * For more information about menus and options, please see the [OOUI documentation on MediaWiki][1].
11195 * // Example: A ComboBoxInputWidget.
11196 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11197 * value: 'Option 1',
11199 * { data: 'Option 1' },
11200 * { data: 'Option 2' },
11201 * { data: 'Option 3' }
11204 * $( 'body' ).append( comboBox.$element );
11207 * // Example: A ComboBoxInputWidget with additional option labels.
11208 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11209 * value: 'Option 1',
11212 * data: 'Option 1',
11213 * label: 'Option One'
11216 * data: 'Option 2',
11217 * label: 'Option Two'
11220 * data: 'Option 3',
11221 * label: 'Option Three'
11225 * $( 'body' ).append( comboBox.$element );
11227 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
11230 * @extends OO.ui.TextInputWidget
11233 * @param {Object} [config] Configuration options
11234 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
11235 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
11236 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
11237 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
11238 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
11239 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11241 OO
.ui
.ComboBoxInputWidget
= function OoUiComboBoxInputWidget( config
) {
11242 // Configuration initialization
11243 config
= $.extend( {
11244 autocomplete
: false
11247 // ComboBoxInputWidget shouldn't support `multiline`
11248 config
.multiline
= false;
11250 // See InputWidget#reusePreInfuseDOM about `config.$input`
11251 if ( config
.$input
) {
11252 config
.$input
.removeAttr( 'list' );
11255 // Parent constructor
11256 OO
.ui
.ComboBoxInputWidget
.parent
.call( this, config
);
11259 this.$overlay
= ( config
.$overlay
=== true ? OO
.ui
.getDefaultOverlay() : config
.$overlay
) || this.$element
;
11260 this.dropdownButton
= new OO
.ui
.ButtonWidget( {
11261 classes
: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ],
11263 disabled
: this.disabled
11265 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend(
11269 $floatableContainer
: this.$element
,
11270 disabled
: this.isDisabled()
11276 this.connect( this, {
11277 change
: 'onInputChange',
11278 enter
: 'onInputEnter'
11280 this.dropdownButton
.connect( this, {
11281 click
: 'onDropdownButtonClick'
11283 this.menu
.connect( this, {
11284 choose
: 'onMenuChoose',
11285 add
: 'onMenuItemsChange',
11286 remove
: 'onMenuItemsChange',
11287 toggle
: 'onMenuToggle'
11291 this.$input
.attr( {
11293 'aria-owns': this.menu
.getElementId(),
11294 'aria-autocomplete': 'list'
11296 // Do not override options set via config.menu.items
11297 if ( config
.options
!== undefined ) {
11298 this.setOptions( config
.options
);
11300 this.$field
= $( '<div>' )
11301 .addClass( 'oo-ui-comboBoxInputWidget-field' )
11302 .append( this.$input
, this.dropdownButton
.$element
);
11304 .addClass( 'oo-ui-comboBoxInputWidget' )
11305 .append( this.$field
);
11306 this.$overlay
.append( this.menu
.$element
);
11307 this.onMenuItemsChange();
11312 OO
.inheritClass( OO
.ui
.ComboBoxInputWidget
, OO
.ui
.TextInputWidget
);
11317 * Get the combobox's menu.
11319 * @return {OO.ui.MenuSelectWidget} Menu widget
11321 OO
.ui
.ComboBoxInputWidget
.prototype.getMenu = function () {
11326 * Get the combobox's text input widget.
11328 * @return {OO.ui.TextInputWidget} Text input widget
11330 OO
.ui
.ComboBoxInputWidget
.prototype.getInput = function () {
11335 * Handle input change events.
11338 * @param {string} value New value
11340 OO
.ui
.ComboBoxInputWidget
.prototype.onInputChange = function ( value
) {
11341 var match
= this.menu
.findItemFromData( value
);
11343 this.menu
.selectItem( match
);
11344 if ( this.menu
.findHighlightedItem() ) {
11345 this.menu
.highlightItem( match
);
11348 if ( !this.isDisabled() ) {
11349 this.menu
.toggle( true );
11354 * Handle input enter events.
11358 OO
.ui
.ComboBoxInputWidget
.prototype.onInputEnter = function () {
11359 if ( !this.isDisabled() ) {
11360 this.menu
.toggle( false );
11365 * Handle button click events.
11369 OO
.ui
.ComboBoxInputWidget
.prototype.onDropdownButtonClick = function () {
11370 this.menu
.toggle();
11375 * Handle menu choose events.
11378 * @param {OO.ui.OptionWidget} item Chosen item
11380 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuChoose = function ( item
) {
11381 this.setValue( item
.getData() );
11385 * Handle menu item change events.
11389 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuItemsChange = function () {
11390 var match
= this.menu
.findItemFromData( this.getValue() );
11391 this.menu
.selectItem( match
);
11392 if ( this.menu
.findHighlightedItem() ) {
11393 this.menu
.highlightItem( match
);
11395 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu
.isEmpty() );
11399 * Handle menu toggle events.
11402 * @param {boolean} isVisible Open state of the menu
11404 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuToggle = function ( isVisible
) {
11405 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-open', isVisible
);
11411 OO
.ui
.ComboBoxInputWidget
.prototype.setDisabled = function ( disabled
) {
11413 OO
.ui
.ComboBoxInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
11415 if ( this.dropdownButton
) {
11416 this.dropdownButton
.setDisabled( this.isDisabled() );
11419 this.menu
.setDisabled( this.isDisabled() );
11426 * Set the options available for this input.
11428 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
11431 OO
.ui
.ComboBoxInputWidget
.prototype.setOptions = function ( options
) {
11434 .addItems( options
.map( function ( opt
) {
11435 return new OO
.ui
.MenuOptionWidget( {
11437 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
11445 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
11446 * which is a widget that is specified by reference before any optional configuration settings.
11448 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
11450 * - **left**: The label is placed before the field-widget and aligned with the left margin.
11451 * A left-alignment is used for forms with many fields.
11452 * - **right**: The label is placed before the field-widget and aligned to the right margin.
11453 * A right-alignment is used for long but familiar forms which users tab through,
11454 * verifying the current field with a quick glance at the label.
11455 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
11456 * that users fill out from top to bottom.
11457 * - **inline**: The label is placed after the field-widget and aligned to the left.
11458 * An inline-alignment is best used with checkboxes or radio buttons.
11460 * Help text can either be:
11462 * - accessed via a help icon that appears in the upper right corner of the rendered field layout, or
11463 * - shown as a subtle explanation below the label.
11465 * If the help text is brief, or is essential to always expose it, set `helpInline` to `true`. If it
11466 * is long or not essential, leave `helpInline` to its default, `false`.
11468 * Please see the [OOUI documentation on MediaWiki] [1] for examples and more information.
11470 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
11473 * @extends OO.ui.Layout
11474 * @mixins OO.ui.mixin.LabelElement
11475 * @mixins OO.ui.mixin.TitledElement
11478 * @param {OO.ui.Widget} fieldWidget Field widget
11479 * @param {Object} [config] Configuration options
11480 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top'
11482 * @cfg {Array} [errors] Error messages about the widget, which will be
11483 * displayed below the widget.
11484 * The array may contain strings or OO.ui.HtmlSnippet instances.
11485 * @cfg {Array} [notices] Notices about the widget, which will be displayed
11486 * below the widget.
11487 * The array may contain strings or OO.ui.HtmlSnippet instances.
11488 * These are more visible than `help` messages when `helpInline` is set, and so
11489 * might be good for transient messages.
11490 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified
11491 * and `helpInline` is `false`, a "help" icon will appear in the upper-right
11492 * corner of the rendered field; clicking it will display the text in a popup.
11493 * If `helpInline` is `true`, then a subtle description will be shown after the
11495 * @cfg {boolean} [helpInline=false] Whether or not the help should be inline,
11496 * or shown when the "help" icon is clicked.
11497 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if
11499 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11501 * @throws {Error} An error is thrown if no widget is specified
11503 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
11504 // Allow passing positional parameters inside the config object
11505 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
11506 config
= fieldWidget
;
11507 fieldWidget
= config
.fieldWidget
;
11510 // Make sure we have required constructor arguments
11511 if ( fieldWidget
=== undefined ) {
11512 throw new Error( 'Widget not found' );
11515 // Configuration initialization
11516 config
= $.extend( { align
: 'left', helpInline
: false }, config
);
11518 // Parent constructor
11519 OO
.ui
.FieldLayout
.parent
.call( this, config
);
11521 // Mixin constructors
11522 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, {
11523 $label
: $( '<label>' )
11525 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
11528 this.fieldWidget
= fieldWidget
;
11531 this.$field
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
11532 this.$messages
= $( '<ul>' );
11533 this.$header
= $( '<span>' );
11534 this.$body
= $( '<div>' );
11536 this.helpInline
= config
.helpInline
;
11539 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
11542 this.$help
= config
.help
?
11543 this.createHelpElement( config
.help
, config
.$overlay
) :
11545 if ( this.fieldWidget
.getInputId() ) {
11546 this.$label
.attr( 'for', this.fieldWidget
.getInputId() );
11547 if ( this.helpInline
) {
11548 this.$help
.attr( 'for', this.fieldWidget
.getInputId() );
11551 this.$label
.on( 'click', function () {
11552 this.fieldWidget
.simulateLabelClick();
11554 if ( this.helpInline
) {
11555 this.$help
.on( 'click', function () {
11556 this.fieldWidget
.simulateLabelClick();
11561 .addClass( 'oo-ui-fieldLayout' )
11562 .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget
.isDisabled() )
11563 .append( this.$body
);
11564 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
11565 this.$header
.addClass( 'oo-ui-fieldLayout-header' );
11566 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
11568 .addClass( 'oo-ui-fieldLayout-field' )
11569 .append( this.fieldWidget
.$element
);
11571 this.setErrors( config
.errors
|| [] );
11572 this.setNotices( config
.notices
|| [] );
11573 this.setAlignment( config
.align
);
11574 // Call this again to take into account the widget's accessKey
11575 this.updateTitle();
11580 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
11581 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
11582 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
11587 * Handle field disable events.
11590 * @param {boolean} value Field is disabled
11592 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
11593 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
11597 * Get the widget contained by the field.
11599 * @return {OO.ui.Widget} Field widget
11601 OO
.ui
.FieldLayout
.prototype.getField = function () {
11602 return this.fieldWidget
;
11606 * Return `true` if the given field widget can be used with `'inline'` alignment (see
11607 * #setAlignment). Return `false` if it can't or if this can't be determined.
11609 * @return {boolean}
11611 OO
.ui
.FieldLayout
.prototype.isFieldInline = function () {
11612 // This is very simplistic, but should be good enough.
11613 return this.getField().$element
.prop( 'tagName' ).toLowerCase() === 'span';
11618 * @param {string} kind 'error' or 'notice'
11619 * @param {string|OO.ui.HtmlSnippet} text
11622 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
11623 var $listItem
, $icon
, message
;
11624 $listItem
= $( '<li>' );
11625 if ( kind
=== 'error' ) {
11626 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
11627 $listItem
.attr( 'role', 'alert' );
11628 } else if ( kind
=== 'notice' ) {
11629 $icon
= new OO
.ui
.IconWidget( { icon
: 'notice' } ).$element
;
11633 message
= new OO
.ui
.LabelWidget( { label
: text
} );
11635 .append( $icon
, message
.$element
)
11636 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
11641 * Set the field alignment mode.
11644 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
11647 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
11648 if ( value
!== this.align
) {
11649 // Default to 'left'
11650 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
11654 if ( value
=== 'inline' && !this.isFieldInline() ) {
11657 // Reorder elements
11659 if ( this.helpInline
) {
11660 if ( value
=== 'top' ) {
11661 this.$header
.append( this.$label
);
11662 this.$body
.append( this.$header
, this.$field
, this.$help
);
11663 } else if ( value
=== 'inline' ) {
11664 this.$header
.append( this.$label
, this.$help
);
11665 this.$body
.append( this.$field
, this.$header
);
11667 this.$header
.append( this.$label
, this.$help
);
11668 this.$body
.append( this.$header
, this.$field
);
11671 if ( value
=== 'top' ) {
11672 this.$header
.append( this.$help
, this.$label
);
11673 this.$body
.append( this.$header
, this.$field
);
11674 } else if ( value
=== 'inline' ) {
11675 this.$header
.append( this.$help
, this.$label
);
11676 this.$body
.append( this.$field
, this.$header
);
11678 this.$header
.append( this.$label
);
11679 this.$body
.append( this.$header
, this.$help
, this.$field
);
11682 // Set classes. The following classes can be used here:
11683 // * oo-ui-fieldLayout-align-left
11684 // * oo-ui-fieldLayout-align-right
11685 // * oo-ui-fieldLayout-align-top
11686 // * oo-ui-fieldLayout-align-inline
11687 if ( this.align
) {
11688 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
11690 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
11691 this.align
= value
;
11698 * Set the list of error messages.
11700 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
11701 * The array may contain strings or OO.ui.HtmlSnippet instances.
11704 OO
.ui
.FieldLayout
.prototype.setErrors = function ( errors
) {
11705 this.errors
= errors
.slice();
11706 this.updateMessages();
11711 * Set the list of notice messages.
11713 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
11714 * The array may contain strings or OO.ui.HtmlSnippet instances.
11717 OO
.ui
.FieldLayout
.prototype.setNotices = function ( notices
) {
11718 this.notices
= notices
.slice();
11719 this.updateMessages();
11724 * Update the rendering of error and notice messages.
11728 OO
.ui
.FieldLayout
.prototype.updateMessages = function () {
11730 this.$messages
.empty();
11732 if ( this.errors
.length
|| this.notices
.length
) {
11733 this.$body
.after( this.$messages
);
11735 this.$messages
.remove();
11739 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
11740 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
11742 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
11743 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
11748 * Include information about the widget's accessKey in our title. TitledElement calls this method.
11749 * (This is a bit of a hack.)
11752 * @param {string} title Tooltip label for 'title' attribute
11755 OO
.ui
.FieldLayout
.prototype.formatTitleWithAccessKey = function ( title
) {
11756 if ( this.fieldWidget
&& this.fieldWidget
.formatTitleWithAccessKey
) {
11757 return this.fieldWidget
.formatTitleWithAccessKey( title
);
11763 * Creates and returns the help element. Also sets the `aria-describedby`
11764 * attribute on the main element of the `fieldWidget`.
11767 * @param {string|OO.ui.HtmlSnippet} [help] Help text.
11768 * @param {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup.
11769 * @return {jQuery} The element that should become `this.$help`.
11771 OO
.ui
.FieldLayout
.prototype.createHelpElement = function ( help
, $overlay
) {
11772 var helpId
, helpWidget
;
11774 if ( this.helpInline
) {
11775 helpWidget
= new OO
.ui
.LabelWidget( {
11777 classes
: [ 'oo-ui-inline-help' ]
11780 helpId
= helpWidget
.getElementId();
11782 helpWidget
= new OO
.ui
.PopupButtonWidget( {
11783 $overlay
: $overlay
,
11787 classes
: [ 'oo-ui-fieldLayout-help' ],
11790 label
: OO
.ui
.msg( 'ooui-field-help' ),
11791 invisibleLabel
: true
11793 if ( help
instanceof OO
.ui
.HtmlSnippet
) {
11794 helpWidget
.getPopup().$body
.html( help
.toString() );
11796 helpWidget
.getPopup().$body
.text( help
);
11799 helpId
= helpWidget
.getPopup().getBodyId();
11802 // Set the 'aria-describedby' attribute on the fieldWidget
11803 // Preference given to an input or a button
11805 this.fieldWidget
.$input
||
11806 this.fieldWidget
.$button
||
11807 this.fieldWidget
.$element
11808 ).attr( 'aria-describedby', helpId
);
11810 return helpWidget
.$element
;
11814 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
11815 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
11816 * is required and is specified before any optional configuration settings.
11818 * Labels can be aligned in one of four ways:
11820 * - **left**: The label is placed before the field-widget and aligned with the left margin.
11821 * A left-alignment is used for forms with many fields.
11822 * - **right**: The label is placed before the field-widget and aligned to the right margin.
11823 * A right-alignment is used for long but familiar forms which users tab through,
11824 * verifying the current field with a quick glance at the label.
11825 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
11826 * that users fill out from top to bottom.
11827 * - **inline**: The label is placed after the field-widget and aligned to the left.
11828 * An inline-alignment is best used with checkboxes or radio buttons.
11830 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
11831 * text is specified.
11834 * // Example of an ActionFieldLayout
11835 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
11836 * new OO.ui.TextInputWidget( {
11837 * placeholder: 'Field widget'
11839 * new OO.ui.ButtonWidget( {
11843 * label: 'An ActionFieldLayout. This label is aligned top',
11845 * help: 'This is help text'
11849 * $( 'body' ).append( actionFieldLayout.$element );
11852 * @extends OO.ui.FieldLayout
11855 * @param {OO.ui.Widget} fieldWidget Field widget
11856 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
11857 * @param {Object} config
11859 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
11860 // Allow passing positional parameters inside the config object
11861 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
11862 config
= fieldWidget
;
11863 fieldWidget
= config
.fieldWidget
;
11864 buttonWidget
= config
.buttonWidget
;
11867 // Parent constructor
11868 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
11871 this.buttonWidget
= buttonWidget
;
11872 this.$button
= $( '<span>' );
11873 this.$input
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
11877 .addClass( 'oo-ui-actionFieldLayout' );
11879 .addClass( 'oo-ui-actionFieldLayout-button' )
11880 .append( this.buttonWidget
.$element
);
11882 .addClass( 'oo-ui-actionFieldLayout-input' )
11883 .append( this.fieldWidget
.$element
);
11885 .append( this.$input
, this.$button
);
11890 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
11893 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
11894 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
11895 * configured with a label as well. For more information and examples,
11896 * please see the [OOUI documentation on MediaWiki][1].
11899 * // Example of a fieldset layout
11900 * var input1 = new OO.ui.TextInputWidget( {
11901 * placeholder: 'A text input field'
11904 * var input2 = new OO.ui.TextInputWidget( {
11905 * placeholder: 'A text input field'
11908 * var fieldset = new OO.ui.FieldsetLayout( {
11909 * label: 'Example of a fieldset layout'
11912 * fieldset.addItems( [
11913 * new OO.ui.FieldLayout( input1, {
11914 * label: 'Field One'
11916 * new OO.ui.FieldLayout( input2, {
11917 * label: 'Field Two'
11920 * $( 'body' ).append( fieldset.$element );
11922 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
11925 * @extends OO.ui.Layout
11926 * @mixins OO.ui.mixin.IconElement
11927 * @mixins OO.ui.mixin.LabelElement
11928 * @mixins OO.ui.mixin.GroupElement
11931 * @param {Object} [config] Configuration options
11932 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
11933 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
11934 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
11935 * For important messages, you are advised to use `notices`, as they are always shown.
11936 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
11937 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11939 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
11940 // Configuration initialization
11941 config
= config
|| {};
11943 // Parent constructor
11944 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
11946 // Mixin constructors
11947 OO
.ui
.mixin
.IconElement
.call( this, config
);
11948 OO
.ui
.mixin
.LabelElement
.call( this, config
);
11949 OO
.ui
.mixin
.GroupElement
.call( this, config
);
11952 this.$header
= $( '<legend>' );
11953 if ( config
.help
) {
11954 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
11955 $overlay
: config
.$overlay
,
11959 classes
: [ 'oo-ui-fieldsetLayout-help' ],
11962 label
: OO
.ui
.msg( 'ooui-field-help' ),
11963 invisibleLabel
: true
11965 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
11966 this.popupButtonWidget
.getPopup().$body
.html( config
.help
.toString() );
11968 this.popupButtonWidget
.getPopup().$body
.text( config
.help
);
11970 this.$help
= this.popupButtonWidget
.$element
;
11972 this.$help
= $( [] );
11977 .addClass( 'oo-ui-fieldsetLayout-header' )
11978 .append( this.$icon
, this.$label
, this.$help
);
11979 this.$group
.addClass( 'oo-ui-fieldsetLayout-group' );
11981 .addClass( 'oo-ui-fieldsetLayout' )
11982 .prepend( this.$header
, this.$group
);
11983 if ( Array
.isArray( config
.items
) ) {
11984 this.addItems( config
.items
);
11990 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
11991 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
11992 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
11993 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
11995 /* Static Properties */
12001 OO
.ui
.FieldsetLayout
.static.tagName
= 'fieldset';
12004 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
12005 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
12006 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
12007 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
12009 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
12010 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
12011 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
12012 * some fancier controls. Some controls have both regular and InputWidget variants, for example
12013 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
12014 * often have simplified APIs to match the capabilities of HTML forms.
12015 * See the [OOUI documentation on MediaWiki] [2] for more information about InputWidgets.
12017 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Forms
12018 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
12021 * // Example of a form layout that wraps a fieldset layout
12022 * var input1 = new OO.ui.TextInputWidget( {
12023 * placeholder: 'Username'
12025 * var input2 = new OO.ui.TextInputWidget( {
12026 * placeholder: 'Password',
12029 * var submit = new OO.ui.ButtonInputWidget( {
12033 * var fieldset = new OO.ui.FieldsetLayout( {
12034 * label: 'A form layout'
12036 * fieldset.addItems( [
12037 * new OO.ui.FieldLayout( input1, {
12038 * label: 'Username',
12041 * new OO.ui.FieldLayout( input2, {
12042 * label: 'Password',
12045 * new OO.ui.FieldLayout( submit )
12047 * var form = new OO.ui.FormLayout( {
12048 * items: [ fieldset ],
12049 * action: '/api/formhandler',
12052 * $( 'body' ).append( form.$element );
12055 * @extends OO.ui.Layout
12056 * @mixins OO.ui.mixin.GroupElement
12059 * @param {Object} [config] Configuration options
12060 * @cfg {string} [method] HTML form `method` attribute
12061 * @cfg {string} [action] HTML form `action` attribute
12062 * @cfg {string} [enctype] HTML form `enctype` attribute
12063 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
12065 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
12068 // Configuration initialization
12069 config
= config
|| {};
12071 // Parent constructor
12072 OO
.ui
.FormLayout
.parent
.call( this, config
);
12074 // Mixin constructors
12075 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
12078 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
12080 // Make sure the action is safe
12081 action
= config
.action
;
12082 if ( action
!== undefined && !OO
.ui
.isSafeUrl( action
) ) {
12083 action
= './' + action
;
12088 .addClass( 'oo-ui-formLayout' )
12090 method
: config
.method
,
12092 enctype
: config
.enctype
12094 if ( Array
.isArray( config
.items
) ) {
12095 this.addItems( config
.items
);
12101 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
12102 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
12107 * A 'submit' event is emitted when the form is submitted.
12112 /* Static Properties */
12118 OO
.ui
.FormLayout
.static.tagName
= 'form';
12123 * Handle form submit events.
12126 * @param {jQuery.Event} e Submit event
12129 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
12130 if ( this.emit( 'submit' ) ) {
12136 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
12137 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
12140 * // Example of a panel layout
12141 * var panel = new OO.ui.PanelLayout( {
12145 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
12147 * $( 'body' ).append( panel.$element );
12150 * @extends OO.ui.Layout
12153 * @param {Object} [config] Configuration options
12154 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
12155 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
12156 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
12157 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
12159 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
12160 // Configuration initialization
12161 config
= $.extend( {
12168 // Parent constructor
12169 OO
.ui
.PanelLayout
.parent
.call( this, config
);
12172 this.$element
.addClass( 'oo-ui-panelLayout' );
12173 if ( config
.scrollable
) {
12174 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
12176 if ( config
.padded
) {
12177 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
12179 if ( config
.expanded
) {
12180 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
12182 if ( config
.framed
) {
12183 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
12189 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
12194 * Focus the panel layout
12196 * The default implementation just focuses the first focusable element in the panel
12198 OO
.ui
.PanelLayout
.prototype.focus = function () {
12199 OO
.ui
.findFocusable( this.$element
).focus();
12203 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
12204 * items), with small margins between them. Convenient when you need to put a number of block-level
12205 * widgets on a single line next to each other.
12207 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
12210 * // HorizontalLayout with a text input and a label
12211 * var layout = new OO.ui.HorizontalLayout( {
12213 * new OO.ui.LabelWidget( { label: 'Label' } ),
12214 * new OO.ui.TextInputWidget( { value: 'Text' } )
12217 * $( 'body' ).append( layout.$element );
12220 * @extends OO.ui.Layout
12221 * @mixins OO.ui.mixin.GroupElement
12224 * @param {Object} [config] Configuration options
12225 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
12227 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
12228 // Configuration initialization
12229 config
= config
|| {};
12231 // Parent constructor
12232 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
12234 // Mixin constructors
12235 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
12238 this.$element
.addClass( 'oo-ui-horizontalLayout' );
12239 if ( Array
.isArray( config
.items
) ) {
12240 this.addItems( config
.items
);
12246 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
12247 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);
12250 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
12251 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
12252 * (to adjust the value in increments) to allow the user to enter a number.
12255 * // Example: A NumberInputWidget.
12256 * var numberInput = new OO.ui.NumberInputWidget( {
12257 * label: 'NumberInputWidget',
12258 * input: { value: 5 },
12262 * $( 'body' ).append( numberInput.$element );
12265 * @extends OO.ui.TextInputWidget
12268 * @param {Object} [config] Configuration options
12269 * @cfg {Object} [minusButton] Configuration options to pass to the
12270 * {@link OO.ui.ButtonWidget decrementing button widget}.
12271 * @cfg {Object} [plusButton] Configuration options to pass to the
12272 * {@link OO.ui.ButtonWidget incrementing button widget}.
12273 * @cfg {number} [min=-Infinity] Minimum allowed value
12274 * @cfg {number} [max=Infinity] Maximum allowed value
12275 * @cfg {number|null} [step] If specified, the field only accepts values that are multiples of this.
12276 * @cfg {number} [buttonStep=step||1] Delta when using the buttons or up/down arrow keys.
12277 * Defaults to `step` if specified, otherwise `1`.
12278 * @cfg {number} [pageStep=10*buttonStep] Delta when using the page-up/page-down keys.
12279 * Defaults to 10 times `buttonStep`.
12280 * @cfg {boolean} [showButtons=true] Whether to show the plus and minus buttons.
12282 OO
.ui
.NumberInputWidget
= function OoUiNumberInputWidget( config
) {
12283 var $field
= $( '<div>' )
12284 .addClass( 'oo-ui-numberInputWidget-field' );
12286 // Configuration initialization
12287 config
= $.extend( {
12293 // For backward compatibility
12294 $.extend( config
, config
.input
);
12297 // Parent constructor
12298 OO
.ui
.NumberInputWidget
.parent
.call( this, $.extend( config
, {
12302 if ( config
.showButtons
) {
12303 this.minusButton
= new OO
.ui
.ButtonWidget( $.extend(
12305 disabled
: this.isDisabled(),
12307 classes
: [ 'oo-ui-numberInputWidget-minusButton' ],
12312 this.minusButton
.$element
.attr( 'aria-hidden', 'true' );
12313 this.plusButton
= new OO
.ui
.ButtonWidget( $.extend(
12315 disabled
: this.isDisabled(),
12317 classes
: [ 'oo-ui-numberInputWidget-plusButton' ],
12322 this.plusButton
.$element
.attr( 'aria-hidden', 'true' );
12327 keydown
: this.onKeyDown
.bind( this ),
12328 'wheel mousewheel DOMMouseScroll': this.onWheel
.bind( this )
12330 if ( config
.showButtons
) {
12331 this.plusButton
.connect( this, {
12332 click
: [ 'onButtonClick', +1 ]
12334 this.minusButton
.connect( this, {
12335 click
: [ 'onButtonClick', -1 ]
12340 $field
.append( this.$input
);
12341 if ( config
.showButtons
) {
12343 .prepend( this.minusButton
.$element
)
12344 .append( this.plusButton
.$element
);
12348 if ( config
.allowInteger
|| config
.isInteger
) {
12349 // Backward compatibility
12352 this.setRange( config
.min
, config
.max
);
12353 this.setStep( config
.buttonStep
, config
.pageStep
, config
.step
);
12354 // Set the validation method after we set step and range
12355 // so that it doesn't immediately call setValidityFlag
12356 this.setValidation( this.validateNumber
.bind( this ) );
12359 .addClass( 'oo-ui-numberInputWidget' )
12360 .toggleClass( 'oo-ui-numberInputWidget-buttoned', config
.showButtons
)
12366 OO
.inheritClass( OO
.ui
.NumberInputWidget
, OO
.ui
.TextInputWidget
);
12370 // Backward compatibility
12371 OO
.ui
.NumberInputWidget
.prototype.setAllowInteger = function ( flag
) {
12372 this.setStep( flag
? 1 : null );
12374 // Backward compatibility
12375 OO
.ui
.NumberInputWidget
.prototype.setIsInteger
= OO
.ui
.NumberInputWidget
.prototype.setAllowInteger
;
12377 // Backward compatibility
12378 OO
.ui
.NumberInputWidget
.prototype.getAllowInteger = function () {
12379 return this.step
=== 1;
12381 // Backward compatibility
12382 OO
.ui
.NumberInputWidget
.prototype.getIsInteger
= OO
.ui
.NumberInputWidget
.prototype.getAllowInteger
;
12385 * Set the range of allowed values
12387 * @param {number} min Minimum allowed value
12388 * @param {number} max Maximum allowed value
12390 OO
.ui
.NumberInputWidget
.prototype.setRange = function ( min
, max
) {
12392 throw new Error( 'Minimum (' + min
+ ') must not be greater than maximum (' + max
+ ')' );
12396 this.$input
.attr( 'min', this.min
);
12397 this.$input
.attr( 'max', this.max
);
12398 this.setValidityFlag();
12402 * Get the current range
12404 * @return {number[]} Minimum and maximum values
12406 OO
.ui
.NumberInputWidget
.prototype.getRange = function () {
12407 return [ this.min
, this.max
];
12411 * Set the stepping deltas
12413 * @param {number} [buttonStep=step||1] Delta when using the buttons or up/down arrow keys.
12414 * Defaults to `step` if specified, otherwise `1`.
12415 * @param {number} [pageStep=10*buttonStep] Delta when using the page-up/page-down keys.
12416 * Defaults to 10 times `buttonStep`.
12417 * @param {number|null} [step] If specified, the field only accepts values that are multiples of this.
12419 OO
.ui
.NumberInputWidget
.prototype.setStep = function ( buttonStep
, pageStep
, step
) {
12420 if ( buttonStep
=== undefined ) {
12421 buttonStep
= step
|| 1;
12423 if ( pageStep
=== undefined ) {
12424 pageStep
= 10 * buttonStep
;
12426 if ( step
!== null && step
<= 0 ) {
12427 throw new Error( 'Step value, if given, must be positive' );
12429 if ( buttonStep
<= 0 ) {
12430 throw new Error( 'Button step value must be positive' );
12432 if ( pageStep
<= 0 ) {
12433 throw new Error( 'Page step value must be positive' );
12436 this.buttonStep
= buttonStep
;
12437 this.pageStep
= pageStep
;
12438 this.$input
.attr( 'step', this.step
|| 'any' );
12439 this.setValidityFlag();
12445 OO
.ui
.NumberInputWidget
.prototype.setValue = function ( value
) {
12446 if ( value
=== '' ) {
12447 // Some browsers allow a value in the input even if there isn't one reported by $input.val()
12448 // so here we make sure an 'empty' value is actually displayed as such.
12449 this.$input
.val( '' );
12451 return OO
.ui
.NumberInputWidget
.parent
.prototype.setValue
.call( this, value
);
12455 * Get the current stepping values
12457 * @return {number[]} Button step, page step, and validity step
12459 OO
.ui
.NumberInputWidget
.prototype.getStep = function () {
12460 return [ this.buttonStep
, this.pageStep
, this.step
];
12464 * Get the current value of the widget as a number
12466 * @return {number} May be NaN, or an invalid number
12468 OO
.ui
.NumberInputWidget
.prototype.getNumericValue = function () {
12469 return +this.getValue();
12473 * Adjust the value of the widget
12475 * @param {number} delta Adjustment amount
12477 OO
.ui
.NumberInputWidget
.prototype.adjustValue = function ( delta
) {
12478 var n
, v
= this.getNumericValue();
12481 if ( isNaN( delta
) || !isFinite( delta
) ) {
12482 throw new Error( 'Delta must be a finite number' );
12485 if ( isNaN( v
) ) {
12489 n
= Math
.max( Math
.min( n
, this.max
), this.min
);
12491 n
= Math
.round( n
/ this.step
) * this.step
;
12496 this.setValue( n
);
12503 * @param {string} value Field value
12504 * @return {boolean}
12506 OO
.ui
.NumberInputWidget
.prototype.validateNumber = function ( value
) {
12508 if ( value
=== '' ) {
12509 return !this.isRequired();
12512 if ( isNaN( n
) || !isFinite( n
) ) {
12516 if ( this.step
&& Math
.floor( n
/ this.step
) !== n
/ this.step
) {
12520 if ( n
< this.min
|| n
> this.max
) {
12528 * Handle mouse click events.
12531 * @param {number} dir +1 or -1
12533 OO
.ui
.NumberInputWidget
.prototype.onButtonClick = function ( dir
) {
12534 this.adjustValue( dir
* this.buttonStep
);
12538 * Handle mouse wheel events.
12541 * @param {jQuery.Event} event
12543 OO
.ui
.NumberInputWidget
.prototype.onWheel = function ( event
) {
12546 if ( !this.isDisabled() && this.$input
.is( ':focus' ) ) {
12547 // Standard 'wheel' event
12548 if ( event
.originalEvent
.deltaMode
!== undefined ) {
12549 this.sawWheelEvent
= true;
12551 if ( event
.originalEvent
.deltaY
) {
12552 delta
= -event
.originalEvent
.deltaY
;
12553 } else if ( event
.originalEvent
.deltaX
) {
12554 delta
= event
.originalEvent
.deltaX
;
12557 // Non-standard events
12558 if ( !this.sawWheelEvent
) {
12559 if ( event
.originalEvent
.wheelDeltaX
) {
12560 delta
= -event
.originalEvent
.wheelDeltaX
;
12561 } else if ( event
.originalEvent
.wheelDeltaY
) {
12562 delta
= event
.originalEvent
.wheelDeltaY
;
12563 } else if ( event
.originalEvent
.wheelDelta
) {
12564 delta
= event
.originalEvent
.wheelDelta
;
12565 } else if ( event
.originalEvent
.detail
) {
12566 delta
= -event
.originalEvent
.detail
;
12571 delta
= delta
< 0 ? -1 : 1;
12572 this.adjustValue( delta
* this.buttonStep
);
12580 * Handle key down events.
12583 * @param {jQuery.Event} e Key down event
12585 OO
.ui
.NumberInputWidget
.prototype.onKeyDown = function ( e
) {
12586 if ( !this.isDisabled() ) {
12587 switch ( e
.which
) {
12588 case OO
.ui
.Keys
.UP
:
12589 this.adjustValue( this.buttonStep
);
12591 case OO
.ui
.Keys
.DOWN
:
12592 this.adjustValue( -this.buttonStep
);
12594 case OO
.ui
.Keys
.PAGEUP
:
12595 this.adjustValue( this.pageStep
);
12597 case OO
.ui
.Keys
.PAGEDOWN
:
12598 this.adjustValue( -this.pageStep
);
12607 OO
.ui
.NumberInputWidget
.prototype.setDisabled = function ( disabled
) {
12609 OO
.ui
.NumberInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
12611 if ( this.minusButton
) {
12612 this.minusButton
.setDisabled( this.isDisabled() );
12614 if ( this.plusButton
) {
12615 this.plusButton
.setDisabled( this.isDisabled() );
12623 //# sourceMappingURL=oojs-ui-core.js.map.json