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-12-05T00:15:55Z
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 ( typeof msg
=== 'function' ) {
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 $ ) {
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 // eslint-disable-next-line no-void
1365 void el
.offsetHeight
;
1366 // Reattach all children
1367 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1368 el
.appendChild( nodes
[ i
] );
1370 // Restore scroll position (no-op if scrollbars disappeared)
1371 el
.scrollLeft
= scrollLeft
;
1372 el
.scrollTop
= scrollTop
;
1378 * Toggle visibility of an element.
1380 * @param {boolean} [show] Make element visible, omit to toggle visibility
1383 * @return {OO.ui.Element} The element, for chaining
1385 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1386 show
= show
=== undefined ? !this.visible
: !!show
;
1388 if ( show
!== this.isVisible() ) {
1389 this.visible
= show
;
1390 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1391 this.emit( 'toggle', show
);
1398 * Check if element is visible.
1400 * @return {boolean} element is visible
1402 OO
.ui
.Element
.prototype.isVisible = function () {
1403 return this.visible
;
1409 * @return {Mixed} Element data
1411 OO
.ui
.Element
.prototype.getData = function () {
1418 * @param {Mixed} data Element data
1420 * @return {OO.ui.Element} The element, for chaining
1422 OO
.ui
.Element
.prototype.setData = function ( data
) {
1428 * Set the element has an 'id' attribute.
1430 * @param {string} id
1432 * @return {OO.ui.Element} The element, for chaining
1434 OO
.ui
.Element
.prototype.setElementId = function ( id
) {
1435 this.elementId
= id
;
1436 this.$element
.attr( 'id', id
);
1441 * Ensure that the element has an 'id' attribute, setting it to an unique value if it's missing,
1442 * and return its value.
1446 OO
.ui
.Element
.prototype.getElementId = function () {
1447 if ( this.elementId
=== null ) {
1448 this.setElementId( OO
.ui
.generateElementId() );
1450 return this.elementId
;
1454 * Check if element supports one or more methods.
1456 * @param {string|string[]} methods Method or list of methods to check
1457 * @return {boolean} All methods are supported
1459 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1463 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1464 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1465 if ( typeof this[ methods
[ i
] ] === 'function' ) {
1470 return methods
.length
=== support
;
1474 * Update the theme-provided classes.
1476 * @localdoc This is called in element mixins and widget classes any time state changes.
1477 * Updating is debounced, minimizing overhead of changing multiple attributes and
1478 * guaranteeing that theme updates do not occur within an element's constructor
1480 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1481 OO
.ui
.theme
.queueUpdateElementClasses( this );
1485 * Get the HTML tag name.
1487 * Override this method to base the result on instance information.
1489 * @return {string} HTML tag name
1491 OO
.ui
.Element
.prototype.getTagName = function () {
1492 return this.constructor.static.tagName
;
1496 * Check if the element is attached to the DOM
1498 * @return {boolean} The element is attached to the DOM
1500 OO
.ui
.Element
.prototype.isElementAttached = function () {
1501 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1505 * Get the DOM document.
1507 * @return {HTMLDocument} Document object
1509 OO
.ui
.Element
.prototype.getElementDocument = function () {
1510 // Don't cache this in other ways either because subclasses could can change this.$element
1511 return OO
.ui
.Element
.static.getDocument( this.$element
);
1515 * Get the DOM window.
1517 * @return {Window} Window object
1519 OO
.ui
.Element
.prototype.getElementWindow = function () {
1520 return OO
.ui
.Element
.static.getWindow( this.$element
);
1524 * Get closest scrollable container.
1526 * @return {HTMLElement} Closest scrollable container
1528 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1529 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1533 * Get group element is in.
1535 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1537 OO
.ui
.Element
.prototype.getElementGroup = function () {
1538 return this.elementGroup
;
1542 * Set group element is in.
1544 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1546 * @return {OO.ui.Element} The element, for chaining
1548 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1549 this.elementGroup
= group
;
1554 * Scroll element into view.
1556 * @param {Object} [config] Configuration options
1557 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1559 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1561 !this.isElementAttached() ||
1562 !this.isVisible() ||
1563 ( this.getElementGroup() && !this.getElementGroup().isVisible() )
1565 return $.Deferred().resolve();
1567 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1571 * Restore the pre-infusion dynamic state for this widget.
1573 * This method is called after #$element has been inserted into DOM. The parameter is the return
1574 * value of #gatherPreInfuseState.
1577 * @param {Object} state
1579 OO
.ui
.Element
.prototype.restorePreInfuseState = function () {
1583 * Wraps an HTML snippet for use with configuration values which default
1584 * to strings. This bypasses the default html-escaping done to string
1590 * @param {string} [content] HTML content
1592 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
1594 this.content
= content
;
1599 OO
.initClass( OO
.ui
.HtmlSnippet
);
1606 * @return {string} Unchanged HTML snippet.
1608 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
1609 return this.content
;
1613 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1614 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1615 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1616 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1617 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1621 * @extends OO.ui.Element
1622 * @mixins OO.EventEmitter
1625 * @param {Object} [config] Configuration options
1627 OO
.ui
.Layout
= function OoUiLayout( config
) {
1628 // Configuration initialization
1629 config
= config
|| {};
1631 // Parent constructor
1632 OO
.ui
.Layout
.parent
.call( this, config
);
1634 // Mixin constructors
1635 OO
.EventEmitter
.call( this );
1638 this.$element
.addClass( 'oo-ui-layout' );
1643 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1644 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1649 * Reset scroll offsets
1652 * @return {OO.ui.Layout} The layout, for chaining
1654 OO
.ui
.Layout
.prototype.resetScroll = function () {
1655 this.$element
[ 0 ].scrollTop
= 0;
1656 // TODO: Reset scrollLeft in an RTL-aware manner, see OO.ui.Element.static.getScrollLeft.
1662 * Widgets are compositions of one or more OOUI elements that users can both view
1663 * and interact with. All widgets can be configured and modified via a standard API,
1664 * and their state can change dynamically according to a model.
1668 * @extends OO.ui.Element
1669 * @mixins OO.EventEmitter
1672 * @param {Object} [config] Configuration options
1673 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1674 * appearance reflects this state.
1676 OO
.ui
.Widget
= function OoUiWidget( config
) {
1677 // Initialize config
1678 config
= $.extend( { disabled
: false }, config
);
1680 // Parent constructor
1681 OO
.ui
.Widget
.parent
.call( this, config
);
1683 // Mixin constructors
1684 OO
.EventEmitter
.call( this );
1687 this.disabled
= null;
1688 this.wasDisabled
= null;
1691 this.$element
.addClass( 'oo-ui-widget' );
1692 this.setDisabled( !!config
.disabled
);
1697 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1698 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1705 * A 'disable' event is emitted when the disabled state of the widget changes
1706 * (i.e. on disable **and** enable).
1708 * @param {boolean} disabled Widget is disabled
1714 * A 'toggle' event is emitted when the visibility of the widget changes.
1716 * @param {boolean} visible Widget is visible
1722 * Check if the widget is disabled.
1724 * @return {boolean} Widget is disabled
1726 OO
.ui
.Widget
.prototype.isDisabled = function () {
1727 return this.disabled
;
1731 * Set the 'disabled' state of the widget.
1733 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1735 * @param {boolean} disabled Disable widget
1737 * @return {OO.ui.Widget} The widget, for chaining
1739 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
1742 this.disabled
= !!disabled
;
1743 isDisabled
= this.isDisabled();
1744 if ( isDisabled
!== this.wasDisabled
) {
1745 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
1746 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
1747 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
1748 this.emit( 'disable', isDisabled
);
1749 this.updateThemeClasses();
1751 this.wasDisabled
= isDisabled
;
1757 * Update the disabled state, in case of changes in parent widget.
1760 * @return {OO.ui.Widget} The widget, for chaining
1762 OO
.ui
.Widget
.prototype.updateDisabled = function () {
1763 this.setDisabled( this.disabled
);
1768 * Get an ID of a labelable node which is part of this widget, if any, to be used for `<label for>`
1771 * If this function returns null, the widget should have a meaningful #simulateLabelClick method
1774 * @return {string|null} The ID of the labelable element
1776 OO
.ui
.Widget
.prototype.getInputId = function () {
1781 * Simulate the behavior of clicking on a label (a HTML `<label>` element) bound to this input.
1782 * HTML only allows `<label>` to act on specific "labelable" elements; complex widgets might need to
1783 * override this method to provide intuitive, accessible behavior.
1785 * By default, this does nothing. OO.ui.mixin.TabIndexedElement overrides it for focusable widgets.
1786 * Individual widgets may override it too.
1788 * This method is called by OO.ui.LabelWidget and OO.ui.FieldLayout. It should not be called
1791 OO
.ui
.Widget
.prototype.simulateLabelClick = function () {
1802 OO
.ui
.Theme
= function OoUiTheme() {
1803 this.elementClassesQueue
= [];
1804 this.debouncedUpdateQueuedElementClasses
= OO
.ui
.debounce( this.updateQueuedElementClasses
);
1809 OO
.initClass( OO
.ui
.Theme
);
1814 * Get a list of classes to be applied to a widget.
1816 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
1817 * otherwise state transitions will not work properly.
1819 * @param {OO.ui.Element} element Element for which to get classes
1820 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1822 OO
.ui
.Theme
.prototype.getElementClasses = function () {
1823 return { on
: [], off
: [] };
1827 * Update CSS classes provided by the theme.
1829 * For elements with theme logic hooks, this should be called any time there's a state change.
1831 * @param {OO.ui.Element} element Element for which to update classes
1833 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
1834 var $elements
= $( [] ),
1835 classes
= this.getElementClasses( element
);
1837 if ( element
.$icon
) {
1838 $elements
= $elements
.add( element
.$icon
);
1840 if ( element
.$indicator
) {
1841 $elements
= $elements
.add( element
.$indicator
);
1845 .removeClass( classes
.off
)
1846 .addClass( classes
.on
);
1852 OO
.ui
.Theme
.prototype.updateQueuedElementClasses = function () {
1854 for ( i
= 0; i
< this.elementClassesQueue
.length
; i
++ ) {
1855 this.updateElementClasses( this.elementClassesQueue
[ i
] );
1858 this.elementClassesQueue
= [];
1862 * Queue #updateElementClasses to be called for this element.
1864 * @localdoc QUnit tests override this method to directly call #queueUpdateElementClasses,
1865 * to make them synchronous.
1867 * @param {OO.ui.Element} element Element for which to update classes
1869 OO
.ui
.Theme
.prototype.queueUpdateElementClasses = function ( element
) {
1870 // Keep items in the queue unique. Use lastIndexOf to start checking from the end because that's
1871 // the most common case (this method is often called repeatedly for the same element).
1872 if ( this.elementClassesQueue
.lastIndexOf( element
) !== -1 ) {
1875 this.elementClassesQueue
.push( element
);
1876 this.debouncedUpdateQueuedElementClasses();
1880 * Get the transition duration in milliseconds for dialogs opening/closing
1882 * The dialog should be fully rendered this many milliseconds after the
1883 * ready process has executed.
1885 * @return {number} Transition duration in milliseconds
1887 OO
.ui
.Theme
.prototype.getDialogTransitionDuration = function () {
1892 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
1893 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
1894 * order in which users will navigate through the focusable elements via the "tab" key.
1897 * // TabIndexedElement is mixed into the ButtonWidget class
1898 * // to provide a tabIndex property.
1899 * var button1 = new OO.ui.ButtonWidget( {
1903 * var button2 = new OO.ui.ButtonWidget( {
1907 * var button3 = new OO.ui.ButtonWidget( {
1911 * var button4 = new OO.ui.ButtonWidget( {
1915 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
1921 * @param {Object} [config] Configuration options
1922 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
1923 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
1924 * functionality will be applied to it instead.
1925 * @cfg {string|number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
1926 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
1927 * to remove the element from the tab-navigation flow.
1929 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
1930 // Configuration initialization
1931 config
= $.extend( { tabIndex
: 0 }, config
);
1934 this.$tabIndexed
= null;
1935 this.tabIndex
= null;
1938 this.connect( this, { disable
: 'onTabIndexedElementDisable' } );
1941 this.setTabIndex( config
.tabIndex
);
1942 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
1947 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
1952 * Set the element that should use the tabindex functionality.
1954 * This method is used to retarget a tabindex mixin so that its functionality applies
1955 * to the specified element. If an element is currently using the functionality, the mixin’s
1956 * effect on that element is removed before the new element is set up.
1958 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
1960 * @return {OO.ui.Element} The element, for chaining
1962 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
1963 var tabIndex
= this.tabIndex
;
1964 // Remove attributes from old $tabIndexed
1965 this.setTabIndex( null );
1966 // Force update of new $tabIndexed
1967 this.$tabIndexed
= $tabIndexed
;
1968 this.tabIndex
= tabIndex
;
1969 return this.updateTabIndex();
1973 * Set the value of the tabindex.
1975 * @param {string|number|null} tabIndex Tabindex value, or `null` for no tabindex
1977 * @return {OO.ui.Element} The element, for chaining
1979 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
1980 tabIndex
= /^-?\d+$/.test( tabIndex
) ? Number( tabIndex
) : null;
1982 if ( this.tabIndex
!== tabIndex
) {
1983 this.tabIndex
= tabIndex
;
1984 this.updateTabIndex();
1991 * Update the `tabindex` attribute, in case of changes to tab index or
1996 * @return {OO.ui.Element} The element, for chaining
1998 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
1999 if ( this.$tabIndexed
) {
2000 if ( this.tabIndex
!== null ) {
2001 // Do not index over disabled elements
2002 this.$tabIndexed
.attr( {
2003 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
2004 // Support: ChromeVox and NVDA
2005 // These do not seem to inherit aria-disabled from parent elements
2006 'aria-disabled': this.isDisabled().toString()
2009 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
2016 * Handle disable events.
2019 * @param {boolean} disabled Element is disabled
2021 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
2022 this.updateTabIndex();
2026 * Get the value of the tabindex.
2028 * @return {number|null} Tabindex value
2030 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
2031 return this.tabIndex
;
2035 * Get an ID of a focusable element of this widget, if any, to be used for `<label for>` value.
2037 * If the element already has an ID then that is returned, otherwise unique ID is
2038 * generated, set on the element, and returned.
2040 * @return {string|null} The ID of the focusable element
2042 OO
.ui
.mixin
.TabIndexedElement
.prototype.getInputId = function () {
2045 if ( !this.$tabIndexed
) {
2048 if ( !this.isLabelableNode( this.$tabIndexed
) ) {
2052 id
= this.$tabIndexed
.attr( 'id' );
2053 if ( id
=== undefined ) {
2054 id
= OO
.ui
.generateElementId();
2055 this.$tabIndexed
.attr( 'id', id
);
2062 * Whether the node is 'labelable' according to the HTML spec
2063 * (i.e., whether it can be interacted with through a `<label for="…">`).
2064 * See: <https://html.spec.whatwg.org/multipage/forms.html#category-label>.
2067 * @param {jQuery} $node
2070 OO
.ui
.mixin
.TabIndexedElement
.prototype.isLabelableNode = function ( $node
) {
2072 labelableTags
= [ 'button', 'meter', 'output', 'progress', 'select', 'textarea' ],
2073 tagName
= $node
.prop( 'tagName' ).toLowerCase();
2075 if ( tagName
=== 'input' && $node
.attr( 'type' ) !== 'hidden' ) {
2078 if ( labelableTags
.indexOf( tagName
) !== -1 ) {
2085 * Focus this element.
2088 * @return {OO.ui.Element} The element, for chaining
2090 OO
.ui
.mixin
.TabIndexedElement
.prototype.focus = function () {
2091 if ( !this.isDisabled() ) {
2092 this.$tabIndexed
.focus();
2098 * Blur this element.
2101 * @return {OO.ui.Element} The element, for chaining
2103 OO
.ui
.mixin
.TabIndexedElement
.prototype.blur = function () {
2104 this.$tabIndexed
.blur();
2109 * @inheritdoc OO.ui.Widget
2111 OO
.ui
.mixin
.TabIndexedElement
.prototype.simulateLabelClick = function () {
2116 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
2117 * interface element that can be configured with access keys for accessibility.
2118 * See the [OOUI documentation on MediaWiki] [1] for examples.
2120 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches#Buttons
2126 * @param {Object} [config] Configuration options
2127 * @cfg {jQuery} [$button] The button element created by the class.
2128 * If this configuration is omitted, the button element will use a generated `<a>`.
2129 * @cfg {boolean} [framed=true] Render the button with a frame
2131 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
2132 // Configuration initialization
2133 config
= config
|| {};
2136 this.$button
= null;
2138 this.active
= config
.active
!== undefined && config
.active
;
2139 this.onDocumentMouseUpHandler
= this.onDocumentMouseUp
.bind( this );
2140 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
2141 this.onDocumentKeyUpHandler
= this.onDocumentKeyUp
.bind( this );
2142 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
2143 this.onClickHandler
= this.onClick
.bind( this );
2144 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
2147 this.$element
.addClass( 'oo-ui-buttonElement' );
2148 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
2149 this.setButtonElement( config
.$button
|| $( '<a>' ) );
2154 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
2156 /* Static Properties */
2159 * Cancel mouse down events.
2161 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
2162 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
2163 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
2168 * @property {boolean}
2170 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
2175 * A 'click' event is emitted when the button element is clicked.
2183 * Set the button element.
2185 * This method is used to retarget a button mixin so that its functionality applies to
2186 * the specified button element instead of the one created by the class. If a button element
2187 * is already set, the method will remove the mixin’s effect on that element.
2189 * @param {jQuery} $button Element to use as button
2191 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
2192 if ( this.$button
) {
2194 .removeClass( 'oo-ui-buttonElement-button' )
2195 .removeAttr( 'role accesskey' )
2197 mousedown
: this.onMouseDownHandler
,
2198 keydown
: this.onKeyDownHandler
,
2199 click
: this.onClickHandler
,
2200 keypress
: this.onKeyPressHandler
2204 this.$button
= $button
2205 .addClass( 'oo-ui-buttonElement-button' )
2207 mousedown
: this.onMouseDownHandler
,
2208 keydown
: this.onKeyDownHandler
,
2209 click
: this.onClickHandler
,
2210 keypress
: this.onKeyPressHandler
2213 // Add `role="button"` on `<a>` elements, where it's needed
2214 // `toUpperCase()` is added for XHTML documents
2215 if ( this.$button
.prop( 'tagName' ).toUpperCase() === 'A' ) {
2216 this.$button
.attr( 'role', 'button' );
2221 * Handles mouse down events.
2224 * @param {jQuery.Event} e Mouse down event
2225 * @return {undefined/boolean} False to prevent default if event is handled
2227 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
2228 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
2231 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
2232 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
2233 // reliably remove the pressed class
2234 this.getElementDocument().addEventListener( 'mouseup', this.onDocumentMouseUpHandler
, true );
2235 // Prevent change of focus unless specifically configured otherwise
2236 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
2242 * Handles document mouse up events.
2245 * @param {MouseEvent} e Mouse up event
2247 OO
.ui
.mixin
.ButtonElement
.prototype.onDocumentMouseUp = function ( e
) {
2248 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
2251 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
2252 // Stop listening for mouseup, since we only needed this once
2253 this.getElementDocument().removeEventListener( 'mouseup', this.onDocumentMouseUpHandler
, true );
2256 // Deprecated alias since 0.28.3
2257 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp = function () {
2258 OO
.ui
.warnDeprecation( 'onMouseUp is deprecated, use onDocumentMouseUp instead' );
2259 this.onDocumentMouseUp
.apply( this, arguments
);
2263 * Handles mouse click events.
2266 * @param {jQuery.Event} e Mouse click event
2268 * @return {undefined/boolean} False to prevent default if event is handled
2270 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
2271 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
2272 if ( this.emit( 'click' ) ) {
2279 * Handles key down events.
2282 * @param {jQuery.Event} e Key down event
2284 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
2285 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2288 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
2289 // Run the keyup handler no matter where the key is when the button is let go, so we can
2290 // reliably remove the pressed class
2291 this.getElementDocument().addEventListener( 'keyup', this.onDocumentKeyUpHandler
, true );
2295 * Handles document key up events.
2298 * @param {KeyboardEvent} e Key up event
2300 OO
.ui
.mixin
.ButtonElement
.prototype.onDocumentKeyUp = function ( e
) {
2301 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2304 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
2305 // Stop listening for keyup, since we only needed this once
2306 this.getElementDocument().removeEventListener( 'keyup', this.onDocumentKeyUpHandler
, true );
2309 // Deprecated alias since 0.28.3
2310 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyUp = function () {
2311 OO
.ui
.warnDeprecation( 'onKeyUp is deprecated, use onDocumentKeyUp instead' );
2312 this.onDocumentKeyUp
.apply( this, arguments
);
2316 * Handles key press events.
2319 * @param {jQuery.Event} e Key press event
2321 * @return {undefined/boolean} False to prevent default if event is handled
2323 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
2324 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
2325 if ( this.emit( 'click' ) ) {
2332 * Check if button has a frame.
2334 * @return {boolean} Button is framed
2336 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
2341 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
2343 * @param {boolean} [framed] Make button framed, omit to toggle
2345 * @return {OO.ui.Element} The element, for chaining
2347 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
2348 framed
= framed
=== undefined ? !this.framed
: !!framed
;
2349 if ( framed
!== this.framed
) {
2350 this.framed
= framed
;
2352 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
2353 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
2354 this.updateThemeClasses();
2361 * Set the button's active state.
2363 * The active state can be set on:
2365 * - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected
2366 * - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on
2367 * - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page
2370 * @param {boolean} value Make button active
2372 * @return {OO.ui.Element} The element, for chaining
2374 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
2375 this.active
= !!value
;
2376 this.$element
.toggleClass( 'oo-ui-buttonElement-active', this.active
);
2377 this.updateThemeClasses();
2382 * Check if the button is active
2385 * @return {boolean} The button is active
2387 OO
.ui
.mixin
.ButtonElement
.prototype.isActive = function () {
2392 * Any OOUI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
2393 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
2394 * items from the group is done through the interface the class provides.
2395 * For more information, please see the [OOUI documentation on MediaWiki] [1].
2397 * [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Groups
2400 * @mixins OO.EmitterList
2404 * @param {Object} [config] Configuration options
2405 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
2406 * is omitted, the group element will use a generated `<div>`.
2408 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
2409 // Configuration initialization
2410 config
= config
|| {};
2412 // Mixin constructors
2413 OO
.EmitterList
.call( this, config
);
2419 this.setGroupElement( config
.$group
|| $( '<div>' ) );
2424 OO
.mixinClass( OO
.ui
.mixin
.GroupElement
, OO
.EmitterList
);
2431 * A change event is emitted when the set of selected items changes.
2433 * @param {OO.ui.Element[]} items Items currently in the group
2439 * Set the group element.
2441 * If an element is already set, items will be moved to the new element.
2443 * @param {jQuery} $group Element to use as group
2445 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
2448 this.$group
= $group
;
2449 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2450 this.$group
.append( this.items
[ i
].$element
);
2455 * Find an item by its data.
2457 * Only the first item with matching data will be returned. To return all matching items,
2458 * use the #findItemsFromData method.
2460 * @param {Object} data Item data to search for
2461 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2463 OO
.ui
.mixin
.GroupElement
.prototype.findItemFromData = function ( data
) {
2465 hash
= OO
.getHash( data
);
2467 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2468 item
= this.items
[ i
];
2469 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2478 * Find items by their data.
2480 * All items with matching data will be returned. To return only the first match, use the #findItemFromData method instead.
2482 * @param {Object} data Item data to search for
2483 * @return {OO.ui.Element[]} Items with equivalent data
2485 OO
.ui
.mixin
.GroupElement
.prototype.findItemsFromData = function ( data
) {
2487 hash
= OO
.getHash( data
),
2490 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2491 item
= this.items
[ i
];
2492 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2501 * Add items to the group.
2503 * Items will be added to the end of the group array unless the optional `index` parameter specifies
2504 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
2506 * @param {OO.ui.Element[]} items An array of items to add to the group
2507 * @param {number} [index] Index of the insertion point
2509 * @return {OO.ui.Element} The element, for chaining
2511 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
2513 OO
.EmitterList
.prototype.addItems
.call( this, items
, index
);
2515 this.emit( 'change', this.getItems() );
2522 OO
.ui
.mixin
.GroupElement
.prototype.moveItem = function ( items
, newIndex
) {
2523 // insertItemElements expects this.items to not have been modified yet, so call before the mixin
2524 this.insertItemElements( items
, newIndex
);
2527 newIndex
= OO
.EmitterList
.prototype.moveItem
.call( this, items
, newIndex
);
2535 OO
.ui
.mixin
.GroupElement
.prototype.insertItem = function ( item
, index
) {
2536 item
.setElementGroup( this );
2537 this.insertItemElements( item
, index
);
2540 index
= OO
.EmitterList
.prototype.insertItem
.call( this, item
, index
);
2546 * Insert elements into the group
2549 * @param {OO.ui.Element} itemWidget Item to insert
2550 * @param {number} index Insertion index
2552 OO
.ui
.mixin
.GroupElement
.prototype.insertItemElements = function ( itemWidget
, index
) {
2553 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
2554 this.$group
.append( itemWidget
.$element
);
2555 } else if ( index
=== 0 ) {
2556 this.$group
.prepend( itemWidget
.$element
);
2558 this.items
[ index
].$element
.before( itemWidget
.$element
);
2563 * Remove the specified items from a group.
2565 * Removed items are detached (not removed) from the DOM so that they may be reused.
2566 * To remove all items from a group, you may wish to use the #clearItems method instead.
2568 * @param {OO.ui.Element[]} items An array of items to remove
2570 * @return {OO.ui.Element} The element, for chaining
2572 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
2573 var i
, len
, item
, index
;
2575 // Remove specific items elements
2576 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
2578 index
= this.items
.indexOf( item
);
2579 if ( index
!== -1 ) {
2580 item
.setElementGroup( null );
2581 item
.$element
.detach();
2586 OO
.EmitterList
.prototype.removeItems
.call( this, items
);
2588 this.emit( 'change', this.getItems() );
2593 * Clear all items from the group.
2595 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2596 * To remove only a subset of items from a group, use the #removeItems method.
2599 * @return {OO.ui.Element} The element, for chaining
2601 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
2604 // Remove all item elements
2605 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2606 this.items
[ i
].setElementGroup( null );
2607 this.items
[ i
].$element
.detach();
2611 OO
.EmitterList
.prototype.clearItems
.call( this );
2613 this.emit( 'change', this.getItems() );
2618 * LabelElement is often mixed into other classes to generate a label, which
2619 * helps identify the function of an interface element.
2620 * See the [OOUI documentation on MediaWiki] [1] for more information.
2622 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
2628 * @param {Object} [config] Configuration options
2629 * @cfg {jQuery} [$label] The label element created by the class. If this
2630 * configuration is omitted, the label element will use a generated `<span>`.
2631 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
2632 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
2633 * in the future. See the [OOUI documentation on MediaWiki] [2] for examples.
2634 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
2635 * @cfg {boolean} [invisibleLabel] Whether the label should be visually hidden (but still accessible
2636 * to screen-readers).
2638 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
2639 // Configuration initialization
2640 config
= config
|| {};
2645 this.invisibleLabel
= null;
2648 this.setLabel( config
.label
|| this.constructor.static.label
);
2649 this.setLabelElement( config
.$label
|| $( '<span>' ) );
2650 this.setInvisibleLabel( config
.invisibleLabel
);
2655 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
2660 * @event labelChange
2661 * @param {string} value
2664 /* Static Properties */
2667 * The label text. The label can be specified as a plaintext string, a function that will
2668 * produce a string in the future, or `null` for no label. The static value will
2669 * be overridden if a label is specified with the #label config option.
2673 * @property {string|Function|null}
2675 OO
.ui
.mixin
.LabelElement
.static.label
= null;
2677 /* Static methods */
2680 * Highlight the first occurrence of the query in the given text
2682 * @param {string} text Text
2683 * @param {string} query Query to find
2684 * @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
2685 * @return {jQuery} Text with the first match of the query
2686 * sub-string wrapped in highlighted span
2688 OO
.ui
.mixin
.LabelElement
.static.highlightQuery = function ( text
, query
, compare
) {
2691 $result
= $( '<span>' );
2695 qLen
= query
.length
;
2696 for ( i
= 0; offset
=== -1 && i
<= tLen
- qLen
; i
++ ) {
2697 if ( compare( query
, text
.slice( i
, i
+ qLen
) ) === 0 ) {
2702 offset
= text
.toLowerCase().indexOf( query
.toLowerCase() );
2705 if ( !query
.length
|| offset
=== -1 ) {
2706 $result
.text( text
);
2709 document
.createTextNode( text
.slice( 0, offset
) ),
2711 .addClass( 'oo-ui-labelElement-label-highlight' )
2712 .text( text
.slice( offset
, offset
+ query
.length
) ),
2713 document
.createTextNode( text
.slice( offset
+ query
.length
) )
2716 return $result
.contents();
2722 * Set the label element.
2724 * If an element is already set, it will be cleaned up before setting up the new element.
2726 * @param {jQuery} $label Element to use as label
2728 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
2729 if ( this.$label
) {
2730 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
2733 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
2734 this.setLabelContent( this.label
);
2740 * An empty string will result in the label being hidden. A string containing only whitespace will
2741 * be converted to a single ` `.
2743 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
2744 * text; or null for no label
2746 * @return {OO.ui.Element} The element, for chaining
2748 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
2749 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
2750 label
= ( ( typeof label
=== 'string' || label
instanceof $ ) && label
.length
) || ( label
instanceof OO
.ui
.HtmlSnippet
&& label
.toString().length
) ? label
: null;
2752 if ( this.label
!== label
) {
2753 if ( this.$label
) {
2754 this.setLabelContent( label
);
2757 this.emit( 'labelChange' );
2760 this.$element
.toggleClass( 'oo-ui-labelElement', !!this.label
&& !this.invisibleLabel
);
2766 * Set whether the label should be visually hidden (but still accessible to screen-readers).
2768 * @param {boolean} invisibleLabel
2770 * @return {OO.ui.Element} The element, for chaining
2772 OO
.ui
.mixin
.LabelElement
.prototype.setInvisibleLabel = function ( invisibleLabel
) {
2773 invisibleLabel
= !!invisibleLabel
;
2775 if ( this.invisibleLabel
!== invisibleLabel
) {
2776 this.invisibleLabel
= invisibleLabel
;
2777 this.emit( 'labelChange' );
2780 this.$label
.toggleClass( 'oo-ui-labelElement-invisible', this.invisibleLabel
);
2781 // Pretend that there is no label, a lot of CSS has been written with this assumption
2782 this.$element
.toggleClass( 'oo-ui-labelElement', !!this.label
&& !this.invisibleLabel
);
2788 * Set the label as plain text with a highlighted query
2790 * @param {string} text Text label to set
2791 * @param {string} query Substring of text to highlight
2792 * @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
2794 * @return {OO.ui.Element} The element, for chaining
2796 OO
.ui
.mixin
.LabelElement
.prototype.setHighlightedQuery = function ( text
, query
, compare
) {
2797 return this.setLabel( this.constructor.static.highlightQuery( text
, query
, compare
) );
2803 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
2804 * text; or null for no label
2806 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
2811 * Set the content of the label.
2813 * Do not call this method until after the label element has been set by #setLabelElement.
2816 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
2817 * text; or null for no label
2819 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
2820 if ( typeof label
=== 'string' ) {
2821 if ( label
.match( /^\s*$/ ) ) {
2822 // Convert whitespace only string to a single non-breaking space
2823 this.$label
.html( ' ' );
2825 this.$label
.text( label
);
2827 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
2828 this.$label
.html( label
.toString() );
2829 } else if ( label
instanceof $ ) {
2830 this.$label
.empty().append( label
);
2832 this.$label
.empty();
2837 * IconElement is often mixed into other classes to generate an icon.
2838 * Icons are graphics, about the size of normal text. They are used to aid the user
2839 * in locating a control or to convey information in a space-efficient way. See the
2840 * [OOUI documentation on MediaWiki] [1] for a list of icons
2841 * included in the library.
2843 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
2849 * @param {Object} [config] Configuration options
2850 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2851 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2852 * the icon element be set to an existing icon instead of the one generated by this class, set a
2853 * value using a jQuery selection. For example:
2855 * // Use a <div> tag instead of a <span>
2857 * // Use an existing icon element instead of the one generated by the class
2858 * $icon: this.$element
2859 * // Use an icon element from a child widget
2860 * $icon: this.childwidget.$element
2861 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
2862 * symbolic names. A map is used for i18n purposes and contains a `default` icon
2863 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
2864 * by the user's language.
2866 * Example of an i18n map:
2868 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2869 * See the [OOUI documentation on MediaWiki] [2] for a list of icons included in the library.
2870 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
2871 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
2872 * text. The icon title is displayed when users move the mouse over the icon.
2874 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
2875 // Configuration initialization
2876 config
= config
|| {};
2881 this.iconTitle
= null;
2884 this.setIcon( config
.icon
|| this.constructor.static.icon
);
2885 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
2886 this.setIconElement( config
.$icon
|| $( '<span>' ) );
2891 OO
.initClass( OO
.ui
.mixin
.IconElement
);
2893 /* Static Properties */
2896 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
2897 * for i18n purposes and contains a `default` icon name and additional names keyed by
2898 * language code. The `default` name is used when no icon is keyed by the user's language.
2900 * Example of an i18n map:
2902 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2904 * Note: the static property will be overridden if the #icon configuration is used.
2908 * @property {Object|string}
2910 OO
.ui
.mixin
.IconElement
.static.icon
= null;
2913 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2914 * function that returns title text, or `null` for no title.
2916 * The static property will be overridden if the #iconTitle configuration is used.
2920 * @property {string|Function|null}
2922 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
2927 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2928 * applies to the specified icon element instead of the one created by the class. If an icon
2929 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2930 * and mixin methods will no longer affect the element.
2932 * @param {jQuery} $icon Element to use as icon
2934 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
2937 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
2938 .removeAttr( 'title' );
2942 .addClass( 'oo-ui-iconElement-icon' )
2943 .toggleClass( 'oo-ui-iconElement-noIcon', !this.icon
)
2944 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
2945 if ( this.iconTitle
!== null ) {
2946 this.$icon
.attr( 'title', this.iconTitle
);
2949 this.updateThemeClasses();
2953 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
2954 * The icon parameter can also be set to a map of icon names. See the #icon config setting
2957 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
2958 * by language code, or `null` to remove the icon.
2960 * @return {OO.ui.Element} The element, for chaining
2962 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
2963 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
2964 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
2966 if ( this.icon
!== icon
) {
2968 if ( this.icon
!== null ) {
2969 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
2971 if ( icon
!== null ) {
2972 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
2978 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
2980 this.$icon
.toggleClass( 'oo-ui-iconElement-noIcon', !this.icon
);
2982 this.updateThemeClasses();
2988 * Set the icon title. Use `null` to remove the title.
2990 * @param {string|Function|null} iconTitle A text string used as the icon title,
2991 * a function that returns title text, or `null` for no title.
2993 * @return {OO.ui.Element} The element, for chaining
2995 OO
.ui
.mixin
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
2997 ( typeof iconTitle
=== 'function' || ( typeof iconTitle
=== 'string' && iconTitle
.length
) ) ?
2998 OO
.ui
.resolveMsg( iconTitle
) : null;
3000 if ( this.iconTitle
!== iconTitle
) {
3001 this.iconTitle
= iconTitle
;
3003 if ( this.iconTitle
!== null ) {
3004 this.$icon
.attr( 'title', iconTitle
);
3006 this.$icon
.removeAttr( 'title' );
3015 * Get the symbolic name of the icon.
3017 * @return {string} Icon name
3019 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
3024 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
3026 * @return {string} Icon title text
3028 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
3029 return this.iconTitle
;
3033 * IndicatorElement is often mixed into other classes to generate an indicator.
3034 * Indicators are small graphics that are generally used in two ways:
3036 * - To draw attention to the status of an item. For example, an indicator might be
3037 * used to show that an item in a list has errors that need to be resolved.
3038 * - To clarify the function of a control that acts in an exceptional way (a button
3039 * that opens a menu instead of performing an action directly, for example).
3041 * For a list of indicators included in the library, please see the
3042 * [OOUI documentation on MediaWiki] [1].
3044 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3050 * @param {Object} [config] Configuration options
3051 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
3052 * configuration is omitted, the indicator element will use a generated `<span>`.
3053 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3054 * See the [OOUI documentation on MediaWiki][2] for a list of indicators included
3056 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3057 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
3058 * or a function that returns title text. The indicator title is displayed when users move
3059 * the mouse over the indicator.
3061 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
3062 // Configuration initialization
3063 config
= config
|| {};
3066 this.$indicator
= null;
3067 this.indicator
= null;
3068 this.indicatorTitle
= null;
3071 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
3072 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
3073 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
3078 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
3080 /* Static Properties */
3083 * Symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3084 * The static property will be overridden if the #indicator configuration is used.
3088 * @property {string|null}
3090 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
3093 * A text string used as the indicator title, a function that returns title text, or `null`
3094 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
3098 * @property {string|Function|null}
3100 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
3105 * Set the indicator element.
3107 * If an element is already set, it will be cleaned up before setting up the new element.
3109 * @param {jQuery} $indicator Element to use as indicator
3111 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
3112 if ( this.$indicator
) {
3114 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
3115 .removeAttr( 'title' );
3118 this.$indicator
= $indicator
3119 .addClass( 'oo-ui-indicatorElement-indicator' )
3120 .toggleClass( 'oo-ui-indicatorElement-noIndicator', !this.indicator
)
3121 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
3122 if ( this.indicatorTitle
!== null ) {
3123 this.$indicator
.attr( 'title', this.indicatorTitle
);
3126 this.updateThemeClasses();
3130 * Set the indicator by its symbolic name: ‘clear’, ‘down’, ‘required’, ‘search’, ‘up’. Use `null` to remove the indicator.
3132 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
3134 * @return {OO.ui.Element} The element, for chaining
3136 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
3137 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
3139 if ( this.indicator
!== indicator
) {
3140 if ( this.$indicator
) {
3141 if ( this.indicator
!== null ) {
3142 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
3144 if ( indicator
!== null ) {
3145 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
3148 this.indicator
= indicator
;
3151 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
3152 if ( this.$indicator
) {
3153 this.$indicator
.toggleClass( 'oo-ui-indicatorElement-noIndicator', !this.indicator
);
3155 this.updateThemeClasses();
3161 * Set the indicator title.
3163 * The title is displayed when a user moves the mouse over the indicator.
3165 * @param {string|Function|null} indicatorTitle Indicator title text, a function that returns text, or
3166 * `null` for no indicator title
3168 * @return {OO.ui.Element} The element, for chaining
3170 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
3172 ( typeof indicatorTitle
=== 'function' || ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ) ?
3173 OO
.ui
.resolveMsg( indicatorTitle
) : null;
3175 if ( this.indicatorTitle
!== indicatorTitle
) {
3176 this.indicatorTitle
= indicatorTitle
;
3177 if ( this.$indicator
) {
3178 if ( this.indicatorTitle
!== null ) {
3179 this.$indicator
.attr( 'title', indicatorTitle
);
3181 this.$indicator
.removeAttr( 'title' );
3190 * Get the symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3192 * @return {string} Symbolic name of indicator
3194 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
3195 return this.indicator
;
3199 * Get the indicator title.
3201 * The title is displayed when a user moves the mouse over the indicator.
3203 * @return {string} Indicator title text
3205 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
3206 return this.indicatorTitle
;
3210 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
3211 * additional functionality to an element created by another class. The class provides
3212 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
3213 * which are used to customize the look and feel of a widget to better describe its
3214 * importance and functionality.
3216 * The library currently contains the following styling flags for general use:
3218 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
3219 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
3221 * The flags affect the appearance of the buttons:
3224 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
3225 * var button1 = new OO.ui.ButtonWidget( {
3226 * label: 'Progressive',
3227 * flags: 'progressive'
3229 * var button2 = new OO.ui.ButtonWidget( {
3230 * label: 'Destructive',
3231 * flags: 'destructive'
3233 * $( 'body' ).append( button1.$element, button2.$element );
3235 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
3236 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
3238 * [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
3244 * @param {Object} [config] Configuration options
3245 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'progressive' or 'primary') to apply.
3246 * Please see the [OOUI documentation on MediaWiki] [2] for more information about available flags.
3247 * [2]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
3248 * @cfg {jQuery} [$flagged] The flagged element. By default,
3249 * the flagged functionality is applied to the element created by the class ($element).
3250 * If a different element is specified, the flagged functionality will be applied to it instead.
3252 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
3253 // Configuration initialization
3254 config
= config
|| {};
3258 this.$flagged
= null;
3261 this.setFlags( config
.flags
);
3262 this.setFlaggedElement( config
.$flagged
|| this.$element
);
3269 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
3270 * parameter contains the name of each modified flag and indicates whether it was
3273 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
3274 * that the flag was added, `false` that the flag was removed.
3280 * Set the flagged element.
3282 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
3283 * If an element is already set, the method will remove the mixin’s effect on that element.
3285 * @param {jQuery} $flagged Element that should be flagged
3287 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
3288 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
3289 return 'oo-ui-flaggedElement-' + flag
;
3292 if ( this.$flagged
) {
3293 this.$flagged
.removeClass( classNames
);
3296 this.$flagged
= $flagged
.addClass( classNames
);
3300 * Check if the specified flag is set.
3302 * @param {string} flag Name of flag
3303 * @return {boolean} The flag is set
3305 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
3306 // This may be called before the constructor, thus before this.flags is set
3307 return this.flags
&& ( flag
in this.flags
);
3311 * Get the names of all flags set.
3313 * @return {string[]} Flag names
3315 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
3316 // This may be called before the constructor, thus before this.flags is set
3317 return Object
.keys( this.flags
|| {} );
3324 * @return {OO.ui.Element} The element, for chaining
3327 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
3328 var flag
, className
,
3331 classPrefix
= 'oo-ui-flaggedElement-';
3333 for ( flag
in this.flags
) {
3334 className
= classPrefix
+ flag
;
3335 changes
[ flag
] = false;
3336 delete this.flags
[ flag
];
3337 remove
.push( className
);
3340 if ( this.$flagged
) {
3341 this.$flagged
.removeClass( remove
);
3344 this.updateThemeClasses();
3345 this.emit( 'flag', changes
);
3351 * Add one or more flags.
3353 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
3354 * or an object keyed by flag name with a boolean value that indicates whether the flag should
3355 * be added (`true`) or removed (`false`).
3357 * @return {OO.ui.Element} The element, for chaining
3360 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
3361 var i
, len
, flag
, className
,
3365 classPrefix
= 'oo-ui-flaggedElement-';
3367 if ( typeof flags
=== 'string' ) {
3368 className
= classPrefix
+ flags
;
3370 if ( !this.flags
[ flags
] ) {
3371 this.flags
[ flags
] = true;
3372 add
.push( className
);
3374 } else if ( Array
.isArray( flags
) ) {
3375 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
3377 className
= classPrefix
+ flag
;
3379 if ( !this.flags
[ flag
] ) {
3380 changes
[ flag
] = true;
3381 this.flags
[ flag
] = true;
3382 add
.push( className
);
3385 } else if ( OO
.isPlainObject( flags
) ) {
3386 for ( flag
in flags
) {
3387 className
= classPrefix
+ flag
;
3388 if ( flags
[ flag
] ) {
3390 if ( !this.flags
[ flag
] ) {
3391 changes
[ flag
] = true;
3392 this.flags
[ flag
] = true;
3393 add
.push( className
);
3397 if ( this.flags
[ flag
] ) {
3398 changes
[ flag
] = false;
3399 delete this.flags
[ flag
];
3400 remove
.push( className
);
3406 if ( this.$flagged
) {
3409 .removeClass( remove
);
3412 this.updateThemeClasses();
3413 this.emit( 'flag', changes
);
3419 * TitledElement is mixed into other classes to provide a `title` attribute.
3420 * Titles are rendered by the browser and are made visible when the user moves
3421 * the mouse over the element. Titles are not visible on touch devices.
3424 * // TitledElement provides a 'title' attribute to the
3425 * // ButtonWidget class
3426 * var button = new OO.ui.ButtonWidget( {
3427 * label: 'Button with Title',
3428 * title: 'I am a button'
3430 * $( 'body' ).append( button.$element );
3436 * @param {Object} [config] Configuration options
3437 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
3438 * If this config is omitted, the title functionality is applied to $element, the
3439 * element created by the class.
3440 * @cfg {string|Function} [title] The title text or a function that returns text. If
3441 * this config is omitted, the value of the {@link #static-title static title} property is used.
3443 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
3444 // Configuration initialization
3445 config
= config
|| {};
3448 this.$titled
= null;
3452 this.setTitle( config
.title
!== undefined ? config
.title
: this.constructor.static.title
);
3453 this.setTitledElement( config
.$titled
|| this.$element
);
3458 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
3460 /* Static Properties */
3463 * The title text, a function that returns text, or `null` for no title. The value of the static property
3464 * is overridden if the #title config option is used.
3468 * @property {string|Function|null}
3470 OO
.ui
.mixin
.TitledElement
.static.title
= null;
3475 * Set the titled element.
3477 * This method is used to retarget a TitledElement mixin so that its functionality applies to the specified element.
3478 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
3480 * @param {jQuery} $titled Element that should use the 'titled' functionality
3482 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
3483 if ( this.$titled
) {
3484 this.$titled
.removeAttr( 'title' );
3487 this.$titled
= $titled
;
3496 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
3498 * @return {OO.ui.Element} The element, for chaining
3500 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
3501 title
= typeof title
=== 'function' ? OO
.ui
.resolveMsg( title
) : title
;
3502 title
= ( typeof title
=== 'string' && title
.length
) ? title
: null;
3504 if ( this.title
!== title
) {
3513 * Update the title attribute, in case of changes to title or accessKey.
3517 * @return {OO.ui.Element} The element, for chaining
3519 OO
.ui
.mixin
.TitledElement
.prototype.updateTitle = function () {
3520 var title
= this.getTitle();
3521 if ( this.$titled
) {
3522 if ( title
!== null ) {
3523 // Only if this is an AccessKeyedElement
3524 if ( this.formatTitleWithAccessKey
) {
3525 title
= this.formatTitleWithAccessKey( title
);
3527 this.$titled
.attr( 'title', title
);
3529 this.$titled
.removeAttr( 'title' );
3538 * @return {string} Title string
3540 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
3545 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
3546 * Accesskeys allow an user to go to a specific element by using
3547 * a shortcut combination of a browser specific keys + the key
3551 * // AccessKeyedElement provides an 'accesskey' attribute to the
3552 * // ButtonWidget class
3553 * var button = new OO.ui.ButtonWidget( {
3554 * label: 'Button with Accesskey',
3557 * $( 'body' ).append( button.$element );
3563 * @param {Object} [config] Configuration options
3564 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3565 * If this config is omitted, the accesskey functionality is applied to $element, the
3566 * element created by the class.
3567 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3568 * this config is omitted, no accesskey will be added.
3570 OO
.ui
.mixin
.AccessKeyedElement
= function OoUiMixinAccessKeyedElement( config
) {
3571 // Configuration initialization
3572 config
= config
|| {};
3575 this.$accessKeyed
= null;
3576 this.accessKey
= null;
3579 this.setAccessKey( config
.accessKey
|| null );
3580 this.setAccessKeyedElement( config
.$accessKeyed
|| this.$element
);
3582 // If this is also a TitledElement and it initialized before we did, we may have
3583 // to update the title with the access key
3584 if ( this.updateTitle
) {
3591 OO
.initClass( OO
.ui
.mixin
.AccessKeyedElement
);
3593 /* Static Properties */
3596 * The access key, a function that returns a key, or `null` for no accesskey.
3600 * @property {string|Function|null}
3602 OO
.ui
.mixin
.AccessKeyedElement
.static.accessKey
= null;
3607 * Set the accesskeyed element.
3609 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
3610 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
3612 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyed' functionality
3614 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKeyedElement = function ( $accessKeyed
) {
3615 if ( this.$accessKeyed
) {
3616 this.$accessKeyed
.removeAttr( 'accesskey' );
3619 this.$accessKeyed
= $accessKeyed
;
3620 if ( this.accessKey
) {
3621 this.$accessKeyed
.attr( 'accesskey', this.accessKey
);
3628 * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no accesskey
3630 * @return {OO.ui.Element} The element, for chaining
3632 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKey = function ( accessKey
) {
3633 accessKey
= typeof accessKey
=== 'string' ? OO
.ui
.resolveMsg( accessKey
) : null;
3635 if ( this.accessKey
!== accessKey
) {
3636 if ( this.$accessKeyed
) {
3637 if ( accessKey
!== null ) {
3638 this.$accessKeyed
.attr( 'accesskey', accessKey
);
3640 this.$accessKeyed
.removeAttr( 'accesskey' );
3643 this.accessKey
= accessKey
;
3645 // Only if this is a TitledElement
3646 if ( this.updateTitle
) {
3657 * @return {string} accessKey string
3659 OO
.ui
.mixin
.AccessKeyedElement
.prototype.getAccessKey = function () {
3660 return this.accessKey
;
3664 * Add information about the access key to the element's tooltip label.
3665 * (This is only public for hacky usage in FieldLayout.)
3667 * @param {string} title Tooltip label for `title` attribute
3670 OO
.ui
.mixin
.AccessKeyedElement
.prototype.formatTitleWithAccessKey = function ( title
) {
3673 if ( !this.$accessKeyed
) {
3674 // Not initialized yet; the constructor will call updateTitle() which will rerun this function
3677 // Use jquery.accessKeyLabel if available to show modifiers, otherwise just display the single key
3678 if ( $.fn
.updateTooltipAccessKeys
&& $.fn
.updateTooltipAccessKeys
.getAccessKeyLabel
) {
3679 accessKey
= $.fn
.updateTooltipAccessKeys
.getAccessKeyLabel( this.$accessKeyed
[ 0 ] );
3681 accessKey
= this.getAccessKey();
3684 title
+= ' [' + accessKey
+ ']';
3690 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3691 * feels, and functionality can be customized via the class’s configuration options
3692 * and methods. Please see the [OOUI documentation on MediaWiki] [1] for more information
3695 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches
3698 * // A button widget
3699 * var button = new OO.ui.ButtonWidget( {
3700 * label: 'Button with Icon',
3704 * $( 'body' ).append( button.$element );
3706 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3709 * @extends OO.ui.Widget
3710 * @mixins OO.ui.mixin.ButtonElement
3711 * @mixins OO.ui.mixin.IconElement
3712 * @mixins OO.ui.mixin.IndicatorElement
3713 * @mixins OO.ui.mixin.LabelElement
3714 * @mixins OO.ui.mixin.TitledElement
3715 * @mixins OO.ui.mixin.FlaggedElement
3716 * @mixins OO.ui.mixin.TabIndexedElement
3717 * @mixins OO.ui.mixin.AccessKeyedElement
3720 * @param {Object} [config] Configuration options
3721 * @cfg {boolean} [active=false] Whether button should be shown as active
3722 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3723 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3724 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3726 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
3727 // Configuration initialization
3728 config
= config
|| {};
3730 // Parent constructor
3731 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
3733 // Mixin constructors
3734 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
3735 OO
.ui
.mixin
.IconElement
.call( this, config
);
3736 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
3737 OO
.ui
.mixin
.LabelElement
.call( this, config
);
3738 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
3739 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
3740 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
3741 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$button
} ) );
3746 this.noFollow
= false;
3749 this.connect( this, { disable
: 'onDisable' } );
3752 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
3754 .addClass( 'oo-ui-buttonWidget' )
3755 .append( this.$button
);
3756 this.setActive( config
.active
);
3757 this.setHref( config
.href
);
3758 this.setTarget( config
.target
);
3759 this.setNoFollow( config
.noFollow
);
3764 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
3765 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
3766 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
3767 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
3768 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
3769 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
3770 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
3771 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
3772 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
3774 /* Static Properties */
3780 OO
.ui
.ButtonWidget
.static.cancelButtonMouseDownEvents
= false;
3786 OO
.ui
.ButtonWidget
.static.tagName
= 'span';
3791 * Get hyperlink location.
3793 * @return {string} Hyperlink location
3795 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
3800 * Get hyperlink target.
3802 * @return {string} Hyperlink target
3804 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
3809 * Get search engine traversal hint.
3811 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3813 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
3814 return this.noFollow
;
3818 * Set hyperlink location.
3820 * @param {string|null} href Hyperlink location, null to remove
3822 * @return {OO.ui.Widget} The widget, for chaining
3824 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
3825 href
= typeof href
=== 'string' ? href
: null;
3826 if ( href
!== null && !OO
.ui
.isSafeUrl( href
) ) {
3830 if ( href
!== this.href
) {
3839 * Update the `href` attribute, in case of changes to href or
3844 * @return {OO.ui.Widget} The widget, for chaining
3846 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
3847 if ( this.href
!== null && !this.isDisabled() ) {
3848 this.$button
.attr( 'href', this.href
);
3850 this.$button
.removeAttr( 'href' );
3857 * Handle disable events.
3860 * @param {boolean} disabled Element is disabled
3862 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
3867 * Set hyperlink target.
3869 * @param {string|null} target Hyperlink target, null to remove
3870 * @return {OO.ui.Widget} The widget, for chaining
3872 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
3873 target
= typeof target
=== 'string' ? target
: null;
3875 if ( target
!== this.target
) {
3876 this.target
= target
;
3877 if ( target
!== null ) {
3878 this.$button
.attr( 'target', target
);
3880 this.$button
.removeAttr( 'target' );
3888 * Set search engine traversal hint.
3890 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3891 * @return {OO.ui.Widget} The widget, for chaining
3893 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
3894 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
3896 if ( noFollow
!== this.noFollow
) {
3897 this.noFollow
= noFollow
;
3899 this.$button
.attr( 'rel', 'nofollow' );
3901 this.$button
.removeAttr( 'rel' );
3908 // Override method visibility hints from ButtonElement
3919 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3920 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3921 * removed, and cleared from the group.
3924 * // Example: A ButtonGroupWidget with two buttons
3925 * var button1 = new OO.ui.PopupButtonWidget( {
3926 * label: 'Select a category',
3929 * $content: $( '<p>List of categories...</p>' ),
3934 * var button2 = new OO.ui.ButtonWidget( {
3937 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
3938 * items: [button1, button2]
3940 * $( 'body' ).append( buttonGroup.$element );
3943 * @extends OO.ui.Widget
3944 * @mixins OO.ui.mixin.GroupElement
3947 * @param {Object} [config] Configuration options
3948 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
3950 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
3951 // Configuration initialization
3952 config
= config
|| {};
3954 // Parent constructor
3955 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
3957 // Mixin constructors
3958 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
3961 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
3962 if ( Array
.isArray( config
.items
) ) {
3963 this.addItems( config
.items
);
3969 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
3970 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
3972 /* Static Properties */
3978 OO
.ui
.ButtonGroupWidget
.static.tagName
= 'span';
3986 * @return {OO.ui.Widget} The widget, for chaining
3988 OO
.ui
.ButtonGroupWidget
.prototype.focus = function () {
3989 if ( !this.isDisabled() ) {
3990 if ( this.items
[ 0 ] ) {
3991 this.items
[ 0 ].focus();
4000 OO
.ui
.ButtonGroupWidget
.prototype.simulateLabelClick = function () {
4005 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
4006 * which creates a label that identifies the icon’s function. See the [OOUI documentation on MediaWiki] [1]
4007 * for a list of icons included in the library.
4010 * // An icon widget with a label
4011 * var myIcon = new OO.ui.IconWidget( {
4015 * // Create a label.
4016 * var iconLabel = new OO.ui.LabelWidget( {
4019 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
4021 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
4024 * @extends OO.ui.Widget
4025 * @mixins OO.ui.mixin.IconElement
4026 * @mixins OO.ui.mixin.TitledElement
4027 * @mixins OO.ui.mixin.LabelElement
4028 * @mixins OO.ui.mixin.FlaggedElement
4031 * @param {Object} [config] Configuration options
4033 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
4034 // Configuration initialization
4035 config
= config
|| {};
4037 // Parent constructor
4038 OO
.ui
.IconWidget
.parent
.call( this, config
);
4040 // Mixin constructors
4041 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
4042 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
4043 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
, invisibleLabel
: true } ) );
4044 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
4047 this.$element
.addClass( 'oo-ui-iconWidget' );
4048 // Remove class added by LabelElement initialization. It causes unexpected CSS to apply when
4049 // nested in other widgets, because this widget used to not mix in LabelElement.
4050 this.$element
.removeClass( 'oo-ui-labelElement-label' );
4055 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
4056 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
4057 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
4058 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.LabelElement
);
4059 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
4061 /* Static Properties */
4067 OO
.ui
.IconWidget
.static.tagName
= 'span';
4070 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
4071 * attention to the status of an item or to clarify the function within a control. For a list of
4072 * indicators included in the library, please see the [OOUI documentation on MediaWiki][1].
4075 * // Example of an indicator widget
4076 * var indicator1 = new OO.ui.IndicatorWidget( {
4077 * indicator: 'required'
4080 * // Create a fieldset layout to add a label
4081 * var fieldset = new OO.ui.FieldsetLayout();
4082 * fieldset.addItems( [
4083 * new OO.ui.FieldLayout( indicator1, { label: 'A required indicator:' } )
4085 * $( 'body' ).append( fieldset.$element );
4087 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
4090 * @extends OO.ui.Widget
4091 * @mixins OO.ui.mixin.IndicatorElement
4092 * @mixins OO.ui.mixin.TitledElement
4093 * @mixins OO.ui.mixin.LabelElement
4096 * @param {Object} [config] Configuration options
4098 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
4099 // Configuration initialization
4100 config
= config
|| {};
4102 // Parent constructor
4103 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
4105 // Mixin constructors
4106 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
4107 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
4108 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
, invisibleLabel
: true } ) );
4111 this.$element
.addClass( 'oo-ui-indicatorWidget' );
4112 // Remove class added by LabelElement initialization. It causes unexpected CSS to apply when
4113 // nested in other widgets, because this widget used to not mix in LabelElement.
4114 this.$element
.removeClass( 'oo-ui-labelElement-label' );
4119 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
4120 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
4121 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
4122 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.LabelElement
);
4124 /* Static Properties */
4130 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
4133 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
4134 * be configured with a `label` option that is set to a string, a label node, or a function:
4136 * - String: a plaintext string
4137 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
4138 * label that includes a link or special styling, such as a gray color or additional graphical elements.
4139 * - Function: a function that will produce a string in the future. Functions are used
4140 * in cases where the value of the label is not currently defined.
4142 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
4143 * will come into focus when the label is clicked.
4146 * // Examples of LabelWidgets
4147 * var label1 = new OO.ui.LabelWidget( {
4148 * label: 'plaintext label'
4150 * var label2 = new OO.ui.LabelWidget( {
4151 * label: $( '<a href="default.html">jQuery label</a>' )
4153 * // Create a fieldset layout with fields for each example
4154 * var fieldset = new OO.ui.FieldsetLayout();
4155 * fieldset.addItems( [
4156 * new OO.ui.FieldLayout( label1 ),
4157 * new OO.ui.FieldLayout( label2 )
4159 * $( 'body' ).append( fieldset.$element );
4162 * @extends OO.ui.Widget
4163 * @mixins OO.ui.mixin.LabelElement
4164 * @mixins OO.ui.mixin.TitledElement
4167 * @param {Object} [config] Configuration options
4168 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
4169 * Clicking the label will focus the specified input field.
4171 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
4172 // Configuration initialization
4173 config
= config
|| {};
4175 // Parent constructor
4176 OO
.ui
.LabelWidget
.parent
.call( this, config
);
4178 // Mixin constructors
4179 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
4180 OO
.ui
.mixin
.TitledElement
.call( this, config
);
4183 this.input
= config
.input
;
4187 if ( this.input
.getInputId() ) {
4188 this.$element
.attr( 'for', this.input
.getInputId() );
4190 this.$label
.on( 'click', function () {
4191 this.input
.simulateLabelClick();
4195 this.$element
.addClass( 'oo-ui-labelWidget' );
4200 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
4201 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
4202 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
4204 /* Static Properties */
4210 OO
.ui
.LabelWidget
.static.tagName
= 'label';
4213 * PendingElement is a mixin that is used to create elements that notify users that something is happening
4214 * and that they should wait before proceeding. The pending state is visually represented with a pending
4215 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
4216 * field of a {@link OO.ui.TextInputWidget text input widget}.
4218 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
4219 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
4220 * in process dialogs.
4223 * function MessageDialog( config ) {
4224 * MessageDialog.parent.call( this, config );
4226 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
4228 * MessageDialog.static.name = 'myMessageDialog';
4229 * MessageDialog.static.actions = [
4230 * { action: 'save', label: 'Done', flags: 'primary' },
4231 * { label: 'Cancel', flags: 'safe' }
4234 * MessageDialog.prototype.initialize = function () {
4235 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
4236 * this.content = new OO.ui.PanelLayout( { padded: true } );
4237 * 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>' );
4238 * this.$body.append( this.content.$element );
4240 * MessageDialog.prototype.getBodyHeight = function () {
4243 * MessageDialog.prototype.getActionProcess = function ( action ) {
4244 * var dialog = this;
4245 * if ( action === 'save' ) {
4246 * dialog.getActions().get({actions: 'save'})[0].pushPending();
4247 * return new OO.ui.Process()
4249 * .next( function () {
4250 * dialog.getActions().get({actions: 'save'})[0].popPending();
4253 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
4256 * var windowManager = new OO.ui.WindowManager();
4257 * $( 'body' ).append( windowManager.$element );
4259 * var dialog = new MessageDialog();
4260 * windowManager.addWindows( [ dialog ] );
4261 * windowManager.openWindow( dialog );
4267 * @param {Object} [config] Configuration options
4268 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
4270 OO
.ui
.mixin
.PendingElement
= function OoUiMixinPendingElement( config
) {
4271 // Configuration initialization
4272 config
= config
|| {};
4276 this.$pending
= null;
4279 this.setPendingElement( config
.$pending
|| this.$element
);
4284 OO
.initClass( OO
.ui
.mixin
.PendingElement
);
4289 * Set the pending element (and clean up any existing one).
4291 * @param {jQuery} $pending The element to set to pending.
4293 OO
.ui
.mixin
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
4294 if ( this.$pending
) {
4295 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
4298 this.$pending
= $pending
;
4299 if ( this.pending
> 0 ) {
4300 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
4305 * Check if an element is pending.
4307 * @return {boolean} Element is pending
4309 OO
.ui
.mixin
.PendingElement
.prototype.isPending = function () {
4310 return !!this.pending
;
4314 * Increase the pending counter. The pending state will remain active until the counter is zero
4315 * (i.e., the number of calls to #pushPending and #popPending is the same).
4318 * @return {OO.ui.Element} The element, for chaining
4320 OO
.ui
.mixin
.PendingElement
.prototype.pushPending = function () {
4321 if ( this.pending
=== 0 ) {
4322 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
4323 this.updateThemeClasses();
4331 * Decrease the pending counter. The pending state will remain active until the counter is zero
4332 * (i.e., the number of calls to #pushPending and #popPending is the same).
4335 * @return {OO.ui.Element} The element, for chaining
4337 OO
.ui
.mixin
.PendingElement
.prototype.popPending = function () {
4338 if ( this.pending
=== 1 ) {
4339 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
4340 this.updateThemeClasses();
4342 this.pending
= Math
.max( 0, this.pending
- 1 );
4348 * Element that will stick adjacent to a specified container, even when it is inserted elsewhere
4349 * in the document (for example, in an OO.ui.Window's $overlay).
4351 * The elements's position is automatically calculated and maintained when window is resized or the
4352 * page is scrolled. If you reposition the container manually, you have to call #position to make
4353 * sure the element is still placed correctly.
4355 * As positioning is only possible when both the element and the container are attached to the DOM
4356 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
4357 * the #toggle method to display a floating popup, for example.
4363 * @param {Object} [config] Configuration options
4364 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
4365 * @cfg {jQuery} [$floatableContainer] Node to position adjacent to
4366 * @cfg {string} [verticalPosition='below'] Where to position $floatable vertically:
4367 * 'below': Directly below $floatableContainer, aligning f's top edge with fC's bottom edge
4368 * 'above': Directly above $floatableContainer, aligning f's bottom edge with fC's top edge
4369 * 'top': Align the top edge with $floatableContainer's top edge
4370 * 'bottom': Align the bottom edge with $floatableContainer's bottom edge
4371 * 'center': Vertically align the center with $floatableContainer's center
4372 * @cfg {string} [horizontalPosition='start'] Where to position $floatable horizontally:
4373 * 'before': Directly before $floatableContainer, aligning f's end edge with fC's start edge
4374 * 'after': Directly after $floatableContainer, aligning f's start edge with fC's end edge
4375 * 'start': Align the start (left in LTR, right in RTL) edge with $floatableContainer's start edge
4376 * 'end': Align the end (right in LTR, left in RTL) edge with $floatableContainer's end edge
4377 * 'center': Horizontally align the center with $floatableContainer's center
4378 * @cfg {boolean} [hideWhenOutOfView=true] Whether to hide the floatable element if the container
4381 OO
.ui
.mixin
.FloatableElement
= function OoUiMixinFloatableElement( config
) {
4382 // Configuration initialization
4383 config
= config
|| {};
4386 this.$floatable
= null;
4387 this.$floatableContainer
= null;
4388 this.$floatableWindow
= null;
4389 this.$floatableClosestScrollable
= null;
4390 this.floatableOutOfView
= false;
4391 this.onFloatableScrollHandler
= this.position
.bind( this );
4392 this.onFloatableWindowResizeHandler
= this.position
.bind( this );
4395 this.setFloatableContainer( config
.$floatableContainer
);
4396 this.setFloatableElement( config
.$floatable
|| this.$element
);
4397 this.setVerticalPosition( config
.verticalPosition
|| 'below' );
4398 this.setHorizontalPosition( config
.horizontalPosition
|| 'start' );
4399 this.hideWhenOutOfView
= config
.hideWhenOutOfView
=== undefined ? true : !!config
.hideWhenOutOfView
;
4405 * Set floatable element.
4407 * If an element is already set, it will be cleaned up before setting up the new element.
4409 * @param {jQuery} $floatable Element to make floatable
4411 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableElement = function ( $floatable
) {
4412 if ( this.$floatable
) {
4413 this.$floatable
.removeClass( 'oo-ui-floatableElement-floatable' );
4414 this.$floatable
.css( { left
: '', top
: '' } );
4417 this.$floatable
= $floatable
.addClass( 'oo-ui-floatableElement-floatable' );
4422 * Set floatable container.
4424 * The element will be positioned relative to the specified container.
4426 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
4428 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableContainer = function ( $floatableContainer
) {
4429 this.$floatableContainer
= $floatableContainer
;
4430 if ( this.$floatable
) {
4436 * Change how the element is positioned vertically.
4438 * @param {string} position 'below', 'above', 'top', 'bottom' or 'center'
4440 OO
.ui
.mixin
.FloatableElement
.prototype.setVerticalPosition = function ( position
) {
4441 if ( [ 'below', 'above', 'top', 'bottom', 'center' ].indexOf( position
) === -1 ) {
4442 throw new Error( 'Invalid value for vertical position: ' + position
);
4444 if ( this.verticalPosition
!== position
) {
4445 this.verticalPosition
= position
;
4446 if ( this.$floatable
) {
4453 * Change how the element is positioned horizontally.
4455 * @param {string} position 'before', 'after', 'start', 'end' or 'center'
4457 OO
.ui
.mixin
.FloatableElement
.prototype.setHorizontalPosition = function ( position
) {
4458 if ( [ 'before', 'after', 'start', 'end', 'center' ].indexOf( position
) === -1 ) {
4459 throw new Error( 'Invalid value for horizontal position: ' + position
);
4461 if ( this.horizontalPosition
!== position
) {
4462 this.horizontalPosition
= position
;
4463 if ( this.$floatable
) {
4470 * Toggle positioning.
4472 * Do not turn positioning on until after the element is attached to the DOM and visible.
4474 * @param {boolean} [positioning] Enable positioning, omit to toggle
4476 * @return {OO.ui.Element} The element, for chaining
4478 OO
.ui
.mixin
.FloatableElement
.prototype.togglePositioning = function ( positioning
) {
4479 var closestScrollableOfContainer
;
4481 if ( !this.$floatable
|| !this.$floatableContainer
) {
4485 positioning
= positioning
=== undefined ? !this.positioning
: !!positioning
;
4487 if ( positioning
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4488 OO
.ui
.warnDeprecation( 'FloatableElement#togglePositioning: Before calling this method, the element must be attached to the DOM.' );
4489 this.warnedUnattached
= true;
4492 if ( this.positioning
!== positioning
) {
4493 this.positioning
= positioning
;
4495 closestScrollableOfContainer
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatableContainer
[ 0 ] );
4496 // If the scrollable is the root, we have to listen to scroll events
4497 // on the window because of browser inconsistencies.
4498 if ( $( closestScrollableOfContainer
).is( 'html, body' ) ) {
4499 closestScrollableOfContainer
= OO
.ui
.Element
.static.getWindow( closestScrollableOfContainer
);
4502 if ( positioning
) {
4503 this.$floatableWindow
= $( this.getElementWindow() );
4504 this.$floatableWindow
.on( 'resize', this.onFloatableWindowResizeHandler
);
4506 this.$floatableClosestScrollable
= $( closestScrollableOfContainer
);
4507 this.$floatableClosestScrollable
.on( 'scroll', this.onFloatableScrollHandler
);
4509 // Initial position after visible
4512 if ( this.$floatableWindow
) {
4513 this.$floatableWindow
.off( 'resize', this.onFloatableWindowResizeHandler
);
4514 this.$floatableWindow
= null;
4517 if ( this.$floatableClosestScrollable
) {
4518 this.$floatableClosestScrollable
.off( 'scroll', this.onFloatableScrollHandler
);
4519 this.$floatableClosestScrollable
= null;
4522 this.$floatable
.css( { left
: '', right
: '', top
: '' } );
4530 * Check whether the bottom edge of the given element is within the viewport of the given container.
4533 * @param {jQuery} $element
4534 * @param {jQuery} $container
4537 OO
.ui
.mixin
.FloatableElement
.prototype.isElementInViewport = function ( $element
, $container
) {
4538 var elemRect
, contRect
, topEdgeInBounds
, bottomEdgeInBounds
, leftEdgeInBounds
, rightEdgeInBounds
,
4539 startEdgeInBounds
, endEdgeInBounds
, viewportSpacing
,
4540 direction
= $element
.css( 'direction' );
4542 elemRect
= $element
[ 0 ].getBoundingClientRect();
4543 if ( $container
[ 0 ] === window
) {
4544 viewportSpacing
= OO
.ui
.getViewportSpacing();
4548 right
: document
.documentElement
.clientWidth
,
4549 bottom
: document
.documentElement
.clientHeight
4551 contRect
.top
+= viewportSpacing
.top
;
4552 contRect
.left
+= viewportSpacing
.left
;
4553 contRect
.right
-= viewportSpacing
.right
;
4554 contRect
.bottom
-= viewportSpacing
.bottom
;
4556 contRect
= $container
[ 0 ].getBoundingClientRect();
4559 topEdgeInBounds
= elemRect
.top
>= contRect
.top
&& elemRect
.top
<= contRect
.bottom
;
4560 bottomEdgeInBounds
= elemRect
.bottom
>= contRect
.top
&& elemRect
.bottom
<= contRect
.bottom
;
4561 leftEdgeInBounds
= elemRect
.left
>= contRect
.left
&& elemRect
.left
<= contRect
.right
;
4562 rightEdgeInBounds
= elemRect
.right
>= contRect
.left
&& elemRect
.right
<= contRect
.right
;
4563 if ( direction
=== 'rtl' ) {
4564 startEdgeInBounds
= rightEdgeInBounds
;
4565 endEdgeInBounds
= leftEdgeInBounds
;
4567 startEdgeInBounds
= leftEdgeInBounds
;
4568 endEdgeInBounds
= rightEdgeInBounds
;
4571 if ( this.verticalPosition
=== 'below' && !bottomEdgeInBounds
) {
4574 if ( this.verticalPosition
=== 'above' && !topEdgeInBounds
) {
4577 if ( this.horizontalPosition
=== 'before' && !startEdgeInBounds
) {
4580 if ( this.horizontalPosition
=== 'after' && !endEdgeInBounds
) {
4584 // The other positioning values are all about being inside the container,
4585 // so in those cases all we care about is that any part of the container is visible.
4586 return elemRect
.top
<= contRect
.bottom
&& elemRect
.bottom
>= contRect
.top
&&
4587 elemRect
.left
<= contRect
.right
&& elemRect
.right
>= contRect
.left
;
4591 * Check if the floatable is hidden to the user because it was offscreen.
4593 * @return {boolean} Floatable is out of view
4595 OO
.ui
.mixin
.FloatableElement
.prototype.isFloatableOutOfView = function () {
4596 return this.floatableOutOfView
;
4600 * Position the floatable below its container.
4602 * This should only be done when both of them are attached to the DOM and visible.
4605 * @return {OO.ui.Element} The element, for chaining
4607 OO
.ui
.mixin
.FloatableElement
.prototype.position = function () {
4608 if ( !this.positioning
) {
4613 // To continue, some things need to be true:
4614 // The element must actually be in the DOM
4615 this.isElementAttached() && (
4616 // The closest scrollable is the current window
4617 this.$floatableClosestScrollable
[ 0 ] === this.getElementWindow() ||
4618 // OR is an element in the element's DOM
4619 $.contains( this.getElementDocument(), this.$floatableClosestScrollable
[ 0 ] )
4622 // Abort early if important parts of the widget are no longer attached to the DOM
4626 this.floatableOutOfView
= this.hideWhenOutOfView
&& !this.isElementInViewport( this.$floatableContainer
, this.$floatableClosestScrollable
);
4627 if ( this.floatableOutOfView
) {
4628 this.$floatable
.addClass( 'oo-ui-element-hidden' );
4631 this.$floatable
.removeClass( 'oo-ui-element-hidden' );
4634 this.$floatable
.css( this.computePosition() );
4636 // We updated the position, so re-evaluate the clipping state.
4637 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
4638 // will not notice the need to update itself.)
4639 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
4640 // it not listen to the right events in the right places?
4649 * Compute how #$floatable should be positioned based on the position of #$floatableContainer
4650 * and the positioning settings. This is a helper for #position that shouldn't be called directly,
4651 * but may be overridden by subclasses if they want to change or add to the positioning logic.
4653 * @return {Object} New position to apply with .css(). Keys are 'top', 'left', 'bottom' and 'right'.
4655 OO
.ui
.mixin
.FloatableElement
.prototype.computePosition = function () {
4656 var isBody
, scrollableX
, scrollableY
, containerPos
,
4657 horizScrollbarHeight
, vertScrollbarWidth
, scrollTop
, scrollLeft
,
4658 newPos
= { top
: '', left
: '', bottom
: '', right
: '' },
4659 direction
= this.$floatableContainer
.css( 'direction' ),
4660 $offsetParent
= this.$floatable
.offsetParent();
4662 if ( $offsetParent
.is( 'html' ) ) {
4663 // The innerHeight/Width and clientHeight/Width calculations don't work well on the
4664 // <html> element, but they do work on the <body>
4665 $offsetParent
= $( $offsetParent
[ 0 ].ownerDocument
.body
);
4667 isBody
= $offsetParent
.is( 'body' );
4668 scrollableX
= $offsetParent
.css( 'overflow-x' ) === 'scroll' || $offsetParent
.css( 'overflow-x' ) === 'auto';
4669 scrollableY
= $offsetParent
.css( 'overflow-y' ) === 'scroll' || $offsetParent
.css( 'overflow-y' ) === 'auto';
4671 vertScrollbarWidth
= $offsetParent
.innerWidth() - $offsetParent
.prop( 'clientWidth' );
4672 horizScrollbarHeight
= $offsetParent
.innerHeight() - $offsetParent
.prop( 'clientHeight' );
4673 // We don't need to compute and add scrollTop and scrollLeft if the scrollable container is the body,
4674 // or if it isn't scrollable
4675 scrollTop
= scrollableY
&& !isBody
? $offsetParent
.scrollTop() : 0;
4676 scrollLeft
= scrollableX
&& !isBody
? OO
.ui
.Element
.static.getScrollLeft( $offsetParent
[ 0 ] ) : 0;
4678 // Avoid passing the <body> to getRelativePosition(), because it won't return what we expect
4679 // if the <body> has a margin
4680 containerPos
= isBody
?
4681 this.$floatableContainer
.offset() :
4682 OO
.ui
.Element
.static.getRelativePosition( this.$floatableContainer
, $offsetParent
);
4683 containerPos
.bottom
= containerPos
.top
+ this.$floatableContainer
.outerHeight();
4684 containerPos
.right
= containerPos
.left
+ this.$floatableContainer
.outerWidth();
4685 containerPos
.start
= direction
=== 'rtl' ? containerPos
.right
: containerPos
.left
;
4686 containerPos
.end
= direction
=== 'rtl' ? containerPos
.left
: containerPos
.right
;
4688 if ( this.verticalPosition
=== 'below' ) {
4689 newPos
.top
= containerPos
.bottom
;
4690 } else if ( this.verticalPosition
=== 'above' ) {
4691 newPos
.bottom
= $offsetParent
.outerHeight() - containerPos
.top
;
4692 } else if ( this.verticalPosition
=== 'top' ) {
4693 newPos
.top
= containerPos
.top
;
4694 } else if ( this.verticalPosition
=== 'bottom' ) {
4695 newPos
.bottom
= $offsetParent
.outerHeight() - containerPos
.bottom
;
4696 } else if ( this.verticalPosition
=== 'center' ) {
4697 newPos
.top
= containerPos
.top
+
4698 ( this.$floatableContainer
.height() - this.$floatable
.height() ) / 2;
4701 if ( this.horizontalPosition
=== 'before' ) {
4702 newPos
.end
= containerPos
.start
;
4703 } else if ( this.horizontalPosition
=== 'after' ) {
4704 newPos
.start
= containerPos
.end
;
4705 } else if ( this.horizontalPosition
=== 'start' ) {
4706 newPos
.start
= containerPos
.start
;
4707 } else if ( this.horizontalPosition
=== 'end' ) {
4708 newPos
.end
= containerPos
.end
;
4709 } else if ( this.horizontalPosition
=== 'center' ) {
4710 newPos
.left
= containerPos
.left
+
4711 ( this.$floatableContainer
.width() - this.$floatable
.width() ) / 2;
4714 if ( newPos
.start
!== undefined ) {
4715 if ( direction
=== 'rtl' ) {
4716 newPos
.right
= ( isBody
? $( $offsetParent
[ 0 ].ownerDocument
.documentElement
) : $offsetParent
).outerWidth() - newPos
.start
;
4718 newPos
.left
= newPos
.start
;
4720 delete newPos
.start
;
4722 if ( newPos
.end
!== undefined ) {
4723 if ( direction
=== 'rtl' ) {
4724 newPos
.left
= newPos
.end
;
4726 newPos
.right
= ( isBody
? $( $offsetParent
[ 0 ].ownerDocument
.documentElement
) : $offsetParent
).outerWidth() - newPos
.end
;
4731 // Account for scroll position
4732 if ( newPos
.top
!== '' ) {
4733 newPos
.top
+= scrollTop
;
4735 if ( newPos
.bottom
!== '' ) {
4736 newPos
.bottom
-= scrollTop
;
4738 if ( newPos
.left
!== '' ) {
4739 newPos
.left
+= scrollLeft
;
4741 if ( newPos
.right
!== '' ) {
4742 newPos
.right
-= scrollLeft
;
4745 // Account for scrollbar gutter
4746 if ( newPos
.bottom
!== '' ) {
4747 newPos
.bottom
-= horizScrollbarHeight
;
4749 if ( direction
=== 'rtl' ) {
4750 if ( newPos
.left
!== '' ) {
4751 newPos
.left
-= vertScrollbarWidth
;
4754 if ( newPos
.right
!== '' ) {
4755 newPos
.right
-= vertScrollbarWidth
;
4763 * Element that can be automatically clipped to visible boundaries.
4765 * Whenever the element's natural height changes, you have to call
4766 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
4767 * clipping correctly.
4769 * The dimensions of #$clippableContainer will be compared to the boundaries of the
4770 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
4771 * then #$clippable will be given a fixed reduced height and/or width and will be made
4772 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
4773 * but you can build a static footer by setting #$clippableContainer to an element that contains
4774 * #$clippable and the footer.
4780 * @param {Object} [config] Configuration options
4781 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
4782 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
4783 * omit to use #$clippable
4785 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
4786 // Configuration initialization
4787 config
= config
|| {};
4790 this.$clippable
= null;
4791 this.$clippableContainer
= null;
4792 this.clipping
= false;
4793 this.clippedHorizontally
= false;
4794 this.clippedVertically
= false;
4795 this.$clippableScrollableContainer
= null;
4796 this.$clippableScroller
= null;
4797 this.$clippableWindow
= null;
4798 this.idealWidth
= null;
4799 this.idealHeight
= null;
4800 this.onClippableScrollHandler
= this.clip
.bind( this );
4801 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
4804 if ( config
.$clippableContainer
) {
4805 this.setClippableContainer( config
.$clippableContainer
);
4807 this.setClippableElement( config
.$clippable
|| this.$element
);
4813 * Set clippable element.
4815 * If an element is already set, it will be cleaned up before setting up the new element.
4817 * @param {jQuery} $clippable Element to make clippable
4819 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
4820 if ( this.$clippable
) {
4821 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
4822 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
4823 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4826 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
4831 * Set clippable container.
4833 * This is the container that will be measured when deciding whether to clip. When clipping,
4834 * #$clippable will be resized in order to keep the clippable container fully visible.
4836 * If the clippable container is unset, #$clippable will be used.
4838 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
4840 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableContainer = function ( $clippableContainer
) {
4841 this.$clippableContainer
= $clippableContainer
;
4842 if ( this.$clippable
) {
4850 * Do not turn clipping on until after the element is attached to the DOM and visible.
4852 * @param {boolean} [clipping] Enable clipping, omit to toggle
4854 * @return {OO.ui.Element} The element, for chaining
4856 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
4857 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
4859 if ( clipping
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4860 OO
.ui
.warnDeprecation( 'ClippableElement#toggleClipping: Before calling this method, the element must be attached to the DOM.' );
4861 this.warnedUnattached
= true;
4864 if ( this.clipping
!== clipping
) {
4865 this.clipping
= clipping
;
4867 this.$clippableScrollableContainer
= $( this.getClosestScrollableElementContainer() );
4868 // If the clippable container is the root, we have to listen to scroll events and check
4869 // jQuery.scrollTop on the window because of browser inconsistencies
4870 this.$clippableScroller
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
4871 $( OO
.ui
.Element
.static.getWindow( this.$clippableScrollableContainer
) ) :
4872 this.$clippableScrollableContainer
;
4873 this.$clippableScroller
.on( 'scroll', this.onClippableScrollHandler
);
4874 this.$clippableWindow
= $( this.getElementWindow() )
4875 .on( 'resize', this.onClippableWindowResizeHandler
);
4876 // Initial clip after visible
4879 this.$clippable
.css( {
4887 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4889 this.$clippableScrollableContainer
= null;
4890 this.$clippableScroller
.off( 'scroll', this.onClippableScrollHandler
);
4891 this.$clippableScroller
= null;
4892 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
4893 this.$clippableWindow
= null;
4901 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4903 * @return {boolean} Element will be clipped to the visible area
4905 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
4906 return this.clipping
;
4910 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
4912 * @return {boolean} Part of the element is being clipped
4914 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
4915 return this.clippedHorizontally
|| this.clippedVertically
;
4919 * Check if the right of the element is being clipped by the nearest scrollable container.
4921 * @return {boolean} Part of the element is being clipped
4923 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
4924 return this.clippedHorizontally
;
4928 * Check if the bottom of the element is being clipped by the nearest scrollable container.
4930 * @return {boolean} Part of the element is being clipped
4932 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
4933 return this.clippedVertically
;
4937 * Set the ideal size. These are the dimensions #$clippable will have when it's not being clipped.
4939 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
4940 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
4942 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
4943 this.idealWidth
= width
;
4944 this.idealHeight
= height
;
4946 if ( !this.clipping
) {
4947 // Update dimensions
4948 this.$clippable
.css( { width
: width
, height
: height
} );
4950 // While clipping, idealWidth and idealHeight are not considered
4954 * Return the side of the clippable on which it is "anchored" (aligned to something else).
4955 * ClippableElement will clip the opposite side when reducing element's width.
4957 * Classes that mix in ClippableElement should override this to return 'right' if their
4958 * clippable is absolutely positioned and using 'right: Npx' (and not using 'left').
4959 * If your class also mixes in FloatableElement, this is handled automatically.
4961 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
4962 * always in pixels, even if they were unset or set to 'auto'.)
4964 * When in doubt, 'left' (or 'right' in RTL) is a sane fallback.
4966 * @return {string} 'left' or 'right'
4968 OO
.ui
.mixin
.ClippableElement
.prototype.getHorizontalAnchorEdge = function () {
4969 if ( this.computePosition
&& this.positioning
&& this.computePosition().right
!== '' ) {
4976 * Return the side of the clippable on which it is "anchored" (aligned to something else).
4977 * ClippableElement will clip the opposite side when reducing element's width.
4979 * Classes that mix in ClippableElement should override this to return 'bottom' if their
4980 * clippable is absolutely positioned and using 'bottom: Npx' (and not using 'top').
4981 * If your class also mixes in FloatableElement, this is handled automatically.
4983 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
4984 * always in pixels, even if they were unset or set to 'auto'.)
4986 * When in doubt, 'top' is a sane fallback.
4988 * @return {string} 'top' or 'bottom'
4990 OO
.ui
.mixin
.ClippableElement
.prototype.getVerticalAnchorEdge = function () {
4991 if ( this.computePosition
&& this.positioning
&& this.computePosition().bottom
!== '' ) {
4998 * Clip element to visible boundaries and allow scrolling when needed. You should call this method
4999 * when the element's natural height changes.
5001 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
5002 * overlapped by, the visible area of the nearest scrollable container.
5004 * Because calling clip() when the natural height changes isn't always possible, we also set
5005 * max-height when the element isn't being clipped. This means that if the element tries to grow
5006 * beyond the edge, something reasonable will happen before clip() is called.
5009 * @return {OO.ui.Element} The element, for chaining
5011 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
5012 var extraHeight
, extraWidth
, viewportSpacing
,
5013 desiredWidth
, desiredHeight
, allotedWidth
, allotedHeight
,
5014 naturalWidth
, naturalHeight
, clipWidth
, clipHeight
,
5015 $item
, itemRect
, $viewport
, viewportRect
, availableRect
,
5016 direction
, vertScrollbarWidth
, horizScrollbarHeight
,
5017 // Extra tolerance so that the sloppy code below doesn't result in results that are off
5018 // by one or two pixels. (And also so that we have space to display drop shadows.)
5019 // Chosen by fair dice roll.
5022 if ( !this.clipping
) {
5023 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
5027 function rectIntersection( a
, b
) {
5029 out
.top
= Math
.max( a
.top
, b
.top
);
5030 out
.left
= Math
.max( a
.left
, b
.left
);
5031 out
.bottom
= Math
.min( a
.bottom
, b
.bottom
);
5032 out
.right
= Math
.min( a
.right
, b
.right
);
5036 viewportSpacing
= OO
.ui
.getViewportSpacing();
5038 if ( this.$clippableScrollableContainer
.is( 'html, body' ) ) {
5039 $viewport
= $( this.$clippableScrollableContainer
[ 0 ].ownerDocument
.body
);
5040 // Dimensions of the browser window, rather than the element!
5044 right
: document
.documentElement
.clientWidth
,
5045 bottom
: document
.documentElement
.clientHeight
5047 viewportRect
.top
+= viewportSpacing
.top
;
5048 viewportRect
.left
+= viewportSpacing
.left
;
5049 viewportRect
.right
-= viewportSpacing
.right
;
5050 viewportRect
.bottom
-= viewportSpacing
.bottom
;
5052 $viewport
= this.$clippableScrollableContainer
;
5053 viewportRect
= $viewport
[ 0 ].getBoundingClientRect();
5054 // Convert into a plain object
5055 viewportRect
= $.extend( {}, viewportRect
);
5058 // Account for scrollbar gutter
5059 direction
= $viewport
.css( 'direction' );
5060 vertScrollbarWidth
= $viewport
.innerWidth() - $viewport
.prop( 'clientWidth' );
5061 horizScrollbarHeight
= $viewport
.innerHeight() - $viewport
.prop( 'clientHeight' );
5062 viewportRect
.bottom
-= horizScrollbarHeight
;
5063 if ( direction
=== 'rtl' ) {
5064 viewportRect
.left
+= vertScrollbarWidth
;
5066 viewportRect
.right
-= vertScrollbarWidth
;
5069 // Add arbitrary tolerance
5070 viewportRect
.top
+= buffer
;
5071 viewportRect
.left
+= buffer
;
5072 viewportRect
.right
-= buffer
;
5073 viewportRect
.bottom
-= buffer
;
5075 $item
= this.$clippableContainer
|| this.$clippable
;
5077 extraHeight
= $item
.outerHeight() - this.$clippable
.outerHeight();
5078 extraWidth
= $item
.outerWidth() - this.$clippable
.outerWidth();
5080 itemRect
= $item
[ 0 ].getBoundingClientRect();
5081 // Convert into a plain object
5082 itemRect
= $.extend( {}, itemRect
);
5084 // Item might already be clipped, so we can't just use its dimensions (in case we might need to
5085 // make it larger than before). Extend the rectangle to the maximum size we are allowed to take.
5086 if ( this.getHorizontalAnchorEdge() === 'right' ) {
5087 itemRect
.left
= viewportRect
.left
;
5089 itemRect
.right
= viewportRect
.right
;
5091 if ( this.getVerticalAnchorEdge() === 'bottom' ) {
5092 itemRect
.top
= viewportRect
.top
;
5094 itemRect
.bottom
= viewportRect
.bottom
;
5097 availableRect
= rectIntersection( viewportRect
, itemRect
);
5099 desiredWidth
= Math
.max( 0, availableRect
.right
- availableRect
.left
);
5100 desiredHeight
= Math
.max( 0, availableRect
.bottom
- availableRect
.top
);
5101 // It should never be desirable to exceed the dimensions of the browser viewport... right?
5102 desiredWidth
= Math
.min( desiredWidth
,
5103 document
.documentElement
.clientWidth
- viewportSpacing
.left
- viewportSpacing
.right
);
5104 desiredHeight
= Math
.min( desiredHeight
,
5105 document
.documentElement
.clientHeight
- viewportSpacing
.top
- viewportSpacing
.right
);
5106 allotedWidth
= Math
.ceil( desiredWidth
- extraWidth
);
5107 allotedHeight
= Math
.ceil( desiredHeight
- extraHeight
);
5108 naturalWidth
= this.$clippable
.prop( 'scrollWidth' );
5109 naturalHeight
= this.$clippable
.prop( 'scrollHeight' );
5110 clipWidth
= allotedWidth
< naturalWidth
;
5111 clipHeight
= allotedHeight
< naturalHeight
;
5114 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. See T157672.
5115 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
5116 this.$clippable
.css( 'overflowX', 'scroll' );
5117 // eslint-disable-next-line no-void
5118 void this.$clippable
[ 0 ].offsetHeight
; // Force reflow
5119 this.$clippable
.css( {
5120 width
: Math
.max( 0, allotedWidth
),
5124 this.$clippable
.css( {
5126 width
: this.idealWidth
|| '',
5127 maxWidth
: Math
.max( 0, allotedWidth
)
5131 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. See T157672.
5132 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
5133 this.$clippable
.css( 'overflowY', 'scroll' );
5134 // eslint-disable-next-line no-void
5135 void this.$clippable
[ 0 ].offsetHeight
; // Force reflow
5136 this.$clippable
.css( {
5137 height
: Math
.max( 0, allotedHeight
),
5141 this.$clippable
.css( {
5143 height
: this.idealHeight
|| '',
5144 maxHeight
: Math
.max( 0, allotedHeight
)
5148 // If we stopped clipping in at least one of the dimensions
5149 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
5150 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
5153 this.clippedHorizontally
= clipWidth
;
5154 this.clippedVertically
= clipHeight
;
5160 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
5161 * By default, each popup has an anchor that points toward its origin.
5162 * Please see the [OOUI documentation on MediaWiki.org] [1] for more information and examples.
5164 * Unlike most widgets, PopupWidget is initially hidden and must be shown by calling #toggle.
5167 * // A popup widget.
5168 * var popup = new OO.ui.PopupWidget( {
5169 * $content: $( '<p>Hi there!</p>' ),
5174 * $( 'body' ).append( popup.$element );
5175 * // To display the popup, toggle the visibility to 'true'.
5176 * popup.toggle( true );
5178 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups
5181 * @extends OO.ui.Widget
5182 * @mixins OO.ui.mixin.LabelElement
5183 * @mixins OO.ui.mixin.ClippableElement
5184 * @mixins OO.ui.mixin.FloatableElement
5187 * @param {Object} [config] Configuration options
5188 * @cfg {number|null} [width=320] Width of popup in pixels. Pass `null` to use automatic width.
5189 * @cfg {number|null} [height=null] Height of popup in pixels. Pass `null` to use automatic height.
5190 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
5191 * @cfg {string} [position='below'] Where to position the popup relative to $floatableContainer
5192 * 'above': Put popup above $floatableContainer; anchor points down to the horizontal center
5193 * of $floatableContainer
5194 * 'below': Put popup below $floatableContainer; anchor points up to the horizontal center
5195 * of $floatableContainer
5196 * 'before': Put popup to the left (LTR) / right (RTL) of $floatableContainer; anchor points
5197 * endwards (right/left) to the vertical center of $floatableContainer
5198 * 'after': Put popup to the right (LTR) / left (RTL) of $floatableContainer; anchor points
5199 * startwards (left/right) to the vertical center of $floatableContainer
5200 * @cfg {string} [align='center'] How to align the popup to $floatableContainer
5201 * 'forwards': If position is above/below, move the popup as far endwards (right in LTR, left in RTL)
5202 * as possible while still keeping the anchor within the popup;
5203 * if position is before/after, move the popup as far downwards as possible.
5204 * 'backwards': If position is above/below, move the popup as far startwards (left in LTR, right in RTL)
5205 * as possible while still keeping the anchor within the popup;
5206 * if position in before/after, move the popup as far upwards as possible.
5207 * 'center': Horizontally (if position is above/below) or vertically (before/after) align the center
5208 * of the popup with the center of $floatableContainer.
5209 * 'force-left': Alias for 'forwards' in LTR and 'backwards' in RTL
5210 * 'force-right': Alias for 'backwards' in RTL and 'forwards' in LTR
5211 * @cfg {boolean} [autoFlip=true] Whether to automatically switch the popup's position between
5212 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5213 * desired direction to display the popup without clipping
5214 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
5215 * See the [OOUI docs on MediaWiki][3] for an example.
5216 * [3]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#containerExample
5217 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
5218 * @cfg {jQuery} [$content] Content to append to the popup's body
5219 * @cfg {jQuery} [$footer] Content to append to the popup's footer
5220 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
5221 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
5222 * This config option is only relevant if #autoClose is set to `true`. See the [OOUI documentation on MediaWiki][2]
5224 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#autocloseExample
5225 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
5227 * @cfg {boolean} [padded=false] Add padding to the popup's body
5229 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
5230 // Configuration initialization
5231 config
= config
|| {};
5233 // Parent constructor
5234 OO
.ui
.PopupWidget
.parent
.call( this, config
);
5236 // Properties (must be set before ClippableElement constructor call)
5237 this.$body
= $( '<div>' );
5238 this.$popup
= $( '<div>' );
5240 // Mixin constructors
5241 OO
.ui
.mixin
.LabelElement
.call( this, config
);
5242 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, {
5243 $clippable
: this.$body
,
5244 $clippableContainer
: this.$popup
5246 OO
.ui
.mixin
.FloatableElement
.call( this, config
);
5249 this.$anchor
= $( '<div>' );
5250 // If undefined, will be computed lazily in computePosition()
5251 this.$container
= config
.$container
;
5252 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
5253 this.autoClose
= !!config
.autoClose
;
5254 this.transitionTimeout
= null;
5255 this.anchored
= false;
5256 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
5257 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
5260 this.setSize( config
.width
, config
.height
);
5261 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
5262 this.setAlignment( config
.align
|| 'center' );
5263 this.setPosition( config
.position
|| 'below' );
5264 this.setAutoFlip( config
.autoFlip
=== undefined || config
.autoFlip
);
5265 this.setAutoCloseIgnore( config
.$autoCloseIgnore
);
5266 this.$body
.addClass( 'oo-ui-popupWidget-body' );
5267 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
5269 .addClass( 'oo-ui-popupWidget-popup' )
5270 .append( this.$body
);
5272 .addClass( 'oo-ui-popupWidget' )
5273 .append( this.$popup
, this.$anchor
);
5274 // Move content, which was added to #$element by OO.ui.Widget, to the body
5275 // FIXME This is gross, we should use '$body' or something for the config
5276 if ( config
.$content
instanceof $ ) {
5277 this.$body
.append( config
.$content
);
5280 if ( config
.padded
) {
5281 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
5284 if ( config
.head
) {
5285 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
5286 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
5287 this.$head
= $( '<div>' )
5288 .addClass( 'oo-ui-popupWidget-head' )
5289 .append( this.$label
, this.closeButton
.$element
);
5290 this.$popup
.prepend( this.$head
);
5293 if ( config
.$footer
) {
5294 this.$footer
= $( '<div>' )
5295 .addClass( 'oo-ui-popupWidget-footer' )
5296 .append( config
.$footer
);
5297 this.$popup
.append( this.$footer
);
5300 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
5301 // that reference properties not initialized at that time of parent class construction
5302 // TODO: Find a better way to handle post-constructor setup
5303 this.visible
= false;
5304 this.$element
.addClass( 'oo-ui-element-hidden' );
5309 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
5310 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
5311 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
5312 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.FloatableElement
);
5319 * The popup is ready: it is visible and has been positioned and clipped.
5325 * Handles document mouse down events.
5328 * @param {MouseEvent} e Mouse down event
5330 OO
.ui
.PopupWidget
.prototype.onDocumentMouseDown = function ( e
) {
5333 !OO
.ui
.contains( this.$element
.add( this.$autoCloseIgnore
).get(), e
.target
, true )
5335 this.toggle( false );
5339 // Deprecated alias since 0.28.3
5340 OO
.ui
.PopupWidget
.prototype.onMouseDown = function () {
5341 OO
.ui
.warnDeprecation( 'onMouseDown is deprecated, use onDocumentMouseDown instead' );
5342 this.onDocumentMouseDown
.apply( this, arguments
);
5346 * Bind document mouse down listener.
5350 OO
.ui
.PopupWidget
.prototype.bindDocumentMouseDownListener = function () {
5351 // Capture clicks outside popup
5352 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
5353 // We add 'click' event because iOS safari needs to respond to this event.
5354 // We can't use 'touchstart' (as is usually the equivalent to 'mousedown') because
5355 // then it will trigger when scrolling. While iOS Safari has some reported behavior
5356 // of occasionally not emitting 'click' properly, that event seems to be the standard
5357 // that it should be emitting, so we add it to this and will operate the event handler
5358 // on whichever of these events was triggered first
5359 this.getElementDocument().addEventListener( 'click', this.onDocumentMouseDownHandler
, true );
5362 // Deprecated alias since 0.28.3
5363 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
5364 OO
.ui
.warnDeprecation( 'bindMouseDownListener is deprecated, use bindDocumentMouseDownListener instead' );
5365 this.bindDocumentMouseDownListener
.apply( this, arguments
);
5369 * Handles close button click events.
5373 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
5374 if ( this.isVisible() ) {
5375 this.toggle( false );
5380 * Unbind document mouse down listener.
5384 OO
.ui
.PopupWidget
.prototype.unbindDocumentMouseDownListener = function () {
5385 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
5386 this.getElementDocument().removeEventListener( 'click', this.onDocumentMouseDownHandler
, true );
5389 // Deprecated alias since 0.28.3
5390 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
5391 OO
.ui
.warnDeprecation( 'unbindMouseDownListener is deprecated, use unbindDocumentMouseDownListener instead' );
5392 this.unbindDocumentMouseDownListener
.apply( this, arguments
);
5396 * Handles document key down events.
5399 * @param {KeyboardEvent} e Key down event
5401 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
5403 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
5406 this.toggle( false );
5408 e
.stopPropagation();
5413 * Bind document key down listener.
5417 OO
.ui
.PopupWidget
.prototype.bindDocumentKeyDownListener = function () {
5418 this.getElementDocument().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
5421 // Deprecated alias since 0.28.3
5422 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
5423 OO
.ui
.warnDeprecation( 'bindKeyDownListener is deprecated, use bindDocumentKeyDownListener instead' );
5424 this.bindDocumentKeyDownListener
.apply( this, arguments
);
5428 * Unbind document key down listener.
5432 OO
.ui
.PopupWidget
.prototype.unbindDocumentKeyDownListener = function () {
5433 this.getElementDocument().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
5436 // Deprecated alias since 0.28.3
5437 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
5438 OO
.ui
.warnDeprecation( 'unbindKeyDownListener is deprecated, use unbindDocumentKeyDownListener instead' );
5439 this.unbindDocumentKeyDownListener
.apply( this, arguments
);
5443 * Show, hide, or toggle the visibility of the anchor.
5445 * @param {boolean} [show] Show anchor, omit to toggle
5447 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
5448 show
= show
=== undefined ? !this.anchored
: !!show
;
5450 if ( this.anchored
!== show
) {
5452 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
5453 this.$element
.addClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5455 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
5456 this.$element
.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5458 this.anchored
= show
;
5463 * Change which edge the anchor appears on.
5465 * @param {string} edge 'top', 'bottom', 'start' or 'end'
5467 OO
.ui
.PopupWidget
.prototype.setAnchorEdge = function ( edge
) {
5468 if ( [ 'top', 'bottom', 'start', 'end' ].indexOf( edge
) === -1 ) {
5469 throw new Error( 'Invalid value for edge: ' + edge
);
5471 if ( this.anchorEdge
!== null ) {
5472 this.$element
.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5474 this.anchorEdge
= edge
;
5475 if ( this.anchored
) {
5476 this.$element
.addClass( 'oo-ui-popupWidget-anchored-' + edge
);
5481 * Check if the anchor is visible.
5483 * @return {boolean} Anchor is visible
5485 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
5486 return this.anchored
;
5490 * Toggle visibility of the popup. The popup is initially hidden and must be shown by calling
5491 * `.toggle( true )` after its #$element is attached to the DOM.
5493 * Do not show the popup while it is not attached to the DOM. The calculations required to display
5494 * it in the right place and with the right dimensions only work correctly while it is attached.
5495 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
5496 * strictly enforced, so currently it only generates a warning in the browser console.
5501 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
5502 var change
, normalHeight
, oppositeHeight
, normalWidth
, oppositeWidth
;
5503 show
= show
=== undefined ? !this.isVisible() : !!show
;
5505 change
= show
!== this.isVisible();
5507 if ( show
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
5508 OO
.ui
.warnDeprecation( 'PopupWidget#toggle: Before calling this method, the popup must be attached to the DOM.' );
5509 this.warnedUnattached
= true;
5511 if ( show
&& !this.$floatableContainer
&& this.isElementAttached() ) {
5512 // Fall back to the parent node if the floatableContainer is not set
5513 this.setFloatableContainer( this.$element
.parent() );
5516 if ( change
&& show
&& this.autoFlip
) {
5517 // Reset auto-flipping before showing the popup again. It's possible we no longer need to flip
5518 // (e.g. if the user scrolled).
5519 this.isAutoFlipped
= false;
5523 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
5526 this.togglePositioning( show
&& !!this.$floatableContainer
);
5529 if ( this.autoClose
) {
5530 this.bindDocumentMouseDownListener();
5531 this.bindDocumentKeyDownListener();
5533 this.updateDimensions();
5534 this.toggleClipping( true );
5536 if ( this.autoFlip
) {
5537 if ( this.popupPosition
=== 'above' || this.popupPosition
=== 'below' ) {
5538 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5539 // If opening the popup in the normal direction causes it to be clipped, open
5540 // in the opposite one instead
5541 normalHeight
= this.$element
.height();
5542 this.isAutoFlipped
= !this.isAutoFlipped
;
5544 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5545 // If that also causes it to be clipped, open in whichever direction
5546 // we have more space
5547 oppositeHeight
= this.$element
.height();
5548 if ( oppositeHeight
< normalHeight
) {
5549 this.isAutoFlipped
= !this.isAutoFlipped
;
5555 if ( this.popupPosition
=== 'before' || this.popupPosition
=== 'after' ) {
5556 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5557 // If opening the popup in the normal direction causes it to be clipped, open
5558 // in the opposite one instead
5559 normalWidth
= this.$element
.width();
5560 this.isAutoFlipped
= !this.isAutoFlipped
;
5561 // Due to T180173 horizontally clipped PopupWidgets have messed up dimensions,
5562 // which causes positioning to be off. Toggle clipping back and fort to work around.
5563 this.toggleClipping( false );
5565 this.toggleClipping( true );
5566 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5567 // If that also causes it to be clipped, open in whichever direction
5568 // we have more space
5569 oppositeWidth
= this.$element
.width();
5570 if ( oppositeWidth
< normalWidth
) {
5571 this.isAutoFlipped
= !this.isAutoFlipped
;
5572 // Due to T180173 horizontally clipped PopupWidgets have messed up dimensions,
5573 // which causes positioning to be off. Toggle clipping back and fort to work around.
5574 this.toggleClipping( false );
5576 this.toggleClipping( true );
5583 this.emit( 'ready' );
5585 this.toggleClipping( false );
5586 if ( this.autoClose
) {
5587 this.unbindDocumentMouseDownListener();
5588 this.unbindDocumentKeyDownListener();
5597 * Set the size of the popup.
5599 * Changing the size may also change the popup's position depending on the alignment.
5601 * @param {number|null} [width=320] Width in pixels. Pass `null` to use automatic width.
5602 * @param {number|null} [height=null] Height in pixels. Pass `null` to use automatic height.
5603 * @param {boolean} [transition=false] Use a smooth transition
5606 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
5607 this.width
= width
!== undefined ? width
: 320;
5608 this.height
= height
!== undefined ? height
: null;
5609 if ( this.isVisible() ) {
5610 this.updateDimensions( transition
);
5615 * Update the size and position.
5617 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
5618 * be called automatically.
5620 * @param {boolean} [transition=false] Use a smooth transition
5623 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
5626 // Prevent transition from being interrupted
5627 clearTimeout( this.transitionTimeout
);
5629 // Enable transition
5630 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
5636 // Prevent transitioning after transition is complete
5637 this.transitionTimeout
= setTimeout( function () {
5638 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
5641 // Prevent transitioning immediately
5642 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
5649 OO
.ui
.PopupWidget
.prototype.computePosition = function () {
5650 var direction
, align
, vertical
, start
, end
, near
, far
, sizeProp
, popupSize
, anchorSize
, anchorPos
,
5651 anchorOffset
, anchorMargin
, parentPosition
, positionProp
, positionAdjustment
, floatablePos
,
5652 offsetParentPos
, containerPos
, popupPosition
, viewportSpacing
,
5654 anchorCss
= { left
: '', right
: '', top
: '', bottom
: '' },
5655 popupPositionOppositeMap
= {
5663 'force-left': 'backwards',
5664 'force-right': 'forwards'
5667 'force-left': 'forwards',
5668 'force-right': 'backwards'
5680 backwards
: this.anchored
? 'before' : 'end'
5688 if ( !this.$container
) {
5689 // Lazy-initialize $container if not specified in constructor
5690 this.$container
= $( this.getClosestScrollableElementContainer() );
5692 direction
= this.$container
.css( 'direction' );
5694 // Set height and width before we do anything else, since it might cause our measurements
5695 // to change (e.g. due to scrollbars appearing or disappearing), and it also affects centering
5697 width
: this.width
!== null ? this.width
: 'auto',
5698 height
: this.height
!== null ? this.height
: 'auto'
5701 align
= alignMap
[ direction
][ this.align
] || this.align
;
5702 popupPosition
= this.popupPosition
;
5703 if ( this.isAutoFlipped
) {
5704 popupPosition
= popupPositionOppositeMap
[ popupPosition
];
5707 // If the popup is positioned before or after, then the anchor positioning is vertical, otherwise horizontal
5708 vertical
= popupPosition
=== 'before' || popupPosition
=== 'after';
5709 start
= vertical
? 'top' : ( direction
=== 'rtl' ? 'right' : 'left' );
5710 end
= vertical
? 'bottom' : ( direction
=== 'rtl' ? 'left' : 'right' );
5711 near
= vertical
? 'top' : 'left';
5712 far
= vertical
? 'bottom' : 'right';
5713 sizeProp
= vertical
? 'Height' : 'Width';
5714 popupSize
= vertical
? ( this.height
|| this.$popup
.height() ) : ( this.width
|| this.$popup
.width() );
5716 this.setAnchorEdge( anchorEdgeMap
[ popupPosition
] );
5717 this.horizontalPosition
= vertical
? popupPosition
: hPosMap
[ align
];
5718 this.verticalPosition
= vertical
? vPosMap
[ align
] : popupPosition
;
5721 parentPosition
= OO
.ui
.mixin
.FloatableElement
.prototype.computePosition
.call( this );
5722 // Find out which property FloatableElement used for positioning, and adjust that value
5723 positionProp
= vertical
?
5724 ( parentPosition
.top
!== '' ? 'top' : 'bottom' ) :
5725 ( parentPosition
.left
!== '' ? 'left' : 'right' );
5727 // Figure out where the near and far edges of the popup and $floatableContainer are
5728 floatablePos
= this.$floatableContainer
.offset();
5729 floatablePos
[ far
] = floatablePos
[ near
] + this.$floatableContainer
[ 'outer' + sizeProp
]();
5730 // Measure where the offsetParent is and compute our position based on that and parentPosition
5731 offsetParentPos
= this.$element
.offsetParent()[ 0 ] === document
.documentElement
?
5732 { top
: 0, left
: 0 } :
5733 this.$element
.offsetParent().offset();
5735 if ( positionProp
=== near
) {
5736 popupPos
[ near
] = offsetParentPos
[ near
] + parentPosition
[ near
];
5737 popupPos
[ far
] = popupPos
[ near
] + popupSize
;
5739 popupPos
[ far
] = offsetParentPos
[ near
] +
5740 this.$element
.offsetParent()[ 'inner' + sizeProp
]() - parentPosition
[ far
];
5741 popupPos
[ near
] = popupPos
[ far
] - popupSize
;
5744 if ( this.anchored
) {
5745 // Position the anchor (which is positioned relative to the popup) to point to $floatableContainer
5746 anchorPos
= ( floatablePos
[ start
] + floatablePos
[ end
] ) / 2;
5747 anchorOffset
= ( start
=== far
? -1 : 1 ) * ( anchorPos
- popupPos
[ start
] );
5749 // If the anchor is less than 2*anchorSize from either edge, move the popup to make more space
5750 // this.$anchor.width()/height() returns 0 because of the CSS trickery we use, so use scrollWidth/Height
5751 anchorSize
= this.$anchor
[ 0 ][ 'scroll' + sizeProp
];
5752 anchorMargin
= parseFloat( this.$anchor
.css( 'margin-' + start
) );
5753 if ( anchorOffset
+ anchorMargin
< 2 * anchorSize
) {
5754 // Not enough space for the anchor on the start side; pull the popup startwards
5755 positionAdjustment
= ( positionProp
=== start
? -1 : 1 ) *
5756 ( 2 * anchorSize
- ( anchorOffset
+ anchorMargin
) );
5757 } else if ( anchorOffset
+ anchorMargin
> popupSize
- 2 * anchorSize
) {
5758 // Not enough space for the anchor on the end side; pull the popup endwards
5759 positionAdjustment
= ( positionProp
=== end
? -1 : 1 ) *
5760 ( anchorOffset
+ anchorMargin
- ( popupSize
- 2 * anchorSize
) );
5762 positionAdjustment
= 0;
5765 positionAdjustment
= 0;
5768 // Check if the popup will go beyond the edge of this.$container
5769 containerPos
= this.$container
[ 0 ] === document
.documentElement
?
5770 { top
: 0, left
: 0 } :
5771 this.$container
.offset();
5772 containerPos
[ far
] = containerPos
[ near
] + this.$container
[ 'inner' + sizeProp
]();
5773 if ( this.$container
[ 0 ] === document
.documentElement
) {
5774 viewportSpacing
= OO
.ui
.getViewportSpacing();
5775 containerPos
[ near
] += viewportSpacing
[ near
];
5776 containerPos
[ far
] -= viewportSpacing
[ far
];
5778 // Take into account how much the popup will move because of the adjustments we're going to make
5779 popupPos
[ near
] += ( positionProp
=== near
? 1 : -1 ) * positionAdjustment
;
5780 popupPos
[ far
] += ( positionProp
=== near
? 1 : -1 ) * positionAdjustment
;
5781 if ( containerPos
[ near
] + this.containerPadding
> popupPos
[ near
] ) {
5782 // Popup goes beyond the near (left/top) edge, move it to the right/bottom
5783 positionAdjustment
+= ( positionProp
=== near
? 1 : -1 ) *
5784 ( containerPos
[ near
] + this.containerPadding
- popupPos
[ near
] );
5785 } else if ( containerPos
[ far
] - this.containerPadding
< popupPos
[ far
] ) {
5786 // Popup goes beyond the far (right/bottom) edge, move it to the left/top
5787 positionAdjustment
+= ( positionProp
=== far
? 1 : -1 ) *
5788 ( popupPos
[ far
] - ( containerPos
[ far
] - this.containerPadding
) );
5791 if ( this.anchored
) {
5792 // Adjust anchorOffset for positionAdjustment
5793 anchorOffset
+= ( positionProp
=== start
? -1 : 1 ) * positionAdjustment
;
5795 // Position the anchor
5796 anchorCss
[ start
] = anchorOffset
;
5797 this.$anchor
.css( anchorCss
);
5800 // Move the popup if needed
5801 parentPosition
[ positionProp
] += positionAdjustment
;
5803 return parentPosition
;
5807 * Set popup alignment
5809 * @param {string} [align=center] Alignment of the popup, `center`, `force-left`, `force-right`,
5810 * `backwards` or `forwards`.
5812 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
5813 // Validate alignment
5814 if ( [ 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
5817 this.align
= 'center';
5823 * Get popup alignment
5825 * @return {string} Alignment of the popup, `center`, `force-left`, `force-right`,
5826 * `backwards` or `forwards`.
5828 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
5833 * Change the positioning of the popup.
5835 * @param {string} position 'above', 'below', 'before' or 'after'
5837 OO
.ui
.PopupWidget
.prototype.setPosition = function ( position
) {
5838 if ( [ 'above', 'below', 'before', 'after' ].indexOf( position
) === -1 ) {
5841 this.popupPosition
= position
;
5846 * Get popup positioning.
5848 * @return {string} 'above', 'below', 'before' or 'after'
5850 OO
.ui
.PopupWidget
.prototype.getPosition = function () {
5851 return this.popupPosition
;
5855 * Set popup auto-flipping.
5857 * @param {boolean} autoFlip Whether to automatically switch the popup's position between
5858 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5859 * desired direction to display the popup without clipping
5861 OO
.ui
.PopupWidget
.prototype.setAutoFlip = function ( autoFlip
) {
5862 autoFlip
= !!autoFlip
;
5864 if ( this.autoFlip
!== autoFlip
) {
5865 this.autoFlip
= autoFlip
;
5870 * Set which elements will not close the popup when clicked.
5872 * For auto-closing popups, clicks on these elements will not cause the popup to auto-close.
5874 * @param {jQuery} $autoCloseIgnore Elements to ignore for auto-closing
5876 OO
.ui
.PopupWidget
.prototype.setAutoCloseIgnore = function ( $autoCloseIgnore
) {
5877 this.$autoCloseIgnore
= $autoCloseIgnore
;
5881 * Get an ID of the body element, this can be used as the
5882 * `aria-describedby` attribute for an input field.
5884 * @return {string} The ID of the body element
5886 OO
.ui
.PopupWidget
.prototype.getBodyId = function () {
5887 var id
= this.$body
.attr( 'id' );
5888 if ( id
=== undefined ) {
5889 id
= OO
.ui
.generateElementId();
5890 this.$body
.attr( 'id', id
);
5896 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5897 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5898 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5899 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5905 * @param {Object} [config] Configuration options
5906 * @cfg {Object} [popup] Configuration to pass to popup
5907 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5909 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
5910 // Configuration initialization
5911 config
= config
|| {};
5914 this.popup
= new OO
.ui
.PopupWidget( $.extend(
5917 $floatableContainer
: this.$element
5921 $autoCloseIgnore
: this.$element
.add( config
.popup
&& config
.popup
.$autoCloseIgnore
)
5931 * @return {OO.ui.PopupWidget} Popup widget
5933 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
5938 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
5939 * which is used to display additional information or options.
5942 * // Example of a popup button.
5943 * var popupButton = new OO.ui.PopupButtonWidget( {
5944 * label: 'Popup button with options',
5947 * $content: $( '<p>Additional options here.</p>' ),
5949 * align: 'force-left'
5952 * // Append the button to the DOM.
5953 * $( 'body' ).append( popupButton.$element );
5956 * @extends OO.ui.ButtonWidget
5957 * @mixins OO.ui.mixin.PopupElement
5960 * @param {Object} [config] Configuration options
5961 * @cfg {jQuery} [$overlay] Render the popup into a separate layer. This configuration is useful in cases where
5962 * the expanded popup is larger than its containing `<div>`. The specified overlay layer is usually on top of the
5963 * containing `<div>` and has a larger area. By default, the popup uses relative positioning.
5964 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
5966 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
5967 // Configuration initialization
5968 config
= config
|| {};
5970 // Parent constructor
5971 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
5973 // Mixin constructors
5974 OO
.ui
.mixin
.PopupElement
.call( this, config
);
5977 this.$overlay
= ( config
.$overlay
=== true ? OO
.ui
.getDefaultOverlay() : config
.$overlay
) || this.$element
;
5980 this.connect( this, { click
: 'onAction' } );
5984 .addClass( 'oo-ui-popupButtonWidget' );
5986 .addClass( 'oo-ui-popupButtonWidget-popup' )
5987 .toggleClass( 'oo-ui-popupButtonWidget-framed-popup', this.isFramed() )
5988 .toggleClass( 'oo-ui-popupButtonWidget-frameless-popup', !this.isFramed() );
5989 this.$overlay
.append( this.popup
.$element
);
5994 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
5995 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
6000 * Handle the button action being triggered.
6004 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
6005 this.popup
.toggle();
6009 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
6011 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
6016 * @mixins OO.ui.mixin.GroupElement
6019 * @param {Object} [config] Configuration options
6021 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
6022 // Mixin constructors
6023 OO
.ui
.mixin
.GroupElement
.call( this, config
);
6028 OO
.mixinClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
6033 * Set the disabled state of the widget.
6035 * This will also update the disabled state of child widgets.
6037 * @param {boolean} disabled Disable widget
6039 * @return {OO.ui.Widget} The widget, for chaining
6041 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
6045 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
6046 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
6048 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
6050 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6051 this.items
[ i
].updateDisabled();
6059 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
6061 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
6062 * allows bidirectional communication.
6064 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
6072 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
6079 * Check if widget is disabled.
6081 * Checks parent if present, making disabled state inheritable.
6083 * @return {boolean} Widget is disabled
6085 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
6086 return this.disabled
||
6087 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
6091 * Set group element is in.
6093 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
6095 * @return {OO.ui.Widget} The widget, for chaining
6097 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
6099 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
6100 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
6102 // Initialize item disabled states
6103 this.updateDisabled();
6109 * OptionWidgets are special elements that can be selected and configured with data. The
6110 * data is often unique for each option, but it does not have to be. OptionWidgets are used
6111 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
6112 * and examples, please see the [OOUI documentation on MediaWiki][1].
6114 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6117 * @extends OO.ui.Widget
6118 * @mixins OO.ui.mixin.ItemWidget
6119 * @mixins OO.ui.mixin.LabelElement
6120 * @mixins OO.ui.mixin.FlaggedElement
6121 * @mixins OO.ui.mixin.AccessKeyedElement
6124 * @param {Object} [config] Configuration options
6126 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
6127 // Configuration initialization
6128 config
= config
|| {};
6130 // Parent constructor
6131 OO
.ui
.OptionWidget
.parent
.call( this, config
);
6133 // Mixin constructors
6134 OO
.ui
.mixin
.ItemWidget
.call( this );
6135 OO
.ui
.mixin
.LabelElement
.call( this, config
);
6136 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
6137 OO
.ui
.mixin
.AccessKeyedElement
.call( this, config
);
6140 this.selected
= false;
6141 this.highlighted
= false;
6142 this.pressed
= false;
6146 .data( 'oo-ui-optionWidget', this )
6147 // Allow programmatic focussing (and by accesskey), but not tabbing
6148 .attr( 'tabindex', '-1' )
6149 .attr( 'role', 'option' )
6150 .attr( 'aria-selected', 'false' )
6151 .addClass( 'oo-ui-optionWidget' )
6152 .append( this.$label
);
6157 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
6158 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
6159 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
6160 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
6161 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
6163 /* Static Properties */
6166 * Whether this option can be selected. See #setSelected.
6170 * @property {boolean}
6172 OO
.ui
.OptionWidget
.static.selectable
= true;
6175 * Whether this option can be highlighted. See #setHighlighted.
6179 * @property {boolean}
6181 OO
.ui
.OptionWidget
.static.highlightable
= true;
6184 * Whether this option can be pressed. See #setPressed.
6188 * @property {boolean}
6190 OO
.ui
.OptionWidget
.static.pressable
= true;
6193 * Whether this option will be scrolled into view when it is selected.
6197 * @property {boolean}
6199 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
6204 * Check if the option can be selected.
6206 * @return {boolean} Item is selectable
6208 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
6209 return this.constructor.static.selectable
&& !this.disabled
&& this.isVisible();
6213 * Check if the option can be highlighted. A highlight indicates that the option
6214 * may be selected when a user presses enter or clicks. Disabled items cannot
6217 * @return {boolean} Item is highlightable
6219 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
6220 return this.constructor.static.highlightable
&& !this.disabled
&& this.isVisible();
6224 * Check if the option can be pressed. The pressed state occurs when a user mouses
6225 * down on an item, but has not yet let go of the mouse.
6227 * @return {boolean} Item is pressable
6229 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
6230 return this.constructor.static.pressable
&& !this.disabled
&& this.isVisible();
6234 * Check if the option is selected.
6236 * @return {boolean} Item is selected
6238 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
6239 return this.selected
;
6243 * Check if the option is highlighted. A highlight indicates that the
6244 * item may be selected when a user presses enter or clicks.
6246 * @return {boolean} Item is highlighted
6248 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
6249 return this.highlighted
;
6253 * Check if the option is pressed. The pressed state occurs when a user mouses
6254 * down on an item, but has not yet let go of the mouse. The item may appear
6255 * selected, but it will not be selected until the user releases the mouse.
6257 * @return {boolean} Item is pressed
6259 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
6260 return this.pressed
;
6264 * Set the option’s selected state. In general, all modifications to the selection
6265 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
6266 * method instead of this method.
6268 * @param {boolean} [state=false] Select option
6270 * @return {OO.ui.Widget} The widget, for chaining
6272 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
6273 if ( this.constructor.static.selectable
) {
6274 this.selected
= !!state
;
6276 .toggleClass( 'oo-ui-optionWidget-selected', state
)
6277 .attr( 'aria-selected', state
.toString() );
6278 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
6279 this.scrollElementIntoView();
6281 this.updateThemeClasses();
6287 * Set the option’s highlighted state. In general, all programmatic
6288 * modifications to the highlight should be handled by the
6289 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
6290 * method instead of this method.
6292 * @param {boolean} [state=false] Highlight option
6294 * @return {OO.ui.Widget} The widget, for chaining
6296 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
6297 if ( this.constructor.static.highlightable
) {
6298 this.highlighted
= !!state
;
6299 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
6300 this.updateThemeClasses();
6306 * Set the option’s pressed state. In general, all
6307 * programmatic modifications to the pressed state should be handled by the
6308 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
6309 * method instead of this method.
6311 * @param {boolean} [state=false] Press option
6313 * @return {OO.ui.Widget} The widget, for chaining
6315 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
6316 if ( this.constructor.static.pressable
) {
6317 this.pressed
= !!state
;
6318 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
6319 this.updateThemeClasses();
6325 * Get text to match search strings against.
6327 * The default implementation returns the label text, but subclasses
6328 * can override this to provide more complex behavior.
6330 * @return {string|boolean} String to match search string against
6332 OO
.ui
.OptionWidget
.prototype.getMatchText = function () {
6333 var label
= this.getLabel();
6334 return typeof label
=== 'string' ? label
: this.$label
.text();
6338 * A SelectWidget is of a generic selection of options. The OOUI library contains several types of
6339 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
6340 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
6343 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
6344 * information, please see the [OOUI documentation on MediaWiki][1].
6347 * // Example of a select widget with three options
6348 * var select = new OO.ui.SelectWidget( {
6350 * new OO.ui.OptionWidget( {
6352 * label: 'Option One',
6354 * new OO.ui.OptionWidget( {
6356 * label: 'Option Two',
6358 * new OO.ui.OptionWidget( {
6360 * label: 'Option Three',
6364 * $( 'body' ).append( select.$element );
6366 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6370 * @extends OO.ui.Widget
6371 * @mixins OO.ui.mixin.GroupWidget
6374 * @param {Object} [config] Configuration options
6375 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
6376 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
6377 * the [OOUI documentation on MediaWiki] [2] for examples.
6378 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6380 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
6381 // Configuration initialization
6382 config
= config
|| {};
6384 // Parent constructor
6385 OO
.ui
.SelectWidget
.parent
.call( this, config
);
6387 // Mixin constructors
6388 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
6391 this.pressed
= false;
6392 this.selecting
= null;
6393 this.onDocumentMouseUpHandler
= this.onDocumentMouseUp
.bind( this );
6394 this.onDocumentMouseMoveHandler
= this.onDocumentMouseMove
.bind( this );
6395 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
6396 this.onDocumentKeyPressHandler
= this.onDocumentKeyPress
.bind( this );
6397 this.keyPressBuffer
= '';
6398 this.keyPressBufferTimer
= null;
6399 this.blockMouseOverEvents
= 0;
6402 this.connect( this, {
6406 focusin
: this.onFocus
.bind( this ),
6407 mousedown
: this.onMouseDown
.bind( this ),
6408 mouseover
: this.onMouseOver
.bind( this ),
6409 mouseleave
: this.onMouseLeave
.bind( this )
6414 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
6415 .attr( 'role', 'listbox' );
6416 this.setFocusOwner( this.$element
);
6417 if ( Array
.isArray( config
.items
) ) {
6418 this.addItems( config
.items
);
6424 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
6425 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
6432 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
6434 * @param {OO.ui.OptionWidget|null} item Highlighted item
6440 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
6441 * pressed state of an option.
6443 * @param {OO.ui.OptionWidget|null} item Pressed item
6449 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
6451 * @param {OO.ui.OptionWidget|null} item Selected item
6456 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
6457 * @param {OO.ui.OptionWidget} item Chosen item
6463 * An `add` event is emitted when options are added to the select with the #addItems method.
6465 * @param {OO.ui.OptionWidget[]} items Added items
6466 * @param {number} index Index of insertion point
6472 * A `remove` event is emitted when options are removed from the select with the #clearItems
6473 * or #removeItems methods.
6475 * @param {OO.ui.OptionWidget[]} items Removed items
6481 * Handle focus events
6484 * @param {jQuery.Event} event
6486 OO
.ui
.SelectWidget
.prototype.onFocus = function ( event
) {
6488 if ( event
.target
=== this.$element
[ 0 ] ) {
6489 // This widget was focussed, e.g. by the user tabbing to it.
6490 // The styles for focus state depend on one of the items being selected.
6491 if ( !this.findSelectedItem() ) {
6492 item
= this.findFirstSelectableItem();
6495 if ( event
.target
.tabIndex
=== -1 ) {
6496 // One of the options got focussed (and the event bubbled up here).
6497 // They can't be tabbed to, but they can be activated using accesskeys.
6498 // OptionWidgets and focusable UI elements inside them have tabindex="-1" set.
6499 item
= this.findTargetItem( event
);
6501 // There is something actually user-focusable in one of the labels of the options, and the
6502 // user focussed it (e.g. by tabbing to it). Do nothing (especially, don't change the focus).
6508 if ( item
.constructor.static.highlightable
) {
6509 this.highlightItem( item
);
6511 this.selectItem( item
);
6515 if ( event
.target
!== this.$element
[ 0 ] ) {
6516 this.$focusOwner
.focus();
6521 * Handle mouse down events.
6524 * @param {jQuery.Event} e Mouse down event
6525 * @return {undefined/boolean} False to prevent default if event is handled
6527 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
6530 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
6531 this.togglePressed( true );
6532 item
= this.findTargetItem( e
);
6533 if ( item
&& item
.isSelectable() ) {
6534 this.pressItem( item
);
6535 this.selecting
= item
;
6536 this.getElementDocument().addEventListener( 'mouseup', this.onDocumentMouseUpHandler
, true );
6537 this.getElementDocument().addEventListener( 'mousemove', this.onDocumentMouseMoveHandler
, true );
6544 * Handle document mouse up events.
6547 * @param {MouseEvent} e Mouse up event
6548 * @return {undefined/boolean} False to prevent default if event is handled
6550 OO
.ui
.SelectWidget
.prototype.onDocumentMouseUp = function ( e
) {
6553 this.togglePressed( false );
6554 if ( !this.selecting
) {
6555 item
= this.findTargetItem( e
);
6556 if ( item
&& item
.isSelectable() ) {
6557 this.selecting
= item
;
6560 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
&& this.selecting
) {
6561 this.pressItem( null );
6562 this.chooseItem( this.selecting
);
6563 this.selecting
= null;
6566 this.getElementDocument().removeEventListener( 'mouseup', this.onDocumentMouseUpHandler
, true );
6567 this.getElementDocument().removeEventListener( 'mousemove', this.onDocumentMouseMoveHandler
, true );
6572 // Deprecated alias since 0.28.3
6573 OO
.ui
.SelectWidget
.prototype.onMouseUp = function () {
6574 OO
.ui
.warnDeprecation( 'onMouseUp is deprecated, use onDocumentMouseUp instead' );
6575 this.onDocumentMouseUp
.apply( this, arguments
);
6579 * Handle document mouse move events.
6582 * @param {MouseEvent} e Mouse move event
6584 OO
.ui
.SelectWidget
.prototype.onDocumentMouseMove = function ( e
) {
6587 if ( !this.isDisabled() && this.pressed
) {
6588 item
= this.findTargetItem( e
);
6589 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
6590 this.pressItem( item
);
6591 this.selecting
= item
;
6596 // Deprecated alias since 0.28.3
6597 OO
.ui
.SelectWidget
.prototype.onMouseMove = function () {
6598 OO
.ui
.warnDeprecation( 'onMouseMove is deprecated, use onDocumentMouseMove instead' );
6599 this.onDocumentMouseMove
.apply( this, arguments
);
6603 * Handle mouse over events.
6606 * @param {jQuery.Event} e Mouse over event
6607 * @return {undefined/boolean} False to prevent default if event is handled
6609 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
6611 if ( this.blockMouseOverEvents
) {
6614 if ( !this.isDisabled() ) {
6615 item
= this.findTargetItem( e
);
6616 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
6622 * Handle mouse leave events.
6625 * @param {jQuery.Event} e Mouse over event
6626 * @return {undefined/boolean} False to prevent default if event is handled
6628 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
6629 if ( !this.isDisabled() ) {
6630 this.highlightItem( null );
6636 * Handle document key down events.
6639 * @param {KeyboardEvent} e Key down event
6641 OO
.ui
.SelectWidget
.prototype.onDocumentKeyDown = function ( e
) {
6644 currentItem
= this.findHighlightedItem() || this.findSelectedItem();
6646 if ( !this.isDisabled() && this.isVisible() ) {
6647 switch ( e
.keyCode
) {
6648 case OO
.ui
.Keys
.ENTER
:
6649 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
6650 // Was only highlighted, now let's select it. No-op if already selected.
6651 this.chooseItem( currentItem
);
6656 case OO
.ui
.Keys
.LEFT
:
6657 this.clearKeyPressBuffer();
6658 nextItem
= this.findRelativeSelectableItem( currentItem
, -1 );
6661 case OO
.ui
.Keys
.DOWN
:
6662 case OO
.ui
.Keys
.RIGHT
:
6663 this.clearKeyPressBuffer();
6664 nextItem
= this.findRelativeSelectableItem( currentItem
, 1 );
6667 case OO
.ui
.Keys
.ESCAPE
:
6668 case OO
.ui
.Keys
.TAB
:
6669 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
6670 currentItem
.setHighlighted( false );
6672 this.unbindDocumentKeyDownListener();
6673 this.unbindDocumentKeyPressListener();
6674 // Don't prevent tabbing away / defocusing
6680 if ( nextItem
.constructor.static.highlightable
) {
6681 this.highlightItem( nextItem
);
6683 this.chooseItem( nextItem
);
6685 this.scrollItemIntoView( nextItem
);
6690 e
.stopPropagation();
6695 // Deprecated alias since 0.28.3
6696 OO
.ui
.SelectWidget
.prototype.onKeyDown = function () {
6697 OO
.ui
.warnDeprecation( 'onKeyDown is deprecated, use onDocumentKeyDown instead' );
6698 this.onDocumentKeyDown
.apply( this, arguments
);
6702 * Bind document key down listener.
6706 OO
.ui
.SelectWidget
.prototype.bindDocumentKeyDownListener = function () {
6707 this.getElementDocument().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
6710 // Deprecated alias since 0.28.3
6711 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
6712 OO
.ui
.warnDeprecation( 'bindKeyDownListener is deprecated, use bindDocumentKeyDownListener instead' );
6713 this.bindDocumentKeyDownListener
.apply( this, arguments
);
6717 * Unbind document key down listener.
6721 OO
.ui
.SelectWidget
.prototype.unbindDocumentKeyDownListener = function () {
6722 this.getElementDocument().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
6725 // Deprecated alias since 0.28.3
6726 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
6727 OO
.ui
.warnDeprecation( 'unbindKeyDownListener is deprecated, use unbindDocumentKeyDownListener instead' );
6728 this.unbindDocumentKeyDownListener
.apply( this, arguments
);
6732 * Scroll item into view, preventing spurious mouse highlight actions from happening.
6734 * @param {OO.ui.OptionWidget} item Item to scroll into view
6736 OO
.ui
.SelectWidget
.prototype.scrollItemIntoView = function ( item
) {
6738 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling
6739 // and around 100-150 ms after it is finished.
6740 this.blockMouseOverEvents
++;
6741 item
.scrollElementIntoView().done( function () {
6742 setTimeout( function () {
6743 widget
.blockMouseOverEvents
--;
6749 * Clear the key-press buffer
6753 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
6754 if ( this.keyPressBufferTimer
) {
6755 clearTimeout( this.keyPressBufferTimer
);
6756 this.keyPressBufferTimer
= null;
6758 this.keyPressBuffer
= '';
6762 * Handle key press events.
6765 * @param {KeyboardEvent} e Key press event
6766 * @return {undefined/boolean} False to prevent default if event is handled
6768 OO
.ui
.SelectWidget
.prototype.onDocumentKeyPress = function ( e
) {
6769 var c
, filter
, item
;
6771 if ( !e
.charCode
) {
6772 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
6773 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
6778 // eslint-disable-next-line no-restricted-properties
6779 if ( String
.fromCodePoint
) {
6780 // eslint-disable-next-line no-restricted-properties
6781 c
= String
.fromCodePoint( e
.charCode
);
6783 c
= String
.fromCharCode( e
.charCode
);
6786 if ( this.keyPressBufferTimer
) {
6787 clearTimeout( this.keyPressBufferTimer
);
6789 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
6791 item
= this.findHighlightedItem() || this.findSelectedItem();
6793 if ( this.keyPressBuffer
=== c
) {
6794 // Common (if weird) special case: typing "xxxx" will cycle through all
6795 // the items beginning with "x".
6797 item
= this.findRelativeSelectableItem( item
, 1 );
6800 this.keyPressBuffer
+= c
;
6803 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
6804 if ( !item
|| !filter( item
) ) {
6805 item
= this.findRelativeSelectableItem( item
, 1, filter
);
6808 if ( this.isVisible() && item
.constructor.static.highlightable
) {
6809 this.highlightItem( item
);
6811 this.chooseItem( item
);
6813 this.scrollItemIntoView( item
);
6817 e
.stopPropagation();
6820 // Deprecated alias since 0.28.3
6821 OO
.ui
.SelectWidget
.prototype.onKeyPress = function () {
6822 OO
.ui
.warnDeprecation( 'onKeyPress is deprecated, use onDocumentKeyPress instead' );
6823 this.onDocumentKeyPress
.apply( this, arguments
);
6827 * Get a matcher for the specific string
6830 * @param {string} s String to match against items
6831 * @param {boolean} [exact=false] Only accept exact matches
6832 * @return {Function} function ( OO.ui.OptionWidget ) => boolean
6834 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
, exact
) {
6837 // eslint-disable-next-line no-restricted-properties
6838 if ( s
.normalize
) {
6839 // eslint-disable-next-line no-restricted-properties
6842 s
= exact
? s
.trim() : s
.replace( /^\s+/, '' );
6843 re
= '^\\s*' + s
.replace( /([\\{}()|.?*+\-^$[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
6847 re
= new RegExp( re
, 'i' );
6848 return function ( item
) {
6849 var matchText
= item
.getMatchText();
6850 // eslint-disable-next-line no-restricted-properties
6851 if ( matchText
.normalize
) {
6852 // eslint-disable-next-line no-restricted-properties
6853 matchText
= matchText
.normalize();
6855 return re
.test( matchText
);
6860 * Bind document key press listener.
6864 OO
.ui
.SelectWidget
.prototype.bindDocumentKeyPressListener = function () {
6865 this.getElementDocument().addEventListener( 'keypress', this.onDocumentKeyPressHandler
, true );
6868 // Deprecated alias since 0.28.3
6869 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
6870 OO
.ui
.warnDeprecation( 'bindKeyPressListener is deprecated, use bindDocumentKeyPressListener instead' );
6871 this.bindDocumentKeyPressListener
.apply( this, arguments
);
6875 * Unbind document key down listener.
6877 * If you override this, be sure to call this.clearKeyPressBuffer() from your
6882 OO
.ui
.SelectWidget
.prototype.unbindDocumentKeyPressListener = function () {
6883 this.getElementDocument().removeEventListener( 'keypress', this.onDocumentKeyPressHandler
, true );
6884 this.clearKeyPressBuffer();
6887 // Deprecated alias since 0.28.3
6888 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
6889 OO
.ui
.warnDeprecation( 'unbindKeyPressListener is deprecated, use unbindDocumentKeyPressListener instead' );
6890 this.unbindDocumentKeyPressListener
.apply( this, arguments
);
6894 * Visibility change handler
6897 * @param {boolean} visible
6899 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
6901 this.clearKeyPressBuffer();
6906 * Get the closest item to a jQuery.Event.
6909 * @param {jQuery.Event} e
6910 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
6912 OO
.ui
.SelectWidget
.prototype.findTargetItem = function ( e
) {
6913 var $option
= $( e
.target
).closest( '.oo-ui-optionWidget' );
6914 if ( !$option
.closest( '.oo-ui-selectWidget' ).is( this.$element
) ) {
6917 return $option
.data( 'oo-ui-optionWidget' ) || null;
6921 * Find selected item.
6923 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
6925 OO
.ui
.SelectWidget
.prototype.findSelectedItem = function () {
6928 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6929 if ( this.items
[ i
].isSelected() ) {
6930 return this.items
[ i
];
6937 * Find highlighted item.
6939 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
6941 OO
.ui
.SelectWidget
.prototype.findHighlightedItem = function () {
6944 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6945 if ( this.items
[ i
].isHighlighted() ) {
6946 return this.items
[ i
];
6953 * Toggle pressed state.
6955 * Press is a state that occurs when a user mouses down on an item, but
6956 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
6957 * until the user releases the mouse.
6959 * @param {boolean} pressed An option is being pressed
6961 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
6962 if ( pressed
=== undefined ) {
6963 pressed
= !this.pressed
;
6965 if ( pressed
!== this.pressed
) {
6967 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
6968 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
6969 this.pressed
= pressed
;
6974 * Highlight an option. If the `item` param is omitted, no options will be highlighted
6975 * and any existing highlight will be removed. The highlight is mutually exclusive.
6977 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
6980 * @return {OO.ui.Widget} The widget, for chaining
6982 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
6983 var i
, len
, highlighted
,
6986 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6987 highlighted
= this.items
[ i
] === item
;
6988 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
6989 this.items
[ i
].setHighlighted( highlighted
);
6995 this.$focusOwner
.attr( 'aria-activedescendant', item
.getElementId() );
6997 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
6999 this.emit( 'highlight', item
);
7006 * Fetch an item by its label.
7008 * @param {string} label Label of the item to select.
7009 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
7010 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
7012 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
7014 len
= this.items
.length
,
7015 filter
= this.getItemMatcher( label
, true );
7017 for ( i
= 0; i
< len
; i
++ ) {
7018 item
= this.items
[ i
];
7019 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
7026 filter
= this.getItemMatcher( label
, false );
7027 for ( i
= 0; i
< len
; i
++ ) {
7028 item
= this.items
[ i
];
7029 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
7045 * Programmatically select an option by its label. If the item does not exist,
7046 * all options will be deselected.
7048 * @param {string} [label] Label of the item to select.
7049 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
7052 * @return {OO.ui.Widget} The widget, for chaining
7054 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
7055 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
7056 if ( label
=== undefined || !itemFromLabel
) {
7057 return this.selectItem();
7059 return this.selectItem( itemFromLabel
);
7063 * Programmatically select an option by its data. If the `data` parameter is omitted,
7064 * or if the item does not exist, all options will be deselected.
7066 * @param {Object|string} [data] Value of the item to select, omit to deselect all
7069 * @return {OO.ui.Widget} The widget, for chaining
7071 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
7072 var itemFromData
= this.findItemFromData( data
);
7073 if ( data
=== undefined || !itemFromData
) {
7074 return this.selectItem();
7076 return this.selectItem( itemFromData
);
7080 * Programmatically select an option by its reference. If the `item` parameter is omitted,
7081 * all options will be deselected.
7083 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
7086 * @return {OO.ui.Widget} The widget, for chaining
7088 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
7089 var i
, len
, selected
,
7092 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
7093 selected
= this.items
[ i
] === item
;
7094 if ( this.items
[ i
].isSelected() !== selected
) {
7095 this.items
[ i
].setSelected( selected
);
7100 if ( item
&& !item
.constructor.static.highlightable
) {
7102 this.$focusOwner
.attr( 'aria-activedescendant', item
.getElementId() );
7104 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
7107 this.emit( 'select', item
);
7116 * Press is a state that occurs when a user mouses down on an item, but has not
7117 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
7118 * releases the mouse.
7120 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
7123 * @return {OO.ui.Widget} The widget, for chaining
7125 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
7126 var i
, len
, pressed
,
7129 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
7130 pressed
= this.items
[ i
] === item
;
7131 if ( this.items
[ i
].isPressed() !== pressed
) {
7132 this.items
[ i
].setPressed( pressed
);
7137 this.emit( 'press', item
);
7146 * Note that ‘choose’ should never be modified programmatically. A user can choose
7147 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
7148 * use the #selectItem method.
7150 * This method is identical to #selectItem, but may vary in subclasses that take additional action
7151 * when users choose an item with the keyboard or mouse.
7153 * @param {OO.ui.OptionWidget} item Item to choose
7156 * @return {OO.ui.Widget} The widget, for chaining
7158 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
7160 this.selectItem( item
);
7161 this.emit( 'choose', item
);
7168 * Find an option by its position relative to the specified item (or to the start of the option array,
7169 * if item is `null`). The direction in which to search through the option array is specified with a
7170 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
7171 * `null` if there are no options in the array.
7173 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
7174 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
7175 * @param {Function} [filter] Only consider items for which this function returns
7176 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
7177 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
7179 OO
.ui
.SelectWidget
.prototype.findRelativeSelectableItem = function ( item
, direction
, filter
) {
7180 var currentIndex
, nextIndex
, i
,
7181 increase
= direction
> 0 ? 1 : -1,
7182 len
= this.items
.length
;
7184 if ( item
instanceof OO
.ui
.OptionWidget
) {
7185 currentIndex
= this.items
.indexOf( item
);
7186 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
7188 // If no item is selected and moving forward, start at the beginning.
7189 // If moving backward, start at the end.
7190 nextIndex
= direction
> 0 ? 0 : len
- 1;
7193 for ( i
= 0; i
< len
; i
++ ) {
7194 item
= this.items
[ nextIndex
];
7196 item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() &&
7197 ( !filter
|| filter( item
) )
7201 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
7207 * Find the next selectable item or `null` if there are no selectable items.
7208 * Disabled options and menu-section markers and breaks are not selectable.
7210 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
7212 OO
.ui
.SelectWidget
.prototype.findFirstSelectableItem = function () {
7213 return this.findRelativeSelectableItem( null, 1 );
7217 * Add an array of options to the select. Optionally, an index number can be used to
7218 * specify an insertion point.
7220 * @param {OO.ui.OptionWidget[]} items Items to add
7221 * @param {number} [index] Index to insert items after
7224 * @return {OO.ui.Widget} The widget, for chaining
7226 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
7228 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
7230 // Always provide an index, even if it was omitted
7231 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
7237 * Remove the specified array of options from the select. Options will be detached
7238 * from the DOM, not removed, so they can be reused later. To remove all options from
7239 * the select, you may wish to use the #clearItems method instead.
7241 * @param {OO.ui.OptionWidget[]} items Items to remove
7244 * @return {OO.ui.Widget} The widget, for chaining
7246 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
7249 // Deselect items being removed
7250 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
7252 if ( item
.isSelected() ) {
7253 this.selectItem( null );
7258 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
7260 this.emit( 'remove', items
);
7266 * Clear all options from the select. Options will be detached from the DOM, not removed,
7267 * so that they can be reused later. To remove a subset of options from the select, use
7268 * the #removeItems method.
7272 * @return {OO.ui.Widget} The widget, for chaining
7274 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
7275 var items
= this.items
.slice();
7278 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
7281 this.selectItem( null );
7283 this.emit( 'remove', items
);
7289 * Set the DOM element which has focus while the user is interacting with this SelectWidget.
7291 * Currently this is just used to set `aria-activedescendant` on it.
7294 * @param {jQuery} $focusOwner
7296 OO
.ui
.SelectWidget
.prototype.setFocusOwner = function ( $focusOwner
) {
7297 this.$focusOwner
= $focusOwner
;
7301 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
7302 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
7303 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
7304 * options. For more information about options and selects, please see the
7305 * [OOUI documentation on MediaWiki][1].
7308 * // Decorated options in a select widget
7309 * var select = new OO.ui.SelectWidget( {
7311 * new OO.ui.DecoratedOptionWidget( {
7313 * label: 'Option with icon',
7316 * new OO.ui.DecoratedOptionWidget( {
7318 * label: 'Option with indicator',
7323 * $( 'body' ).append( select.$element );
7325 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7328 * @extends OO.ui.OptionWidget
7329 * @mixins OO.ui.mixin.IconElement
7330 * @mixins OO.ui.mixin.IndicatorElement
7333 * @param {Object} [config] Configuration options
7335 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
7336 // Parent constructor
7337 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
7339 // Mixin constructors
7340 OO
.ui
.mixin
.IconElement
.call( this, config
);
7341 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
7345 .addClass( 'oo-ui-decoratedOptionWidget' )
7346 .prepend( this.$icon
)
7347 .append( this.$indicator
);
7352 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
7353 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
7354 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
7357 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
7358 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
7359 * the [OOUI documentation on MediaWiki] [1] for more information.
7361 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
7364 * @extends OO.ui.DecoratedOptionWidget
7367 * @param {Object} [config] Configuration options
7369 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
7370 // Parent constructor
7371 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
7374 this.checkIcon
= new OO
.ui
.IconWidget( {
7376 classes
: [ 'oo-ui-menuOptionWidget-checkIcon' ]
7381 .prepend( this.checkIcon
.$element
)
7382 .addClass( 'oo-ui-menuOptionWidget' );
7387 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
7389 /* Static Properties */
7395 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
7398 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
7399 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
7402 * var myDropdown = new OO.ui.DropdownWidget( {
7405 * new OO.ui.MenuSectionOptionWidget( {
7408 * new OO.ui.MenuOptionWidget( {
7410 * label: 'Welsh Corgi'
7412 * new OO.ui.MenuOptionWidget( {
7414 * label: 'Standard Poodle'
7416 * new OO.ui.MenuSectionOptionWidget( {
7419 * new OO.ui.MenuOptionWidget( {
7426 * $( 'body' ).append( myDropdown.$element );
7429 * @extends OO.ui.DecoratedOptionWidget
7432 * @param {Object} [config] Configuration options
7434 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
7435 // Parent constructor
7436 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
7439 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' )
7440 .removeAttr( 'role aria-selected' );
7445 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
7447 /* Static Properties */
7453 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
7459 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
7462 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
7463 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
7464 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
7465 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
7466 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
7467 * and customized to be opened, closed, and displayed as needed.
7469 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
7470 * mouse outside the menu.
7472 * Menus also have support for keyboard interaction:
7474 * - Enter/Return key: choose and select a menu option
7475 * - Up-arrow key: highlight the previous menu option
7476 * - Down-arrow key: highlight the next menu option
7477 * - Esc key: hide the menu
7479 * Unlike most widgets, MenuSelectWidget is initially hidden and must be shown by calling #toggle.
7481 * Please see the [OOUI documentation on MediaWiki][1] for more information.
7482 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7485 * @extends OO.ui.SelectWidget
7486 * @mixins OO.ui.mixin.ClippableElement
7487 * @mixins OO.ui.mixin.FloatableElement
7490 * @param {Object} [config] Configuration options
7491 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
7492 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
7493 * and {@link OO.ui.mixin.LookupElement LookupElement}
7494 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
7495 * the text the user types. This config is used by {@link OO.ui.TagMultiselectWidget TagMultiselectWidget}
7496 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
7497 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
7498 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
7499 * that button, unless the button (or its parent widget) is passed in here.
7500 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
7501 * @cfg {jQuery} [$autoCloseIgnore] If these elements are clicked, don't auto-hide the menu.
7502 * @cfg {boolean} [hideOnChoose=true] Hide the menu when the user chooses an option.
7503 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
7504 * @cfg {boolean} [highlightOnFilter] Highlight the first result when filtering
7505 * @cfg {number} [width] Width of the menu
7507 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
7508 // Configuration initialization
7509 config
= config
|| {};
7511 // Parent constructor
7512 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
7514 // Mixin constructors
7515 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
7516 OO
.ui
.mixin
.FloatableElement
.call( this, config
);
7518 // Initial vertical positions other than 'center' will result in
7519 // the menu being flipped if there is not enough space in the container.
7520 // Store the original position so we know what to reset to.
7521 this.originalVerticalPosition
= this.verticalPosition
;
7524 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
7525 this.hideOnChoose
= config
.hideOnChoose
=== undefined || !!config
.hideOnChoose
;
7526 this.filterFromInput
= !!config
.filterFromInput
;
7527 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
7528 this.$widget
= config
.widget
? config
.widget
.$element
: null;
7529 this.$autoCloseIgnore
= config
.$autoCloseIgnore
|| $( [] );
7530 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
7531 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
7532 this.highlightOnFilter
= !!config
.highlightOnFilter
;
7533 this.width
= config
.width
;
7536 this.$element
.addClass( 'oo-ui-menuSelectWidget' );
7537 if ( config
.widget
) {
7538 this.setFocusOwner( config
.widget
.$tabIndexed
);
7541 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
7542 // that reference properties not initialized at that time of parent class construction
7543 // TODO: Find a better way to handle post-constructor setup
7544 this.visible
= false;
7545 this.$element
.addClass( 'oo-ui-element-hidden' );
7550 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
7551 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
7552 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.FloatableElement
);
7559 * The menu is ready: it is visible and has been positioned and clipped.
7562 /* Static properties */
7565 * Positions to flip to if there isn't room in the container for the
7566 * menu in a specific direction.
7568 * @property {Object.<string,string>}
7570 OO
.ui
.MenuSelectWidget
.static.flippedPositions
= {
7580 * Handles document mouse down events.
7583 * @param {MouseEvent} e Mouse down event
7585 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
7589 this.$element
.add( this.$widget
).add( this.$autoCloseIgnore
).get(),
7594 this.toggle( false );
7601 OO
.ui
.MenuSelectWidget
.prototype.onDocumentKeyDown = function ( e
) {
7602 var currentItem
= this.findHighlightedItem() || this.findSelectedItem();
7604 if ( !this.isDisabled() && this.isVisible() ) {
7605 switch ( e
.keyCode
) {
7606 case OO
.ui
.Keys
.LEFT
:
7607 case OO
.ui
.Keys
.RIGHT
:
7608 // Do nothing if a text field is associated, arrow keys will be handled natively
7609 if ( !this.$input
) {
7610 OO
.ui
.MenuSelectWidget
.parent
.prototype.onDocumentKeyDown
.call( this, e
);
7613 case OO
.ui
.Keys
.ESCAPE
:
7614 case OO
.ui
.Keys
.TAB
:
7615 if ( currentItem
) {
7616 currentItem
.setHighlighted( false );
7618 this.toggle( false );
7619 // Don't prevent tabbing away, prevent defocusing
7620 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
7622 e
.stopPropagation();
7626 OO
.ui
.MenuSelectWidget
.parent
.prototype.onDocumentKeyDown
.call( this, e
);
7633 * Update menu item visibility and clipping after input changes (if filterFromInput is enabled)
7634 * or after items were added/removed (always).
7638 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
7639 var i
, item
, items
, visible
, section
, sectionEmpty
, filter
, exactFilter
,
7641 len
= this.items
.length
,
7642 showAll
= !this.isVisible(),
7645 if ( this.$input
&& this.filterFromInput
) {
7646 filter
= showAll
? null : this.getItemMatcher( this.$input
.val() );
7647 exactFilter
= this.getItemMatcher( this.$input
.val(), true );
7648 // Hide non-matching options, and also hide section headers if all options
7649 // in their section are hidden.
7650 for ( i
= 0; i
< len
; i
++ ) {
7651 item
= this.items
[ i
];
7652 if ( item
instanceof OO
.ui
.MenuSectionOptionWidget
) {
7654 // If the previous section was empty, hide its header
7655 section
.toggle( showAll
|| !sectionEmpty
);
7658 sectionEmpty
= true;
7659 } else if ( item
instanceof OO
.ui
.OptionWidget
) {
7660 visible
= showAll
|| filter( item
);
7661 exactMatch
= exactMatch
|| exactFilter( item
);
7662 anyVisible
= anyVisible
|| visible
;
7663 sectionEmpty
= sectionEmpty
&& !visible
;
7664 item
.toggle( visible
);
7667 // Process the final section
7669 section
.toggle( showAll
|| !sectionEmpty
);
7672 if ( anyVisible
&& this.items
.length
&& !exactMatch
) {
7673 this.scrollItemIntoView( this.items
[ 0 ] );
7676 if ( !anyVisible
) {
7677 this.highlightItem( null );
7680 this.$element
.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible
);
7682 if ( this.highlightOnFilter
) {
7683 // Highlight the first item on the list
7685 items
= this.getItems();
7686 for ( i
= 0; i
< items
.length
; i
++ ) {
7687 if ( items
[ i
].isVisible() ) {
7692 this.highlightItem( item
);
7697 // Reevaluate clipping
7704 OO
.ui
.MenuSelectWidget
.prototype.bindDocumentKeyDownListener = function () {
7705 if ( this.$input
) {
7706 this.$input
.on( 'keydown', this.onDocumentKeyDownHandler
);
7708 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindDocumentKeyDownListener
.call( this );
7715 OO
.ui
.MenuSelectWidget
.prototype.unbindDocumentKeyDownListener = function () {
7716 if ( this.$input
) {
7717 this.$input
.off( 'keydown', this.onDocumentKeyDownHandler
);
7719 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindDocumentKeyDownListener
.call( this );
7726 OO
.ui
.MenuSelectWidget
.prototype.bindDocumentKeyPressListener = function () {
7727 if ( this.$input
) {
7728 if ( this.filterFromInput
) {
7729 this.$input
.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
7730 this.updateItemVisibility();
7733 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindDocumentKeyPressListener
.call( this );
7740 OO
.ui
.MenuSelectWidget
.prototype.unbindDocumentKeyPressListener = function () {
7741 if ( this.$input
) {
7742 if ( this.filterFromInput
) {
7743 this.$input
.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
7744 this.updateItemVisibility();
7747 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindDocumentKeyPressListener
.call( this );
7754 * When a user chooses an item, the menu is closed, unless the hideOnChoose config option is set to false.
7756 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
7757 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
7759 * @param {OO.ui.OptionWidget} item Item to choose
7761 * @return {OO.ui.Widget} The widget, for chaining
7763 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
7764 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
7765 if ( this.hideOnChoose
) {
7766 this.toggle( false );
7774 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
7776 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
7778 this.updateItemVisibility();
7786 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
7788 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
7790 this.updateItemVisibility();
7798 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
7800 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
7802 this.updateItemVisibility();
7808 * Toggle visibility of the menu. The menu is initially hidden and must be shown by calling
7809 * `.toggle( true )` after its #$element is attached to the DOM.
7811 * Do not show the menu while it is not attached to the DOM. The calculations required to display
7812 * it in the right place and with the right dimensions only work correctly while it is attached.
7813 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
7814 * strictly enforced, so currently it only generates a warning in the browser console.
7819 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
7820 var change
, originalHeight
, flippedHeight
;
7822 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
7823 change
= visible
!== this.isVisible();
7825 if ( visible
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
7826 OO
.ui
.warnDeprecation( 'MenuSelectWidget#toggle: Before calling this method, the menu must be attached to the DOM.' );
7827 this.warnedUnattached
= true;
7830 if ( change
&& visible
) {
7831 // Reset position before showing the popup again. It's possible we no longer need to flip
7832 // (e.g. if the user scrolled).
7833 this.setVerticalPosition( this.originalVerticalPosition
);
7837 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
7843 this.setIdealSize( this.width
);
7844 } else if ( this.$floatableContainer
) {
7845 this.$clippable
.css( 'width', 'auto' );
7847 this.$floatableContainer
[ 0 ].offsetWidth
> this.$clippable
[ 0 ].offsetWidth
?
7848 // Dropdown is smaller than handle so expand to width
7849 this.$floatableContainer
[ 0 ].offsetWidth
:
7850 // Dropdown is larger than handle so auto size
7853 this.$clippable
.css( 'width', '' );
7856 this.togglePositioning( !!this.$floatableContainer
);
7857 this.toggleClipping( true );
7859 this.bindDocumentKeyDownListener();
7860 this.bindDocumentKeyPressListener();
7863 ( this.isClippedVertically() || this.isFloatableOutOfView() ) &&
7864 this.originalVerticalPosition
!== 'center'
7866 // If opening the menu in one direction causes it to be clipped, flip it
7867 originalHeight
= this.$element
.height();
7868 this.setVerticalPosition(
7869 this.constructor.static.flippedPositions
[ this.originalVerticalPosition
]
7871 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
7872 // If flipping also causes it to be clipped, open in whichever direction
7873 // we have more space
7874 flippedHeight
= this.$element
.height();
7875 if ( originalHeight
> flippedHeight
) {
7876 this.setVerticalPosition( this.originalVerticalPosition
);
7880 // Note that we do not flip the menu's opening direction if the clipping changes
7881 // later (e.g. after the user scrolls), that seems like it would be annoying
7883 this.$focusOwner
.attr( 'aria-expanded', 'true' );
7885 if ( this.findSelectedItem() ) {
7886 this.$focusOwner
.attr( 'aria-activedescendant', this.findSelectedItem().getElementId() );
7887 this.findSelectedItem().scrollElementIntoView( { duration
: 0 } );
7891 if ( this.autoHide
) {
7892 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
7895 this.emit( 'ready' );
7897 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
7898 this.unbindDocumentKeyDownListener();
7899 this.unbindDocumentKeyPressListener();
7900 this.$focusOwner
.attr( 'aria-expanded', 'false' );
7901 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
7902 this.togglePositioning( false );
7903 this.toggleClipping( false );
7911 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
7912 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
7913 * users can interact with it.
7915 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7916 * OO.ui.DropdownInputWidget instead.
7919 * // Example: A DropdownWidget with a menu that contains three options
7920 * var dropDown = new OO.ui.DropdownWidget( {
7921 * label: 'Dropdown menu: Select a menu option',
7924 * new OO.ui.MenuOptionWidget( {
7928 * new OO.ui.MenuOptionWidget( {
7932 * new OO.ui.MenuOptionWidget( {
7940 * $( 'body' ).append( dropDown.$element );
7942 * dropDown.getMenu().selectItemByData( 'b' );
7944 * dropDown.getMenu().findSelectedItem().getData(); // returns 'b'
7946 * For more information, please see the [OOUI documentation on MediaWiki] [1].
7948 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
7951 * @extends OO.ui.Widget
7952 * @mixins OO.ui.mixin.IconElement
7953 * @mixins OO.ui.mixin.IndicatorElement
7954 * @mixins OO.ui.mixin.LabelElement
7955 * @mixins OO.ui.mixin.TitledElement
7956 * @mixins OO.ui.mixin.TabIndexedElement
7959 * @param {Object} [config] Configuration options
7960 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.MenuSelectWidget menu select widget}
7961 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
7962 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
7963 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
7964 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
7966 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
7967 // Configuration initialization
7968 config
= $.extend( { indicator
: 'down' }, config
);
7970 // Parent constructor
7971 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
7973 // Properties (must be set before TabIndexedElement constructor call)
7974 this.$handle
= $( '<span>' );
7975 this.$overlay
= ( config
.$overlay
=== true ? OO
.ui
.getDefaultOverlay() : config
.$overlay
) || this.$element
;
7977 // Mixin constructors
7978 OO
.ui
.mixin
.IconElement
.call( this, config
);
7979 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
7980 OO
.ui
.mixin
.LabelElement
.call( this, config
);
7981 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
7982 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
7985 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend( {
7987 $floatableContainer
: this.$element
7992 click
: this.onClick
.bind( this ),
7993 keydown
: this.onKeyDown
.bind( this ),
7994 // Hack? Handle type-to-search when menu is not expanded and not handling its own events
7995 keypress
: this.menu
.onDocumentKeyPressHandler
,
7996 blur
: this.menu
.clearKeyPressBuffer
.bind( this.menu
)
7998 this.menu
.connect( this, {
7999 select
: 'onMenuSelect',
8000 toggle
: 'onMenuToggle'
8005 .addClass( 'oo-ui-dropdownWidget-handle' )
8008 'aria-owns': this.menu
.getElementId(),
8009 'aria-autocomplete': 'list'
8011 .append( this.$icon
, this.$label
, this.$indicator
);
8013 .addClass( 'oo-ui-dropdownWidget' )
8014 .append( this.$handle
);
8015 this.$overlay
.append( this.menu
.$element
);
8020 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
8021 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
8022 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
8023 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
8024 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
8025 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
8032 * @return {OO.ui.MenuSelectWidget} Menu of widget
8034 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
8039 * Handles menu select events.
8042 * @param {OO.ui.MenuOptionWidget} item Selected menu item
8044 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
8048 this.setLabel( null );
8052 selectedLabel
= item
.getLabel();
8054 // If the label is a DOM element, clone it, because setLabel will append() it
8055 if ( selectedLabel
instanceof $ ) {
8056 selectedLabel
= selectedLabel
.clone();
8059 this.setLabel( selectedLabel
);
8063 * Handle menu toggle events.
8066 * @param {boolean} isVisible Open state of the menu
8068 OO
.ui
.DropdownWidget
.prototype.onMenuToggle = function ( isVisible
) {
8069 this.$element
.toggleClass( 'oo-ui-dropdownWidget-open', isVisible
);
8072 this.$element
.hasClass( 'oo-ui-dropdownWidget-open' ).toString()
8077 * Handle mouse click events.
8080 * @param {jQuery.Event} e Mouse click event
8081 * @return {undefined/boolean} False to prevent default if event is handled
8083 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
8084 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
8091 * Handle key down events.
8094 * @param {jQuery.Event} e Key down event
8095 * @return {undefined/boolean} False to prevent default if event is handled
8097 OO
.ui
.DropdownWidget
.prototype.onKeyDown = function ( e
) {
8099 !this.isDisabled() &&
8101 e
.which
=== OO
.ui
.Keys
.ENTER
||
8103 e
.which
=== OO
.ui
.Keys
.SPACE
&&
8104 // Avoid conflicts with type-to-search, see SelectWidget#onKeyPress.
8105 // Space only closes the menu is the user is not typing to search.
8106 this.menu
.keyPressBuffer
=== ''
8109 !this.menu
.isVisible() &&
8111 e
.which
=== OO
.ui
.Keys
.UP
||
8112 e
.which
=== OO
.ui
.Keys
.DOWN
8123 * RadioOptionWidget is an option widget that looks like a radio button.
8124 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
8125 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8127 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8130 * @extends OO.ui.OptionWidget
8133 * @param {Object} [config] Configuration options
8135 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
8136 // Configuration initialization
8137 config
= config
|| {};
8139 // Properties (must be done before parent constructor which calls #setDisabled)
8140 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
8142 // Parent constructor
8143 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
8146 // Remove implicit role, we're handling it ourselves
8147 this.radio
.$input
.attr( 'role', 'presentation' );
8149 .addClass( 'oo-ui-radioOptionWidget' )
8150 .attr( 'role', 'radio' )
8151 .attr( 'aria-checked', 'false' )
8152 .removeAttr( 'aria-selected' )
8153 .prepend( this.radio
.$element
);
8158 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
8160 /* Static Properties */
8166 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
8172 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
8178 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
8184 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
8191 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
8192 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
8194 this.radio
.setSelected( state
);
8196 .attr( 'aria-checked', state
.toString() )
8197 .removeAttr( 'aria-selected' );
8205 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
8206 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
8208 this.radio
.setDisabled( this.isDisabled() );
8214 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
8215 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
8216 * an interface for adding, removing and selecting options.
8217 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8219 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8220 * OO.ui.RadioSelectInputWidget instead.
8223 * // A RadioSelectWidget with RadioOptions.
8224 * var option1 = new OO.ui.RadioOptionWidget( {
8226 * label: 'Selected radio option'
8229 * var option2 = new OO.ui.RadioOptionWidget( {
8231 * label: 'Unselected radio option'
8234 * var radioSelect=new OO.ui.RadioSelectWidget( {
8235 * items: [ option1, option2 ]
8238 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
8239 * radioSelect.selectItem( option1 );
8241 * $( 'body' ).append( radioSelect.$element );
8243 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8247 * @extends OO.ui.SelectWidget
8248 * @mixins OO.ui.mixin.TabIndexedElement
8251 * @param {Object} [config] Configuration options
8253 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
8254 // Parent constructor
8255 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
8257 // Mixin constructors
8258 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
8262 focus
: this.bindDocumentKeyDownListener
.bind( this ),
8263 blur
: this.unbindDocumentKeyDownListener
.bind( this )
8268 .addClass( 'oo-ui-radioSelectWidget' )
8269 .attr( 'role', 'radiogroup' );
8274 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
8275 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
8278 * MultioptionWidgets are special elements that can be selected and configured with data. The
8279 * data is often unique for each option, but it does not have to be. MultioptionWidgets are used
8280 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
8281 * and examples, please see the [OOUI documentation on MediaWiki][1].
8283 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Multioptions
8286 * @extends OO.ui.Widget
8287 * @mixins OO.ui.mixin.ItemWidget
8288 * @mixins OO.ui.mixin.LabelElement
8291 * @param {Object} [config] Configuration options
8292 * @cfg {boolean} [selected=false] Whether the option is initially selected
8294 OO
.ui
.MultioptionWidget
= function OoUiMultioptionWidget( config
) {
8295 // Configuration initialization
8296 config
= config
|| {};
8298 // Parent constructor
8299 OO
.ui
.MultioptionWidget
.parent
.call( this, config
);
8301 // Mixin constructors
8302 OO
.ui
.mixin
.ItemWidget
.call( this );
8303 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8306 this.selected
= null;
8310 .addClass( 'oo-ui-multioptionWidget' )
8311 .append( this.$label
);
8312 this.setSelected( config
.selected
);
8317 OO
.inheritClass( OO
.ui
.MultioptionWidget
, OO
.ui
.Widget
);
8318 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.ItemWidget
);
8319 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.LabelElement
);
8326 * A change event is emitted when the selected state of the option changes.
8328 * @param {boolean} selected Whether the option is now selected
8334 * Check if the option is selected.
8336 * @return {boolean} Item is selected
8338 OO
.ui
.MultioptionWidget
.prototype.isSelected = function () {
8339 return this.selected
;
8343 * Set the option’s selected state. In general, all modifications to the selection
8344 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
8345 * method instead of this method.
8347 * @param {boolean} [state=false] Select option
8349 * @return {OO.ui.Widget} The widget, for chaining
8351 OO
.ui
.MultioptionWidget
.prototype.setSelected = function ( state
) {
8353 if ( this.selected
!== state
) {
8354 this.selected
= state
;
8355 this.emit( 'change', state
);
8356 this.$element
.toggleClass( 'oo-ui-multioptionWidget-selected', state
);
8362 * MultiselectWidget allows selecting multiple options from a list.
8364 * For more information about menus and options, please see the [OOUI documentation on MediaWiki][1].
8366 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
8370 * @extends OO.ui.Widget
8371 * @mixins OO.ui.mixin.GroupWidget
8374 * @param {Object} [config] Configuration options
8375 * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
8377 OO
.ui
.MultiselectWidget
= function OoUiMultiselectWidget( config
) {
8378 // Parent constructor
8379 OO
.ui
.MultiselectWidget
.parent
.call( this, config
);
8381 // Configuration initialization
8382 config
= config
|| {};
8384 // Mixin constructors
8385 OO
.ui
.mixin
.GroupWidget
.call( this, config
);
8388 this.aggregate( { change
: 'select' } );
8389 // This is mostly for compatibility with TagMultiselectWidget... normally, 'change' is emitted
8390 // by GroupElement only when items are added/removed
8391 this.connect( this, { select
: [ 'emit', 'change' ] } );
8394 if ( config
.items
) {
8395 this.addItems( config
.items
);
8397 this.$group
.addClass( 'oo-ui-multiselectWidget-group' );
8398 this.$element
.addClass( 'oo-ui-multiselectWidget' )
8399 .append( this.$group
);
8404 OO
.inheritClass( OO
.ui
.MultiselectWidget
, OO
.ui
.Widget
);
8405 OO
.mixinClass( OO
.ui
.MultiselectWidget
, OO
.ui
.mixin
.GroupWidget
);
8412 * A change event is emitted when the set of items changes, or an item is selected or deselected.
8418 * A select event is emitted when an item is selected or deselected.
8424 * Find options that are selected.
8426 * @return {OO.ui.MultioptionWidget[]} Selected options
8428 OO
.ui
.MultiselectWidget
.prototype.findSelectedItems = function () {
8429 return this.items
.filter( function ( item
) {
8430 return item
.isSelected();
8435 * Find the data of options that are selected.
8437 * @return {Object[]|string[]} Values of selected options
8439 OO
.ui
.MultiselectWidget
.prototype.findSelectedItemsData = function () {
8440 return this.findSelectedItems().map( function ( item
) {
8446 * Select options by reference. Options not mentioned in the `items` array will be deselected.
8448 * @param {OO.ui.MultioptionWidget[]} items Items to select
8450 * @return {OO.ui.Widget} The widget, for chaining
8452 OO
.ui
.MultiselectWidget
.prototype.selectItems = function ( items
) {
8453 this.items
.forEach( function ( item
) {
8454 var selected
= items
.indexOf( item
) !== -1;
8455 item
.setSelected( selected
);
8461 * Select items by their data. Options not mentioned in the `datas` array will be deselected.
8463 * @param {Object[]|string[]} datas Values of items to select
8465 * @return {OO.ui.Widget} The widget, for chaining
8467 OO
.ui
.MultiselectWidget
.prototype.selectItemsByData = function ( datas
) {
8470 items
= datas
.map( function ( data
) {
8471 return widget
.findItemFromData( data
);
8473 this.selectItems( items
);
8478 * CheckboxMultioptionWidget is an option widget that looks like a checkbox.
8479 * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
8480 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8482 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8485 * @extends OO.ui.MultioptionWidget
8488 * @param {Object} [config] Configuration options
8490 OO
.ui
.CheckboxMultioptionWidget
= function OoUiCheckboxMultioptionWidget( config
) {
8491 // Configuration initialization
8492 config
= config
|| {};
8494 // Properties (must be done before parent constructor which calls #setDisabled)
8495 this.checkbox
= new OO
.ui
.CheckboxInputWidget();
8497 // Parent constructor
8498 OO
.ui
.CheckboxMultioptionWidget
.parent
.call( this, config
);
8501 this.checkbox
.on( 'change', this.onCheckboxChange
.bind( this ) );
8502 this.$element
.on( 'keydown', this.onKeyDown
.bind( this ) );
8506 .addClass( 'oo-ui-checkboxMultioptionWidget' )
8507 .prepend( this.checkbox
.$element
);
8512 OO
.inheritClass( OO
.ui
.CheckboxMultioptionWidget
, OO
.ui
.MultioptionWidget
);
8514 /* Static Properties */
8520 OO
.ui
.CheckboxMultioptionWidget
.static.tagName
= 'label';
8525 * Handle checkbox selected state change.
8529 OO
.ui
.CheckboxMultioptionWidget
.prototype.onCheckboxChange = function () {
8530 this.setSelected( this.checkbox
.isSelected() );
8536 OO
.ui
.CheckboxMultioptionWidget
.prototype.setSelected = function ( state
) {
8537 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setSelected
.call( this, state
);
8538 this.checkbox
.setSelected( state
);
8545 OO
.ui
.CheckboxMultioptionWidget
.prototype.setDisabled = function ( disabled
) {
8546 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
8547 this.checkbox
.setDisabled( this.isDisabled() );
8554 OO
.ui
.CheckboxMultioptionWidget
.prototype.focus = function () {
8555 this.checkbox
.focus();
8559 * Handle key down events.
8562 * @param {jQuery.Event} e
8564 OO
.ui
.CheckboxMultioptionWidget
.prototype.onKeyDown = function ( e
) {
8566 element
= this.getElementGroup(),
8569 if ( e
.keyCode
=== OO
.ui
.Keys
.LEFT
|| e
.keyCode
=== OO
.ui
.Keys
.UP
) {
8570 nextItem
= element
.getRelativeFocusableItem( this, -1 );
8571 } else if ( e
.keyCode
=== OO
.ui
.Keys
.RIGHT
|| e
.keyCode
=== OO
.ui
.Keys
.DOWN
) {
8572 nextItem
= element
.getRelativeFocusableItem( this, 1 );
8582 * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
8583 * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
8584 * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
8585 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8587 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8588 * OO.ui.CheckboxMultiselectInputWidget instead.
8591 * // A CheckboxMultiselectWidget with CheckboxMultioptions.
8592 * var option1 = new OO.ui.CheckboxMultioptionWidget( {
8595 * label: 'Selected checkbox'
8598 * var option2 = new OO.ui.CheckboxMultioptionWidget( {
8600 * label: 'Unselected checkbox'
8603 * var multiselect=new OO.ui.CheckboxMultiselectWidget( {
8604 * items: [ option1, option2 ]
8607 * $( 'body' ).append( multiselect.$element );
8609 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8612 * @extends OO.ui.MultiselectWidget
8615 * @param {Object} [config] Configuration options
8617 OO
.ui
.CheckboxMultiselectWidget
= function OoUiCheckboxMultiselectWidget( config
) {
8618 // Parent constructor
8619 OO
.ui
.CheckboxMultiselectWidget
.parent
.call( this, config
);
8622 this.$lastClicked
= null;
8625 this.$group
.on( 'click', this.onClick
.bind( this ) );
8629 .addClass( 'oo-ui-checkboxMultiselectWidget' );
8634 OO
.inheritClass( OO
.ui
.CheckboxMultiselectWidget
, OO
.ui
.MultiselectWidget
);
8639 * Get an option by its position relative to the specified item (or to the start of the option array,
8640 * if item is `null`). The direction in which to search through the option array is specified with a
8641 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
8642 * `null` if there are no options in the array.
8644 * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
8645 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
8646 * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items in the select
8648 OO
.ui
.CheckboxMultiselectWidget
.prototype.getRelativeFocusableItem = function ( item
, direction
) {
8649 var currentIndex
, nextIndex
, i
,
8650 increase
= direction
> 0 ? 1 : -1,
8651 len
= this.items
.length
;
8654 currentIndex
= this.items
.indexOf( item
);
8655 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
8657 // If no item is selected and moving forward, start at the beginning.
8658 // If moving backward, start at the end.
8659 nextIndex
= direction
> 0 ? 0 : len
- 1;
8662 for ( i
= 0; i
< len
; i
++ ) {
8663 item
= this.items
[ nextIndex
];
8664 if ( item
&& !item
.isDisabled() ) {
8667 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
8673 * Handle click events on checkboxes.
8675 * @param {jQuery.Event} e
8677 OO
.ui
.CheckboxMultiselectWidget
.prototype.onClick = function ( e
) {
8678 var $options
, lastClickedIndex
, nowClickedIndex
, i
, direction
, wasSelected
, items
,
8679 $lastClicked
= this.$lastClicked
,
8680 $nowClicked
= $( e
.target
).closest( '.oo-ui-checkboxMultioptionWidget' )
8681 .not( '.oo-ui-widget-disabled' );
8683 // Allow selecting multiple options at once by Shift-clicking them
8684 if ( $lastClicked
&& $nowClicked
.length
&& e
.shiftKey
) {
8685 $options
= this.$group
.find( '.oo-ui-checkboxMultioptionWidget' );
8686 lastClickedIndex
= $options
.index( $lastClicked
);
8687 nowClickedIndex
= $options
.index( $nowClicked
);
8688 // If it's the same item, either the user is being silly, or it's a fake event generated by the
8689 // browser. In either case we don't need custom handling.
8690 if ( nowClickedIndex
!== lastClickedIndex
) {
8692 wasSelected
= items
[ nowClickedIndex
].isSelected();
8693 direction
= nowClickedIndex
> lastClickedIndex
? 1 : -1;
8695 // This depends on the DOM order of the items and the order of the .items array being the same.
8696 for ( i
= lastClickedIndex
; i
!== nowClickedIndex
; i
+= direction
) {
8697 if ( !items
[ i
].isDisabled() ) {
8698 items
[ i
].setSelected( !wasSelected
);
8701 // For the now-clicked element, use immediate timeout to allow the browser to do its own
8702 // handling first, then set our value. The order in which events happen is different for
8703 // clicks on the <input> and on the <label> and there are additional fake clicks fired for
8704 // non-click actions that change the checkboxes.
8706 setTimeout( function () {
8707 if ( !items
[ nowClickedIndex
].isDisabled() ) {
8708 items
[ nowClickedIndex
].setSelected( !wasSelected
);
8714 if ( $nowClicked
.length
) {
8715 this.$lastClicked
= $nowClicked
;
8723 * @return {OO.ui.Widget} The widget, for chaining
8725 OO
.ui
.CheckboxMultiselectWidget
.prototype.focus = function () {
8727 if ( !this.isDisabled() ) {
8728 item
= this.getRelativeFocusableItem( null, 1 );
8739 OO
.ui
.CheckboxMultiselectWidget
.prototype.simulateLabelClick = function () {
8744 * Progress bars visually display the status of an operation, such as a download,
8745 * and can be either determinate or indeterminate:
8747 * - **determinate** process bars show the percent of an operation that is complete.
8749 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
8750 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
8751 * not use percentages.
8753 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
8756 * // Examples of determinate and indeterminate progress bars.
8757 * var progressBar1 = new OO.ui.ProgressBarWidget( {
8760 * var progressBar2 = new OO.ui.ProgressBarWidget();
8762 * // Create a FieldsetLayout to layout progress bars
8763 * var fieldset = new OO.ui.FieldsetLayout;
8764 * fieldset.addItems( [
8765 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
8766 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
8768 * $( 'body' ).append( fieldset.$element );
8771 * @extends OO.ui.Widget
8774 * @param {Object} [config] Configuration options
8775 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
8776 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
8777 * By default, the progress bar is indeterminate.
8779 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
8780 // Configuration initialization
8781 config
= config
|| {};
8783 // Parent constructor
8784 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
8787 this.$bar
= $( '<div>' );
8788 this.progress
= null;
8791 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
8792 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
8795 role
: 'progressbar',
8797 'aria-valuemax': 100
8799 .addClass( 'oo-ui-progressBarWidget' )
8800 .append( this.$bar
);
8805 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
8807 /* Static Properties */
8813 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
8818 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
8820 * @return {number|boolean} Progress percent
8822 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
8823 return this.progress
;
8827 * Set the percent of the process completed or `false` for an indeterminate process.
8829 * @param {number|boolean} progress Progress percent or `false` for indeterminate
8831 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
8832 this.progress
= progress
;
8834 if ( progress
!== false ) {
8835 this.$bar
.css( 'width', this.progress
+ '%' );
8836 this.$element
.attr( 'aria-valuenow', this.progress
);
8838 this.$bar
.css( 'width', '' );
8839 this.$element
.removeAttr( 'aria-valuenow' );
8841 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress
=== false );
8845 * InputWidget is the base class for all input widgets, which
8846 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
8847 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
8848 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
8850 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
8854 * @extends OO.ui.Widget
8855 * @mixins OO.ui.mixin.FlaggedElement
8856 * @mixins OO.ui.mixin.TabIndexedElement
8857 * @mixins OO.ui.mixin.TitledElement
8858 * @mixins OO.ui.mixin.AccessKeyedElement
8861 * @param {Object} [config] Configuration options
8862 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
8863 * @cfg {string} [value=''] The value of the input.
8864 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
8865 * @cfg {string} [inputId] The value of the input’s HTML `id` attribute.
8866 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
8867 * before it is accepted.
8869 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
8870 // Configuration initialization
8871 config
= config
|| {};
8873 // Parent constructor
8874 OO
.ui
.InputWidget
.parent
.call( this, config
);
8877 // See #reusePreInfuseDOM about config.$input
8878 this.$input
= config
.$input
|| this.getInputElement( config
);
8880 this.inputFilter
= config
.inputFilter
;
8882 // Mixin constructors
8883 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
8884 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
8885 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
8886 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$input
} ) );
8889 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
8893 .addClass( 'oo-ui-inputWidget-input' )
8894 .attr( 'name', config
.name
)
8895 .prop( 'disabled', this.isDisabled() );
8897 .addClass( 'oo-ui-inputWidget' )
8898 .append( this.$input
);
8899 this.setValue( config
.value
);
8901 this.setDir( config
.dir
);
8903 if ( config
.inputId
!== undefined ) {
8904 this.setInputId( config
.inputId
);
8910 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
8911 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
8912 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
8913 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
8914 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
8916 /* Static Methods */
8921 OO
.ui
.InputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
8922 config
= OO
.ui
.InputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
8923 // Reusing `$input` lets browsers preserve inputted values across page reloads, see T114134.
8924 config
.$input
= $( node
).find( '.oo-ui-inputWidget-input' );
8931 OO
.ui
.InputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8932 var state
= OO
.ui
.InputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8933 if ( config
.$input
&& config
.$input
.length
) {
8934 state
.value
= config
.$input
.val();
8935 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
8936 state
.focus
= config
.$input
.is( ':focus' );
8946 * A change event is emitted when the value of the input changes.
8948 * @param {string} value
8954 * Get input element.
8956 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
8957 * different circumstances. The element must have a `value` property (like form elements).
8960 * @param {Object} config Configuration options
8961 * @return {jQuery} Input element
8963 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
8964 return $( '<input>' );
8968 * Handle potentially value-changing events.
8971 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
8973 OO
.ui
.InputWidget
.prototype.onEdit = function () {
8975 if ( !this.isDisabled() ) {
8976 // Allow the stack to clear so the value will be updated
8977 setTimeout( function () {
8978 widget
.setValue( widget
.$input
.val() );
8984 * Get the value of the input.
8986 * @return {string} Input value
8988 OO
.ui
.InputWidget
.prototype.getValue = function () {
8989 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
8990 // it, and we won't know unless they're kind enough to trigger a 'change' event.
8991 var value
= this.$input
.val();
8992 if ( this.value
!== value
) {
8993 this.setValue( value
);
8999 * Set the directionality of the input.
9001 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
9003 * @return {OO.ui.Widget} The widget, for chaining
9005 OO
.ui
.InputWidget
.prototype.setDir = function ( dir
) {
9006 this.$input
.prop( 'dir', dir
);
9011 * Set the value of the input.
9013 * @param {string} value New value
9016 * @return {OO.ui.Widget} The widget, for chaining
9018 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
9019 value
= this.cleanUpValue( value
);
9020 // Update the DOM if it has changed. Note that with cleanUpValue, it
9021 // is possible for the DOM value to change without this.value changing.
9022 if ( this.$input
.val() !== value
) {
9023 this.$input
.val( value
);
9025 if ( this.value
!== value
) {
9027 this.emit( 'change', this.value
);
9029 // The first time that the value is set (probably while constructing the widget),
9030 // remember it in defaultValue. This property can be later used to check whether
9031 // the value of the input has been changed since it was created.
9032 if ( this.defaultValue
=== undefined ) {
9033 this.defaultValue
= this.value
;
9034 this.$input
[ 0 ].defaultValue
= this.defaultValue
;
9040 * Clean up incoming value.
9042 * Ensures value is a string, and converts undefined and null to empty string.
9045 * @param {string} value Original value
9046 * @return {string} Cleaned up value
9048 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
9049 if ( value
=== undefined || value
=== null ) {
9051 } else if ( this.inputFilter
) {
9052 return this.inputFilter( String( value
) );
9054 return String( value
);
9061 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
9062 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9063 if ( this.$input
) {
9064 this.$input
.prop( 'disabled', this.isDisabled() );
9070 * Set the 'id' attribute of the `<input>` element.
9072 * @param {string} id
9074 * @return {OO.ui.Widget} The widget, for chaining
9076 OO
.ui
.InputWidget
.prototype.setInputId = function ( id
) {
9077 this.$input
.attr( 'id', id
);
9084 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
9085 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
9086 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
9087 this.setValue( state
.value
);
9089 if ( state
.focus
) {
9095 * Data widget intended for creating 'hidden'-type inputs.
9098 * @extends OO.ui.Widget
9101 * @param {Object} [config] Configuration options
9102 * @cfg {string} [value=''] The value of the input.
9103 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
9105 OO
.ui
.HiddenInputWidget
= function OoUiHiddenInputWidget( config
) {
9106 // Configuration initialization
9107 config
= $.extend( { value
: '', name
: '' }, config
);
9109 // Parent constructor
9110 OO
.ui
.HiddenInputWidget
.parent
.call( this, config
);
9113 this.$element
.attr( {
9115 value
: config
.value
,
9118 this.$element
.removeAttr( 'aria-disabled' );
9123 OO
.inheritClass( OO
.ui
.HiddenInputWidget
, OO
.ui
.Widget
);
9125 /* Static Properties */
9131 OO
.ui
.HiddenInputWidget
.static.tagName
= 'input';
9134 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
9135 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
9136 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
9137 * HTML `<button>` (the default) or an HTML `<input>` tags. See the
9138 * [OOUI documentation on MediaWiki] [1] for more information.
9141 * // A ButtonInputWidget rendered as an HTML button, the default.
9142 * var button = new OO.ui.ButtonInputWidget( {
9143 * label: 'Input button',
9147 * $( 'body' ).append( button.$element );
9149 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#Button_inputs
9152 * @extends OO.ui.InputWidget
9153 * @mixins OO.ui.mixin.ButtonElement
9154 * @mixins OO.ui.mixin.IconElement
9155 * @mixins OO.ui.mixin.IndicatorElement
9156 * @mixins OO.ui.mixin.LabelElement
9157 * @mixins OO.ui.mixin.TitledElement
9160 * @param {Object} [config] Configuration options
9161 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
9162 * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
9163 * Widgets configured to be an `<input>` do not support {@link #icon icons} and {@link #indicator indicators},
9164 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
9165 * be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
9167 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
9168 // Configuration initialization
9169 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
9171 // See InputWidget#reusePreInfuseDOM about config.$input
9172 if ( config
.$input
) {
9173 config
.$input
.empty();
9176 // Properties (must be set before parent constructor, which calls #setValue)
9177 this.useInputTag
= config
.useInputTag
;
9179 // Parent constructor
9180 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
9182 // Mixin constructors
9183 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
9184 OO
.ui
.mixin
.IconElement
.call( this, config
);
9185 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
9186 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9187 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
9190 if ( !config
.useInputTag
) {
9191 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
9193 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
9198 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
9199 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
9200 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
9201 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
9202 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
9203 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
9205 /* Static Properties */
9211 OO
.ui
.ButtonInputWidget
.static.tagName
= 'span';
9219 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
9221 type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ? config
.type
: 'button';
9222 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
9228 * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
9230 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
9231 * text, or `null` for no label
9233 * @return {OO.ui.Widget} The widget, for chaining
9235 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
9236 if ( typeof label
=== 'function' ) {
9237 label
= OO
.ui
.resolveMsg( label
);
9240 if ( this.useInputTag
) {
9241 // Discard non-plaintext labels
9242 if ( typeof label
!== 'string' ) {
9246 this.$input
.val( label
);
9249 return OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
9253 * Set the value of the input.
9255 * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
9256 * they do not support {@link #value values}.
9258 * @param {string} value New value
9260 * @return {OO.ui.Widget} The widget, for chaining
9262 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
9263 if ( !this.useInputTag
) {
9264 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
9272 OO
.ui
.ButtonInputWidget
.prototype.getInputId = function () {
9273 // Disable generating `<label>` elements for buttons. One would very rarely need additional label
9274 // for a button, and it's already a big clickable target, and it causes unexpected rendering.
9279 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
9280 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
9281 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
9282 * alignment. For more information, please see the [OOUI documentation on MediaWiki][1].
9284 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9287 * // An example of selected, unselected, and disabled checkbox inputs
9288 * var checkbox1=new OO.ui.CheckboxInputWidget( {
9292 * var checkbox2=new OO.ui.CheckboxInputWidget( {
9295 * var checkbox3=new OO.ui.CheckboxInputWidget( {
9299 * // Create a fieldset layout with fields for each checkbox.
9300 * var fieldset = new OO.ui.FieldsetLayout( {
9301 * label: 'Checkboxes'
9303 * fieldset.addItems( [
9304 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
9305 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
9306 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
9308 * $( 'body' ).append( fieldset.$element );
9310 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9313 * @extends OO.ui.InputWidget
9316 * @param {Object} [config] Configuration options
9317 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
9319 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
9320 // Configuration initialization
9321 config
= config
|| {};
9323 // Parent constructor
9324 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
9327 this.checkIcon
= new OO
.ui
.IconWidget( {
9329 classes
: [ 'oo-ui-checkboxInputWidget-checkIcon' ]
9334 .addClass( 'oo-ui-checkboxInputWidget' )
9335 // Required for pretty styling in WikimediaUI theme
9336 .append( this.checkIcon
.$element
);
9337 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
9342 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
9344 /* Static Properties */
9350 OO
.ui
.CheckboxInputWidget
.static.tagName
= 'span';
9352 /* Static Methods */
9357 OO
.ui
.CheckboxInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9358 var state
= OO
.ui
.CheckboxInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9359 state
.checked
= config
.$input
.prop( 'checked' );
9369 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
9370 return $( '<input>' ).attr( 'type', 'checkbox' );
9376 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
9378 if ( !this.isDisabled() ) {
9379 // Allow the stack to clear so the value will be updated
9380 setTimeout( function () {
9381 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
9387 * Set selection state of this checkbox.
9389 * @param {boolean} state `true` for selected
9391 * @return {OO.ui.Widget} The widget, for chaining
9393 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
9395 if ( this.selected
!== state
) {
9396 this.selected
= state
;
9397 this.$input
.prop( 'checked', this.selected
);
9398 this.emit( 'change', this.selected
);
9400 // The first time that the selection state is set (probably while constructing the widget),
9401 // remember it in defaultSelected. This property can be later used to check whether
9402 // the selection state of the input has been changed since it was created.
9403 if ( this.defaultSelected
=== undefined ) {
9404 this.defaultSelected
= this.selected
;
9405 this.$input
[ 0 ].defaultChecked
= this.defaultSelected
;
9411 * Check if this checkbox is selected.
9413 * @return {boolean} Checkbox is selected
9415 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
9416 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
9417 // it, and we won't know unless they're kind enough to trigger a 'change' event.
9418 var selected
= this.$input
.prop( 'checked' );
9419 if ( this.selected
!== selected
) {
9420 this.setSelected( selected
);
9422 return this.selected
;
9428 OO
.ui
.CheckboxInputWidget
.prototype.simulateLabelClick = function () {
9429 if ( !this.isDisabled() ) {
9430 this.$input
.click();
9438 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
9439 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
9440 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
9441 this.setSelected( state
.checked
);
9446 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
9447 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
9448 * of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9449 * more information about input widgets.
9451 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
9452 * are no options. If no `value` configuration option is provided, the first option is selected.
9453 * If you need a state representing no value (no option being selected), use a DropdownWidget.
9455 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
9458 * // Example: A DropdownInputWidget with three options
9459 * var dropdownInput = new OO.ui.DropdownInputWidget( {
9461 * { data: 'a', label: 'First' },
9462 * { data: 'b', label: 'Second'},
9463 * { data: 'c', label: 'Third' }
9466 * $( 'body' ).append( dropdownInput.$element );
9468 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9471 * @extends OO.ui.InputWidget
9474 * @param {Object} [config] Configuration options
9475 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9476 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
9477 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
9478 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
9479 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
9480 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
9482 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
9483 // Configuration initialization
9484 config
= config
|| {};
9486 // Properties (must be done before parent constructor which calls #setDisabled)
9487 this.dropdownWidget
= new OO
.ui
.DropdownWidget( $.extend(
9489 $overlay
: config
.$overlay
9493 // Set up the options before parent constructor, which uses them to validate config.value.
9494 // Use this instead of setOptions() because this.$input is not set up yet.
9495 this.setOptionsData( config
.options
|| [] );
9497 // Parent constructor
9498 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
9501 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
9505 .addClass( 'oo-ui-dropdownInputWidget' )
9506 .append( this.dropdownWidget
.$element
);
9507 this.setTabIndexedElement( this.dropdownWidget
.$tabIndexed
);
9512 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
9520 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
9521 return $( '<select>' );
9525 * Handles menu select events.
9528 * @param {OO.ui.MenuOptionWidget|null} item Selected menu item
9530 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
9531 this.setValue( item
? item
.getData() : '' );
9537 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
9539 value
= this.cleanUpValue( value
);
9540 // Only allow setting values that are actually present in the dropdown
9541 selected
= this.dropdownWidget
.getMenu().findItemFromData( value
) ||
9542 this.dropdownWidget
.getMenu().findFirstSelectableItem();
9543 this.dropdownWidget
.getMenu().selectItem( selected
);
9544 value
= selected
? selected
.getData() : '';
9545 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
9546 if ( this.optionsDirty
) {
9547 // We reached this from the constructor or from #setOptions.
9548 // We have to update the <select> element.
9549 this.updateOptionsInterface();
9557 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
9558 this.dropdownWidget
.setDisabled( state
);
9559 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9564 * Set the options available for this input.
9566 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9568 * @return {OO.ui.Widget} The widget, for chaining
9570 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
9571 var value
= this.getValue();
9573 this.setOptionsData( options
);
9575 // Re-set the value to update the visible interface (DropdownWidget and <select>).
9576 // In case the previous value is no longer an available option, select the first valid one.
9577 this.setValue( value
);
9583 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
9585 * This method may be called before the parent constructor, so various properties may not be
9588 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9591 OO
.ui
.DropdownInputWidget
.prototype.setOptionsData = function ( options
) {
9596 this.optionsDirty
= true;
9598 optionWidgets
= options
.map( function ( opt
) {
9601 if ( opt
.optgroup
!== undefined ) {
9602 return widget
.createMenuSectionOptionWidget( opt
.optgroup
);
9605 optValue
= widget
.cleanUpValue( opt
.data
);
9606 return widget
.createMenuOptionWidget(
9608 opt
.label
!== undefined ? opt
.label
: optValue
9613 this.dropdownWidget
.getMenu().clearItems().addItems( optionWidgets
);
9617 * Create a menu option widget.
9620 * @param {string} data Item data
9621 * @param {string} label Item label
9622 * @return {OO.ui.MenuOptionWidget} Option widget
9624 OO
.ui
.DropdownInputWidget
.prototype.createMenuOptionWidget = function ( data
, label
) {
9625 return new OO
.ui
.MenuOptionWidget( {
9632 * Create a menu section option widget.
9635 * @param {string} label Section item label
9636 * @return {OO.ui.MenuSectionOptionWidget} Menu section option widget
9638 OO
.ui
.DropdownInputWidget
.prototype.createMenuSectionOptionWidget = function ( label
) {
9639 return new OO
.ui
.MenuSectionOptionWidget( {
9645 * Update the user-visible interface to match the internal list of options and value.
9647 * This method must only be called after the parent constructor.
9651 OO
.ui
.DropdownInputWidget
.prototype.updateOptionsInterface = function () {
9653 $optionsContainer
= this.$input
,
9654 defaultValue
= this.defaultValue
,
9657 this.$input
.empty();
9659 this.dropdownWidget
.getMenu().getItems().forEach( function ( optionWidget
) {
9662 if ( !( optionWidget
instanceof OO
.ui
.MenuSectionOptionWidget
) ) {
9663 $optionNode
= $( '<option>' )
9664 .attr( 'value', optionWidget
.getData() )
9665 .text( optionWidget
.getLabel() );
9667 // Remember original selection state. This property can be later used to check whether
9668 // the selection state of the input has been changed since it was created.
9669 $optionNode
[ 0 ].defaultSelected
= ( optionWidget
.getData() === defaultValue
);
9671 $optionsContainer
.append( $optionNode
);
9673 $optionNode
= $( '<optgroup>' )
9674 .attr( 'label', optionWidget
.getLabel() );
9675 widget
.$input
.append( $optionNode
);
9676 $optionsContainer
= $optionNode
;
9680 this.optionsDirty
= false;
9686 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
9687 this.dropdownWidget
.focus();
9694 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
9695 this.dropdownWidget
.blur();
9700 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
9701 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
9702 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
9703 * please see the [OOUI documentation on MediaWiki][1].
9705 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9708 * // An example of selected, unselected, and disabled radio inputs
9709 * var radio1 = new OO.ui.RadioInputWidget( {
9713 * var radio2 = new OO.ui.RadioInputWidget( {
9716 * var radio3 = new OO.ui.RadioInputWidget( {
9720 * // Create a fieldset layout with fields for each radio button.
9721 * var fieldset = new OO.ui.FieldsetLayout( {
9722 * label: 'Radio inputs'
9724 * fieldset.addItems( [
9725 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
9726 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
9727 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
9729 * $( 'body' ).append( fieldset.$element );
9731 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9734 * @extends OO.ui.InputWidget
9737 * @param {Object} [config] Configuration options
9738 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
9740 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
9741 // Configuration initialization
9742 config
= config
|| {};
9744 // Parent constructor
9745 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
9749 .addClass( 'oo-ui-radioInputWidget' )
9750 // Required for pretty styling in WikimediaUI theme
9751 .append( $( '<span>' ) );
9752 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
9757 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
9759 /* Static Properties */
9765 OO
.ui
.RadioInputWidget
.static.tagName
= 'span';
9767 /* Static Methods */
9772 OO
.ui
.RadioInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9773 var state
= OO
.ui
.RadioInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9774 state
.checked
= config
.$input
.prop( 'checked' );
9784 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
9785 return $( '<input>' ).attr( 'type', 'radio' );
9791 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
9792 // RadioInputWidget doesn't track its state.
9796 * Set selection state of this radio button.
9798 * @param {boolean} state `true` for selected
9800 * @return {OO.ui.Widget} The widget, for chaining
9802 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
9803 // RadioInputWidget doesn't track its state.
9804 this.$input
.prop( 'checked', state
);
9805 // The first time that the selection state is set (probably while constructing the widget),
9806 // remember it in defaultSelected. This property can be later used to check whether
9807 // the selection state of the input has been changed since it was created.
9808 if ( this.defaultSelected
=== undefined ) {
9809 this.defaultSelected
= state
;
9810 this.$input
[ 0 ].defaultChecked
= this.defaultSelected
;
9816 * Check if this radio button is selected.
9818 * @return {boolean} Radio is selected
9820 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
9821 return this.$input
.prop( 'checked' );
9827 OO
.ui
.RadioInputWidget
.prototype.simulateLabelClick = function () {
9828 if ( !this.isDisabled() ) {
9829 this.$input
.click();
9837 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
9838 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
9839 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
9840 this.setSelected( state
.checked
);
9845 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
9846 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
9847 * of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9848 * more information about input widgets.
9850 * This and OO.ui.DropdownInputWidget support the same configuration options.
9853 * // Example: A RadioSelectInputWidget with three options
9854 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
9856 * { data: 'a', label: 'First' },
9857 * { data: 'b', label: 'Second'},
9858 * { data: 'c', label: 'Third' }
9861 * $( 'body' ).append( radioSelectInput.$element );
9863 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9866 * @extends OO.ui.InputWidget
9869 * @param {Object} [config] Configuration options
9870 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9872 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
9873 // Configuration initialization
9874 config
= config
|| {};
9876 // Properties (must be done before parent constructor which calls #setDisabled)
9877 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
9878 // Set up the options before parent constructor, which uses them to validate config.value.
9879 // Use this instead of setOptions() because this.$input is not set up yet
9880 this.setOptionsData( config
.options
|| [] );
9882 // Parent constructor
9883 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
9886 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
9890 .addClass( 'oo-ui-radioSelectInputWidget' )
9891 .append( this.radioSelectWidget
.$element
);
9892 this.setTabIndexedElement( this.radioSelectWidget
.$tabIndexed
);
9897 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
9899 /* Static Methods */
9904 OO
.ui
.RadioSelectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9905 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9906 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
9913 OO
.ui
.RadioSelectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
9914 config
= OO
.ui
.RadioSelectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
9915 // Cannot reuse the `<input type=radio>` set
9916 delete config
.$input
;
9926 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
9927 // Use this instead of <input type="hidden">, because hidden inputs do not have separate
9928 // 'value' and 'defaultValue' properties, and InputWidget wants to handle 'defaultValue'.
9929 return $( '<input>' ).addClass( 'oo-ui-element-hidden' );
9933 * Handles menu select events.
9936 * @param {OO.ui.RadioOptionWidget} item Selected menu item
9938 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
9939 this.setValue( item
.getData() );
9945 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
9947 value
= this.cleanUpValue( value
);
9948 // Only allow setting values that are actually present in the dropdown
9949 selected
= this.radioSelectWidget
.findItemFromData( value
) ||
9950 this.radioSelectWidget
.findFirstSelectableItem();
9951 this.radioSelectWidget
.selectItem( selected
);
9952 value
= selected
? selected
.getData() : '';
9953 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
9960 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
9961 this.radioSelectWidget
.setDisabled( state
);
9962 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9967 * Set the options available for this input.
9969 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9971 * @return {OO.ui.Widget} The widget, for chaining
9973 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
9974 var value
= this.getValue();
9976 this.setOptionsData( options
);
9978 // Re-set the value to update the visible interface (RadioSelectWidget).
9979 // In case the previous value is no longer an available option, select the first valid one.
9980 this.setValue( value
);
9986 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
9988 * This method may be called before the parent constructor, so various properties may not be
9991 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9994 OO
.ui
.RadioSelectInputWidget
.prototype.setOptionsData = function ( options
) {
9997 this.radioSelectWidget
9999 .addItems( options
.map( function ( opt
) {
10000 var optValue
= widget
.cleanUpValue( opt
.data
);
10001 return new OO
.ui
.RadioOptionWidget( {
10003 label
: opt
.label
!== undefined ? opt
.label
: optValue
10011 OO
.ui
.RadioSelectInputWidget
.prototype.focus = function () {
10012 this.radioSelectWidget
.focus();
10019 OO
.ui
.RadioSelectInputWidget
.prototype.blur = function () {
10020 this.radioSelectWidget
.blur();
10025 * CheckboxMultiselectInputWidget is a
10026 * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
10027 * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
10028 * HTML `<input type=checkbox>` tags. Please see the [OOUI documentation on MediaWiki][1] for
10029 * more information about input widgets.
10032 * // Example: A CheckboxMultiselectInputWidget with three options
10033 * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
10035 * { data: 'a', label: 'First' },
10036 * { data: 'b', label: 'Second'},
10037 * { data: 'c', label: 'Third' }
10040 * $( 'body' ).append( multiselectInput.$element );
10042 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
10045 * @extends OO.ui.InputWidget
10048 * @param {Object} [config] Configuration options
10049 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: …, disabled: … }`
10051 OO
.ui
.CheckboxMultiselectInputWidget
= function OoUiCheckboxMultiselectInputWidget( config
) {
10052 // Configuration initialization
10053 config
= config
|| {};
10055 // Properties (must be done before parent constructor which calls #setDisabled)
10056 this.checkboxMultiselectWidget
= new OO
.ui
.CheckboxMultiselectWidget();
10057 // Must be set before the #setOptionsData call below
10058 this.inputName
= config
.name
;
10059 // Set up the options before parent constructor, which uses them to validate config.value.
10060 // Use this instead of setOptions() because this.$input is not set up yet
10061 this.setOptionsData( config
.options
|| [] );
10063 // Parent constructor
10064 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.call( this, config
);
10067 this.checkboxMultiselectWidget
.connect( this, { select
: 'onCheckboxesSelect' } );
10071 .addClass( 'oo-ui-checkboxMultiselectInputWidget' )
10072 .append( this.checkboxMultiselectWidget
.$element
);
10073 // We don't use this.$input, but rather the CheckboxInputWidgets inside each option
10074 this.$input
.detach();
10079 OO
.inheritClass( OO
.ui
.CheckboxMultiselectInputWidget
, OO
.ui
.InputWidget
);
10081 /* Static Methods */
10086 OO
.ui
.CheckboxMultiselectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
10087 var state
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
10088 state
.value
= $( node
).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
10089 .toArray().map( function ( el
) { return el
.value
; } );
10096 OO
.ui
.CheckboxMultiselectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
10097 config
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
10098 // Cannot reuse the `<input type=checkbox>` set
10099 delete config
.$input
;
10109 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getInputElement = function () {
10111 return $( '<unused>' );
10115 * Handles CheckboxMultiselectWidget select events.
10119 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.onCheckboxesSelect = function () {
10120 this.setValue( this.checkboxMultiselectWidget
.findSelectedItemsData() );
10126 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getValue = function () {
10127 var value
= this.$element
.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
10128 .toArray().map( function ( el
) { return el
.value
; } );
10129 if ( this.value
!== value
) {
10130 this.setValue( value
);
10138 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setValue = function ( value
) {
10139 value
= this.cleanUpValue( value
);
10140 this.checkboxMultiselectWidget
.selectItemsByData( value
);
10141 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setValue
.call( this, value
);
10142 if ( this.optionsDirty
) {
10143 // We reached this from the constructor or from #setOptions.
10144 // We have to update the <select> element.
10145 this.updateOptionsInterface();
10151 * Clean up incoming value.
10153 * @param {string[]} value Original value
10154 * @return {string[]} Cleaned up value
10156 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.cleanUpValue = function ( value
) {
10157 var i
, singleValue
,
10159 if ( !Array
.isArray( value
) ) {
10162 for ( i
= 0; i
< value
.length
; i
++ ) {
10164 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( this, value
[ i
] );
10165 // Remove options that we don't have here
10166 if ( !this.checkboxMultiselectWidget
.findItemFromData( singleValue
) ) {
10169 cleanValue
.push( singleValue
);
10177 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setDisabled = function ( state
) {
10178 this.checkboxMultiselectWidget
.setDisabled( state
);
10179 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
10184 * Set the options available for this input.
10186 * @param {Object[]} options Array of menu options in the format `{ data: …, label: …, disabled: … }`
10188 * @return {OO.ui.Widget} The widget, for chaining
10190 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setOptions = function ( options
) {
10191 var value
= this.getValue();
10193 this.setOptionsData( options
);
10195 // Re-set the value to update the visible interface (CheckboxMultiselectWidget).
10196 // This will also get rid of any stale options that we just removed.
10197 this.setValue( value
);
10203 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
10205 * This method may be called before the parent constructor, so various properties may not be
10208 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10211 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setOptionsData = function ( options
) {
10214 this.optionsDirty
= true;
10216 this.checkboxMultiselectWidget
10218 .addItems( options
.map( function ( opt
) {
10219 var optValue
, item
, optDisabled
;
10221 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( widget
, opt
.data
);
10222 optDisabled
= opt
.disabled
!== undefined ? opt
.disabled
: false;
10223 item
= new OO
.ui
.CheckboxMultioptionWidget( {
10225 label
: opt
.label
!== undefined ? opt
.label
: optValue
,
10226 disabled
: optDisabled
10228 // Set the 'name' and 'value' for form submission
10229 item
.checkbox
.$input
.attr( 'name', widget
.inputName
);
10230 item
.checkbox
.setValue( optValue
);
10236 * Update the user-visible interface to match the internal list of options and value.
10238 * This method must only be called after the parent constructor.
10242 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.updateOptionsInterface = function () {
10243 var defaultValue
= this.defaultValue
;
10245 this.checkboxMultiselectWidget
.getItems().forEach( function ( item
) {
10246 // Remember original selection state. This property can be later used to check whether
10247 // the selection state of the input has been changed since it was created.
10248 var isDefault
= defaultValue
.indexOf( item
.getData() ) !== -1;
10249 item
.checkbox
.defaultSelected
= isDefault
;
10250 item
.checkbox
.$input
[ 0 ].defaultChecked
= isDefault
;
10253 this.optionsDirty
= false;
10259 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.focus = function () {
10260 this.checkboxMultiselectWidget
.focus();
10265 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
10266 * size of the field as well as its presentation. In addition, these widgets can be configured
10267 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
10268 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
10269 * which modifies incoming values rather than validating them.
10270 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
10272 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
10275 * // Example of a text input widget
10276 * var textInput = new OO.ui.TextInputWidget( {
10277 * value: 'Text input'
10279 * $( 'body' ).append( textInput.$element );
10281 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
10284 * @extends OO.ui.InputWidget
10285 * @mixins OO.ui.mixin.IconElement
10286 * @mixins OO.ui.mixin.IndicatorElement
10287 * @mixins OO.ui.mixin.PendingElement
10288 * @mixins OO.ui.mixin.LabelElement
10291 * @param {Object} [config] Configuration options
10292 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password'
10293 * 'email', 'url' or 'number'.
10294 * @cfg {string} [placeholder] Placeholder text
10295 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
10296 * instruct the browser to focus this widget.
10297 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
10298 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
10300 * For unfortunate historical reasons, this counts the number of UTF-16 code units rather than
10301 * Unicode codepoints, which means that codepoints outside the Basic Multilingual Plane (e.g.
10302 * many emojis) count as 2 characters each.
10303 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
10304 * the value or placeholder text: `'before'` or `'after'`
10305 * @cfg {boolean} [required=false] Mark the field as required with `true`. Implies `indicator: 'required'`.
10306 * Note that `false` & setting `indicator: 'required' will result in no indicator shown.
10307 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
10308 * @cfg {boolean} [spellcheck] Should the browser support spellcheck for this field (`undefined` means
10309 * leaving it up to the browser).
10310 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
10311 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
10312 * (the value must contain only numbers); when RegExp, a regular expression that must match the
10313 * value for it to be considered valid; when Function, a function receiving the value as parameter
10314 * that must return true, or promise resolving to true, for it to be considered valid.
10316 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
10317 // Configuration initialization
10318 config
= $.extend( {
10320 labelPosition
: 'after'
10323 // Parent constructor
10324 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
10326 // Mixin constructors
10327 OO
.ui
.mixin
.IconElement
.call( this, config
);
10328 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
10329 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
10330 OO
.ui
.mixin
.LabelElement
.call( this, config
);
10333 this.type
= this.getSaneType( config
);
10334 this.readOnly
= false;
10335 this.required
= false;
10336 this.validate
= null;
10337 this.styleHeight
= null;
10338 this.scrollWidth
= null;
10340 this.setValidation( config
.validate
);
10341 this.setLabelPosition( config
.labelPosition
);
10345 keypress
: this.onKeyPress
.bind( this ),
10346 blur
: this.onBlur
.bind( this ),
10347 focus
: this.onFocus
.bind( this )
10349 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
10350 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
10351 this.on( 'labelChange', this.updatePosition
.bind( this ) );
10352 this.on( 'change', OO
.ui
.debounce( this.onDebouncedChange
.bind( this ), 250 ) );
10356 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
10357 .append( this.$icon
, this.$indicator
);
10358 this.setReadOnly( !!config
.readOnly
);
10359 this.setRequired( !!config
.required
);
10360 if ( config
.placeholder
!== undefined ) {
10361 this.$input
.attr( 'placeholder', config
.placeholder
);
10363 if ( config
.maxLength
!== undefined ) {
10364 this.$input
.attr( 'maxlength', config
.maxLength
);
10366 if ( config
.autofocus
) {
10367 this.$input
.attr( 'autofocus', 'autofocus' );
10369 if ( config
.autocomplete
=== false ) {
10370 this.$input
.attr( 'autocomplete', 'off' );
10371 // Turning off autocompletion also disables "form caching" when the user navigates to a
10372 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
10374 beforeunload: function () {
10375 this.$input
.removeAttr( 'autocomplete' );
10377 pageshow: function () {
10378 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
10379 // whole page... it shouldn't hurt, though.
10380 this.$input
.attr( 'autocomplete', 'off' );
10384 if ( config
.spellcheck
!== undefined ) {
10385 this.$input
.attr( 'spellcheck', config
.spellcheck
? 'true' : 'false' );
10387 if ( this.label
) {
10388 this.isWaitingToBeAttached
= true;
10389 this.installParentChangeDetector();
10395 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
10396 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
10397 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
10398 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
10399 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
10401 /* Static Properties */
10403 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
10411 * An `enter` event is emitted when the user presses 'enter' inside the text box.
10419 * Handle icon mouse down events.
10422 * @param {jQuery.Event} e Mouse down event
10423 * @return {undefined/boolean} False to prevent default if event is handled
10425 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
10426 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
10433 * Handle indicator mouse down events.
10436 * @param {jQuery.Event} e Mouse down event
10437 * @return {undefined/boolean} False to prevent default if event is handled
10439 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
10440 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
10447 * Handle key press events.
10450 * @param {jQuery.Event} e Key press event
10451 * @fires enter If enter key is pressed
10453 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
10454 if ( e
.which
=== OO
.ui
.Keys
.ENTER
) {
10455 this.emit( 'enter', e
);
10460 * Handle blur events.
10463 * @param {jQuery.Event} e Blur event
10465 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
10466 this.setValidityFlag();
10470 * Handle focus events.
10473 * @param {jQuery.Event} e Focus event
10475 OO
.ui
.TextInputWidget
.prototype.onFocus = function () {
10476 if ( this.isWaitingToBeAttached
) {
10477 // If we've received focus, then we must be attached to the document, and if
10478 // isWaitingToBeAttached is still true, that means the handler never fired. Fire it now.
10479 this.onElementAttach();
10481 this.setValidityFlag( true );
10485 * Handle element attach events.
10488 * @param {jQuery.Event} e Element attach event
10490 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
10491 this.isWaitingToBeAttached
= false;
10492 // Any previously calculated size is now probably invalid if we reattached elsewhere
10493 this.valCache
= null;
10494 this.positionLabel();
10498 * Handle debounced change events.
10500 * @param {string} value
10503 OO
.ui
.TextInputWidget
.prototype.onDebouncedChange = function () {
10504 this.setValidityFlag();
10508 * Check if the input is {@link #readOnly read-only}.
10510 * @return {boolean}
10512 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
10513 return this.readOnly
;
10517 * Set the {@link #readOnly read-only} state of the input.
10519 * @param {boolean} state Make input read-only
10521 * @return {OO.ui.Widget} The widget, for chaining
10523 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
10524 this.readOnly
= !!state
;
10525 this.$input
.prop( 'readOnly', this.readOnly
);
10530 * Check if the input is {@link #required required}.
10532 * @return {boolean}
10534 OO
.ui
.TextInputWidget
.prototype.isRequired = function () {
10535 return this.required
;
10539 * Set the {@link #required required} state of the input.
10541 * @param {boolean} state Make input required
10543 * @return {OO.ui.Widget} The widget, for chaining
10545 OO
.ui
.TextInputWidget
.prototype.setRequired = function ( state
) {
10546 this.required
= !!state
;
10547 if ( this.required
) {
10549 .prop( 'required', true )
10550 .attr( 'aria-required', 'true' );
10551 if ( this.getIndicator() === null ) {
10552 this.setIndicator( 'required' );
10556 .prop( 'required', false )
10557 .removeAttr( 'aria-required' );
10558 if ( this.getIndicator() === 'required' ) {
10559 this.setIndicator( null );
10566 * Support function for making #onElementAttach work across browsers.
10568 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
10569 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
10571 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
10572 * first time that the element gets attached to the documented.
10574 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
10575 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
10576 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
10579 if ( MutationObserver
) {
10580 // The new way. If only it wasn't so ugly.
10582 if ( this.isElementAttached() ) {
10583 // Widget is attached already, do nothing. This breaks the functionality of this function when
10584 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
10585 // would require observation of the whole document, which would hurt performance of other,
10586 // more important code.
10590 // Find topmost node in the tree
10591 topmostNode
= this.$element
[ 0 ];
10592 while ( topmostNode
.parentNode
) {
10593 topmostNode
= topmostNode
.parentNode
;
10596 // We have no way to detect the $element being attached somewhere without observing the entire
10597 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
10598 // parent node of $element, and instead detect when $element is removed from it (and thus
10599 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
10600 // doesn't get attached, we end up back here and create the parent.
10602 mutationObserver
= new MutationObserver( function ( mutations
) {
10603 var i
, j
, removedNodes
;
10604 for ( i
= 0; i
< mutations
.length
; i
++ ) {
10605 removedNodes
= mutations
[ i
].removedNodes
;
10606 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
10607 if ( removedNodes
[ j
] === topmostNode
) {
10608 setTimeout( onRemove
, 0 );
10615 onRemove = function () {
10616 // If the node was attached somewhere else, report it
10617 if ( widget
.isElementAttached() ) {
10618 widget
.onElementAttach();
10620 mutationObserver
.disconnect();
10621 widget
.installParentChangeDetector();
10624 // Create a fake parent and observe it
10625 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
10626 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
10628 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
10629 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
10630 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
10638 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
10639 if ( this.getSaneType( config
) === 'number' ) {
10640 return $( '<input>' )
10641 .attr( 'step', 'any' )
10642 .attr( 'type', 'number' );
10644 return $( '<input>' ).attr( 'type', this.getSaneType( config
) );
10649 * Get sanitized value for 'type' for given config.
10651 * @param {Object} config Configuration options
10652 * @return {string|null}
10655 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
10656 var allowedTypes
= [
10663 return allowedTypes
.indexOf( config
.type
) !== -1 ? config
.type
: 'text';
10667 * Focus the input and select a specified range within the text.
10669 * @param {number} from Select from offset
10670 * @param {number} [to] Select to offset, defaults to from
10672 * @return {OO.ui.Widget} The widget, for chaining
10674 OO
.ui
.TextInputWidget
.prototype.selectRange = function ( from, to
) {
10675 var isBackwards
, start
, end
,
10676 input
= this.$input
[ 0 ];
10680 isBackwards
= to
< from;
10681 start
= isBackwards
? to
: from;
10682 end
= isBackwards
? from : to
;
10687 input
.setSelectionRange( start
, end
, isBackwards
? 'backward' : 'forward' );
10689 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
10690 // Rather than expensively check if the input is attached every time, just check
10691 // if it was the cause of an error being thrown. If not, rethrow the error.
10692 if ( this.getElementDocument().body
.contains( input
) ) {
10700 * Get an object describing the current selection range in a directional manner
10702 * @return {Object} Object containing 'from' and 'to' offsets
10704 OO
.ui
.TextInputWidget
.prototype.getRange = function () {
10705 var input
= this.$input
[ 0 ],
10706 start
= input
.selectionStart
,
10707 end
= input
.selectionEnd
,
10708 isBackwards
= input
.selectionDirection
=== 'backward';
10711 from: isBackwards
? end
: start
,
10712 to
: isBackwards
? start
: end
10717 * Get the length of the text input value.
10719 * This could differ from the length of #getValue if the
10720 * value gets filtered
10722 * @return {number} Input length
10724 OO
.ui
.TextInputWidget
.prototype.getInputLength = function () {
10725 return this.$input
[ 0 ].value
.length
;
10729 * Focus the input and select the entire text.
10732 * @return {OO.ui.Widget} The widget, for chaining
10734 OO
.ui
.TextInputWidget
.prototype.select = function () {
10735 return this.selectRange( 0, this.getInputLength() );
10739 * Focus the input and move the cursor to the start.
10742 * @return {OO.ui.Widget} The widget, for chaining
10744 OO
.ui
.TextInputWidget
.prototype.moveCursorToStart = function () {
10745 return this.selectRange( 0 );
10749 * Focus the input and move the cursor to the end.
10752 * @return {OO.ui.Widget} The widget, for chaining
10754 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
10755 return this.selectRange( this.getInputLength() );
10759 * Insert new content into the input.
10761 * @param {string} content Content to be inserted
10763 * @return {OO.ui.Widget} The widget, for chaining
10765 OO
.ui
.TextInputWidget
.prototype.insertContent = function ( content
) {
10767 range
= this.getRange(),
10768 value
= this.getValue();
10770 start
= Math
.min( range
.from, range
.to
);
10771 end
= Math
.max( range
.from, range
.to
);
10773 this.setValue( value
.slice( 0, start
) + content
+ value
.slice( end
) );
10774 this.selectRange( start
+ content
.length
);
10779 * Insert new content either side of a selection.
10781 * @param {string} pre Content to be inserted before the selection
10782 * @param {string} post Content to be inserted after the selection
10784 * @return {OO.ui.Widget} The widget, for chaining
10786 OO
.ui
.TextInputWidget
.prototype.encapsulateContent = function ( pre
, post
) {
10788 range
= this.getRange(),
10789 offset
= pre
.length
;
10791 start
= Math
.min( range
.from, range
.to
);
10792 end
= Math
.max( range
.from, range
.to
);
10794 this.selectRange( start
).insertContent( pre
);
10795 this.selectRange( offset
+ end
).insertContent( post
);
10797 this.selectRange( offset
+ start
, offset
+ end
);
10802 * Set the validation pattern.
10804 * The validation pattern is either a regular expression, a function, or the symbolic name of a
10805 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
10806 * value must contain only numbers).
10808 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
10809 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
10811 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
10812 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
10813 this.validate
= validate
;
10815 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
10820 * Sets the 'invalid' flag appropriately.
10822 * @param {boolean} [isValid] Optionally override validation result
10824 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
10826 setFlag = function ( valid
) {
10828 widget
.$input
.attr( 'aria-invalid', 'true' );
10830 widget
.$input
.removeAttr( 'aria-invalid' );
10832 widget
.setFlags( { invalid
: !valid
} );
10835 if ( isValid
!== undefined ) {
10836 setFlag( isValid
);
10838 this.getValidity().then( function () {
10847 * Get the validity of current value.
10849 * This method returns a promise that resolves if the value is valid and rejects if
10850 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
10852 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
10854 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
10857 function rejectOrResolve( valid
) {
10859 return $.Deferred().resolve().promise();
10861 return $.Deferred().reject().promise();
10865 // Check browser validity and reject if it is invalid
10867 this.$input
[ 0 ].checkValidity
!== undefined &&
10868 this.$input
[ 0 ].checkValidity() === false
10870 return rejectOrResolve( false );
10873 // Run our checks if the browser thinks the field is valid
10874 if ( this.validate
instanceof Function
) {
10875 result
= this.validate( this.getValue() );
10876 if ( result
&& typeof result
.promise
=== 'function' ) {
10877 return result
.promise().then( function ( valid
) {
10878 return rejectOrResolve( valid
);
10881 return rejectOrResolve( result
);
10884 return rejectOrResolve( this.getValue().match( this.validate
) );
10889 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
10891 * @param {string} labelPosition Label position, 'before' or 'after'
10893 * @return {OO.ui.Widget} The widget, for chaining
10895 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
10896 this.labelPosition
= labelPosition
;
10897 if ( this.label
) {
10898 // If there is no label and we only change the position, #updatePosition is a no-op,
10899 // but it takes really a lot of work to do nothing.
10900 this.updatePosition();
10906 * Update the position of the inline label.
10908 * This method is called by #setLabelPosition, and can also be called on its own if
10909 * something causes the label to be mispositioned.
10912 * @return {OO.ui.Widget} The widget, for chaining
10914 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
10915 var after
= this.labelPosition
=== 'after';
10918 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
10919 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
10921 this.valCache
= null;
10922 this.scrollWidth
= null;
10923 this.positionLabel();
10929 * Position the label by setting the correct padding on the input.
10933 * @return {OO.ui.Widget} The widget, for chaining
10935 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
10936 var after
, rtl
, property
, newCss
;
10938 if ( this.isWaitingToBeAttached
) {
10939 // #onElementAttach will be called soon, which calls this method
10944 'padding-right': '',
10948 if ( this.label
) {
10949 this.$element
.append( this.$label
);
10951 this.$label
.detach();
10952 // Clear old values if present
10953 this.$input
.css( newCss
);
10957 after
= this.labelPosition
=== 'after';
10958 rtl
= this.$element
.css( 'direction' ) === 'rtl';
10959 property
= after
=== rtl
? 'padding-left' : 'padding-right';
10961 newCss
[ property
] = this.$label
.outerWidth( true ) + ( after
? this.scrollWidth
: 0 );
10962 // We have to clear the padding on the other side, in case the element direction changed
10963 this.$input
.css( newCss
);
10970 * @extends OO.ui.TextInputWidget
10973 * @param {Object} [config] Configuration options
10975 OO
.ui
.SearchInputWidget
= function OoUiSearchInputWidget( config
) {
10976 config
= $.extend( {
10980 // Parent constructor
10981 OO
.ui
.SearchInputWidget
.parent
.call( this, config
);
10984 this.connect( this, {
10989 this.updateSearchIndicator();
10990 this.connect( this, {
10991 disable
: 'onDisable'
10997 OO
.inheritClass( OO
.ui
.SearchInputWidget
, OO
.ui
.TextInputWidget
);
11005 OO
.ui
.SearchInputWidget
.prototype.getSaneType = function () {
11012 OO
.ui
.SearchInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
11013 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
11014 // Clear the text field
11015 this.setValue( '' );
11022 * Update the 'clear' indicator displayed on type: 'search' text
11023 * fields, hiding it when the field is already empty or when it's not
11026 OO
.ui
.SearchInputWidget
.prototype.updateSearchIndicator = function () {
11027 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
11028 this.setIndicator( null );
11030 this.setIndicator( 'clear' );
11035 * Handle change events.
11039 OO
.ui
.SearchInputWidget
.prototype.onChange = function () {
11040 this.updateSearchIndicator();
11044 * Handle disable events.
11046 * @param {boolean} disabled Element is disabled
11049 OO
.ui
.SearchInputWidget
.prototype.onDisable = function () {
11050 this.updateSearchIndicator();
11056 OO
.ui
.SearchInputWidget
.prototype.setReadOnly = function ( state
) {
11057 OO
.ui
.SearchInputWidget
.parent
.prototype.setReadOnly
.call( this, state
);
11058 this.updateSearchIndicator();
11064 * @extends OO.ui.TextInputWidget
11067 * @param {Object} [config] Configuration options
11068 * @cfg {number} [rows] Number of visible lines in textarea. If used with `autosize`,
11069 * specifies minimum number of rows to display.
11070 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
11071 * Use the #maxRows config to specify a maximum number of displayed rows.
11072 * @cfg {number} [maxRows] Maximum number of rows to display when #autosize is set to true.
11073 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
11075 OO
.ui
.MultilineTextInputWidget
= function OoUiMultilineTextInputWidget( config
) {
11076 config
= $.extend( {
11079 // Parent constructor
11080 OO
.ui
.MultilineTextInputWidget
.parent
.call( this, config
);
11083 this.autosize
= !!config
.autosize
;
11084 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
11085 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
11087 // Clone for resizing
11088 if ( this.autosize
) {
11089 this.$clone
= this.$input
11091 .removeAttr( 'id' )
11092 .removeAttr( 'name' )
11093 .insertAfter( this.$input
)
11094 .attr( 'aria-hidden', 'true' )
11095 .addClass( 'oo-ui-element-hidden' );
11099 this.connect( this, {
11104 if ( config
.rows
) {
11105 this.$input
.attr( 'rows', config
.rows
);
11107 if ( this.autosize
) {
11108 this.$input
.addClass( 'oo-ui-textInputWidget-autosized' );
11109 this.isWaitingToBeAttached
= true;
11110 this.installParentChangeDetector();
11116 OO
.inheritClass( OO
.ui
.MultilineTextInputWidget
, OO
.ui
.TextInputWidget
);
11118 /* Static Methods */
11123 OO
.ui
.MultilineTextInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
11124 var state
= OO
.ui
.MultilineTextInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
11125 state
.scrollTop
= config
.$input
.scrollTop();
11134 OO
.ui
.MultilineTextInputWidget
.prototype.onElementAttach = function () {
11135 OO
.ui
.MultilineTextInputWidget
.parent
.prototype.onElementAttach
.call( this );
11140 * Handle change events.
11144 OO
.ui
.MultilineTextInputWidget
.prototype.onChange = function () {
11151 OO
.ui
.MultilineTextInputWidget
.prototype.updatePosition = function () {
11152 OO
.ui
.MultilineTextInputWidget
.parent
.prototype.updatePosition
.call( this );
11159 * Modify to emit 'enter' on Ctrl/Meta+Enter, instead of plain Enter
11161 OO
.ui
.MultilineTextInputWidget
.prototype.onKeyPress = function ( e
) {
11163 ( e
.which
=== OO
.ui
.Keys
.ENTER
&& ( e
.ctrlKey
|| e
.metaKey
) ) ||
11164 // Some platforms emit keycode 10 for ctrl+enter in a textarea
11167 this.emit( 'enter', e
);
11172 * Automatically adjust the size of the text input.
11174 * This only affects multiline inputs that are {@link #autosize autosized}.
11177 * @return {OO.ui.Widget} The widget, for chaining
11180 OO
.ui
.MultilineTextInputWidget
.prototype.adjustSize = function () {
11181 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
,
11182 idealHeight
, newHeight
, scrollWidth
, property
;
11184 if ( this.$input
.val() !== this.valCache
) {
11185 if ( this.autosize
) {
11187 .val( this.$input
.val() )
11188 .attr( 'rows', this.minRows
)
11189 // Set inline height property to 0 to measure scroll height
11190 .css( 'height', 0 );
11192 this.$clone
.removeClass( 'oo-ui-element-hidden' );
11194 this.valCache
= this.$input
.val();
11196 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
11198 // Remove inline height property to measure natural heights
11199 this.$clone
.css( 'height', '' );
11200 innerHeight
= this.$clone
.innerHeight();
11201 outerHeight
= this.$clone
.outerHeight();
11203 // Measure max rows height
11205 .attr( 'rows', this.maxRows
)
11206 .css( 'height', 'auto' )
11208 maxInnerHeight
= this.$clone
.innerHeight();
11210 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
11211 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
11212 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
11213 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
11215 this.$clone
.addClass( 'oo-ui-element-hidden' );
11217 // Only apply inline height when expansion beyond natural height is needed
11218 // Use the difference between the inner and outer height as a buffer
11219 newHeight
= idealHeight
> innerHeight
? idealHeight
+ ( outerHeight
- innerHeight
) : '';
11220 if ( newHeight
!== this.styleHeight
) {
11221 this.$input
.css( 'height', newHeight
);
11222 this.styleHeight
= newHeight
;
11223 this.emit( 'resize' );
11226 scrollWidth
= this.$input
[ 0 ].offsetWidth
- this.$input
[ 0 ].clientWidth
;
11227 if ( scrollWidth
!== this.scrollWidth
) {
11228 property
= this.$element
.css( 'direction' ) === 'rtl' ? 'left' : 'right';
11230 this.$label
.css( { right
: '', left
: '' } );
11231 this.$indicator
.css( { right
: '', left
: '' } );
11233 if ( scrollWidth
) {
11234 this.$indicator
.css( property
, scrollWidth
);
11235 if ( this.labelPosition
=== 'after' ) {
11236 this.$label
.css( property
, scrollWidth
);
11240 this.scrollWidth
= scrollWidth
;
11241 this.positionLabel();
11251 OO
.ui
.MultilineTextInputWidget
.prototype.getInputElement = function () {
11252 return $( '<textarea>' );
11256 * Check if the input automatically adjusts its size.
11258 * @return {boolean}
11260 OO
.ui
.MultilineTextInputWidget
.prototype.isAutosizing = function () {
11261 return !!this.autosize
;
11267 OO
.ui
.MultilineTextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
11268 OO
.ui
.MultilineTextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
11269 if ( state
.scrollTop
!== undefined ) {
11270 this.$input
.scrollTop( state
.scrollTop
);
11275 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
11276 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
11277 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
11279 * - by typing a value in the text input field. If the value exactly matches the value of a menu
11280 * option, that option will appear to be selected.
11281 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
11284 * After the user chooses an option, its `data` will be used as a new value for the widget.
11285 * A `label` also can be specified for each option: if given, it will be shown instead of the
11286 * `data` in the dropdown menu.
11288 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
11290 * For more information about menus and options, please see the [OOUI documentation on MediaWiki][1].
11293 * // Example: A ComboBoxInputWidget.
11294 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11295 * value: 'Option 1',
11297 * { data: 'Option 1' },
11298 * { data: 'Option 2' },
11299 * { data: 'Option 3' }
11302 * $( 'body' ).append( comboBox.$element );
11305 * // Example: A ComboBoxInputWidget with additional option labels.
11306 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11307 * value: 'Option 1',
11310 * data: 'Option 1',
11311 * label: 'Option One'
11314 * data: 'Option 2',
11315 * label: 'Option Two'
11318 * data: 'Option 3',
11319 * label: 'Option Three'
11323 * $( 'body' ).append( comboBox.$element );
11325 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
11328 * @extends OO.ui.TextInputWidget
11331 * @param {Object} [config] Configuration options
11332 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
11333 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
11334 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
11335 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
11336 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
11337 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11339 OO
.ui
.ComboBoxInputWidget
= function OoUiComboBoxInputWidget( config
) {
11340 // Configuration initialization
11341 config
= $.extend( {
11342 autocomplete
: false
11345 // ComboBoxInputWidget shouldn't support `multiline`
11346 config
.multiline
= false;
11348 // See InputWidget#reusePreInfuseDOM about `config.$input`
11349 if ( config
.$input
) {
11350 config
.$input
.removeAttr( 'list' );
11353 // Parent constructor
11354 OO
.ui
.ComboBoxInputWidget
.parent
.call( this, config
);
11357 this.$overlay
= ( config
.$overlay
=== true ? OO
.ui
.getDefaultOverlay() : config
.$overlay
) || this.$element
;
11358 this.dropdownButton
= new OO
.ui
.ButtonWidget( {
11359 classes
: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ],
11361 disabled
: this.disabled
11363 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend(
11367 $floatableContainer
: this.$element
,
11368 disabled
: this.isDisabled()
11374 this.connect( this, {
11375 change
: 'onInputChange',
11376 enter
: 'onInputEnter'
11378 this.dropdownButton
.connect( this, {
11379 click
: 'onDropdownButtonClick'
11381 this.menu
.connect( this, {
11382 choose
: 'onMenuChoose',
11383 add
: 'onMenuItemsChange',
11384 remove
: 'onMenuItemsChange',
11385 toggle
: 'onMenuToggle'
11389 this.$input
.attr( {
11391 'aria-owns': this.menu
.getElementId(),
11392 'aria-autocomplete': 'list'
11394 // Do not override options set via config.menu.items
11395 if ( config
.options
!== undefined ) {
11396 this.setOptions( config
.options
);
11398 this.$field
= $( '<div>' )
11399 .addClass( 'oo-ui-comboBoxInputWidget-field' )
11400 .append( this.$input
, this.dropdownButton
.$element
);
11402 .addClass( 'oo-ui-comboBoxInputWidget' )
11403 .append( this.$field
);
11404 this.$overlay
.append( this.menu
.$element
);
11405 this.onMenuItemsChange();
11410 OO
.inheritClass( OO
.ui
.ComboBoxInputWidget
, OO
.ui
.TextInputWidget
);
11415 * Get the combobox's menu.
11417 * @return {OO.ui.MenuSelectWidget} Menu widget
11419 OO
.ui
.ComboBoxInputWidget
.prototype.getMenu = function () {
11424 * Get the combobox's text input widget.
11426 * @return {OO.ui.TextInputWidget} Text input widget
11428 OO
.ui
.ComboBoxInputWidget
.prototype.getInput = function () {
11433 * Handle input change events.
11436 * @param {string} value New value
11438 OO
.ui
.ComboBoxInputWidget
.prototype.onInputChange = function ( value
) {
11439 var match
= this.menu
.findItemFromData( value
);
11441 this.menu
.selectItem( match
);
11442 if ( this.menu
.findHighlightedItem() ) {
11443 this.menu
.highlightItem( match
);
11446 if ( !this.isDisabled() ) {
11447 this.menu
.toggle( true );
11452 * Handle input enter events.
11456 OO
.ui
.ComboBoxInputWidget
.prototype.onInputEnter = function () {
11457 if ( !this.isDisabled() ) {
11458 this.menu
.toggle( false );
11463 * Handle button click events.
11467 OO
.ui
.ComboBoxInputWidget
.prototype.onDropdownButtonClick = function () {
11468 this.menu
.toggle();
11473 * Handle menu choose events.
11476 * @param {OO.ui.OptionWidget} item Chosen item
11478 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuChoose = function ( item
) {
11479 this.setValue( item
.getData() );
11483 * Handle menu item change events.
11487 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuItemsChange = function () {
11488 var match
= this.menu
.findItemFromData( this.getValue() );
11489 this.menu
.selectItem( match
);
11490 if ( this.menu
.findHighlightedItem() ) {
11491 this.menu
.highlightItem( match
);
11493 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu
.isEmpty() );
11497 * Handle menu toggle events.
11500 * @param {boolean} isVisible Open state of the menu
11502 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuToggle = function ( isVisible
) {
11503 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-open', isVisible
);
11509 OO
.ui
.ComboBoxInputWidget
.prototype.setDisabled = function ( disabled
) {
11511 OO
.ui
.ComboBoxInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
11513 if ( this.dropdownButton
) {
11514 this.dropdownButton
.setDisabled( this.isDisabled() );
11517 this.menu
.setDisabled( this.isDisabled() );
11524 * Set the options available for this input.
11526 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
11528 * @return {OO.ui.Widget} The widget, for chaining
11530 OO
.ui
.ComboBoxInputWidget
.prototype.setOptions = function ( options
) {
11533 .addItems( options
.map( function ( opt
) {
11534 return new OO
.ui
.MenuOptionWidget( {
11536 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
11544 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
11545 * which is a widget that is specified by reference before any optional configuration settings.
11547 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
11549 * - **left**: The label is placed before the field-widget and aligned with the left margin.
11550 * A left-alignment is used for forms with many fields.
11551 * - **right**: The label is placed before the field-widget and aligned to the right margin.
11552 * A right-alignment is used for long but familiar forms which users tab through,
11553 * verifying the current field with a quick glance at the label.
11554 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
11555 * that users fill out from top to bottom.
11556 * - **inline**: The label is placed after the field-widget and aligned to the left.
11557 * An inline-alignment is best used with checkboxes or radio buttons.
11559 * Help text can either be:
11561 * - accessed via a help icon that appears in the upper right corner of the rendered field layout, or
11562 * - shown as a subtle explanation below the label.
11564 * If the help text is brief, or is essential to always expose it, set `helpInline` to `true`. If it
11565 * is long or not essential, leave `helpInline` to its default, `false`.
11567 * Please see the [OOUI documentation on MediaWiki] [1] for examples and more information.
11569 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
11572 * @extends OO.ui.Layout
11573 * @mixins OO.ui.mixin.LabelElement
11574 * @mixins OO.ui.mixin.TitledElement
11577 * @param {OO.ui.Widget} fieldWidget Field widget
11578 * @param {Object} [config] Configuration options
11579 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top'
11581 * @cfg {Array} [errors] Error messages about the widget, which will be
11582 * displayed below the widget.
11583 * The array may contain strings or OO.ui.HtmlSnippet instances.
11584 * @cfg {Array} [notices] Notices about the widget, which will be displayed
11585 * below the widget.
11586 * The array may contain strings or OO.ui.HtmlSnippet instances.
11587 * These are more visible than `help` messages when `helpInline` is set, and so
11588 * might be good for transient messages.
11589 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified
11590 * and `helpInline` is `false`, a "help" icon will appear in the upper-right
11591 * corner of the rendered field; clicking it will display the text in a popup.
11592 * If `helpInline` is `true`, then a subtle description will be shown after the
11594 * @cfg {boolean} [helpInline=false] Whether or not the help should be inline,
11595 * or shown when the "help" icon is clicked.
11596 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if
11598 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11600 * @throws {Error} An error is thrown if no widget is specified
11602 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
11603 // Allow passing positional parameters inside the config object
11604 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
11605 config
= fieldWidget
;
11606 fieldWidget
= config
.fieldWidget
;
11609 // Make sure we have required constructor arguments
11610 if ( fieldWidget
=== undefined ) {
11611 throw new Error( 'Widget not found' );
11614 // Configuration initialization
11615 config
= $.extend( { align
: 'left', helpInline
: false }, config
);
11617 // Parent constructor
11618 OO
.ui
.FieldLayout
.parent
.call( this, config
);
11620 // Mixin constructors
11621 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, {
11622 $label
: $( '<label>' )
11624 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
11627 this.fieldWidget
= fieldWidget
;
11630 this.$field
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
11631 this.$messages
= $( '<ul>' );
11632 this.$header
= $( '<span>' );
11633 this.$body
= $( '<div>' );
11635 this.helpInline
= config
.helpInline
;
11638 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
11641 this.$help
= config
.help
?
11642 this.createHelpElement( config
.help
, config
.$overlay
) :
11644 if ( this.fieldWidget
.getInputId() ) {
11645 this.$label
.attr( 'for', this.fieldWidget
.getInputId() );
11646 if ( this.helpInline
) {
11647 this.$help
.attr( 'for', this.fieldWidget
.getInputId() );
11650 this.$label
.on( 'click', function () {
11651 this.fieldWidget
.simulateLabelClick();
11653 if ( this.helpInline
) {
11654 this.$help
.on( 'click', function () {
11655 this.fieldWidget
.simulateLabelClick();
11660 .addClass( 'oo-ui-fieldLayout' )
11661 .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget
.isDisabled() )
11662 .append( this.$body
);
11663 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
11664 this.$header
.addClass( 'oo-ui-fieldLayout-header' );
11665 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
11667 .addClass( 'oo-ui-fieldLayout-field' )
11668 .append( this.fieldWidget
.$element
);
11670 this.setErrors( config
.errors
|| [] );
11671 this.setNotices( config
.notices
|| [] );
11672 this.setAlignment( config
.align
);
11673 // Call this again to take into account the widget's accessKey
11674 this.updateTitle();
11679 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
11680 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
11681 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
11686 * Handle field disable events.
11689 * @param {boolean} value Field is disabled
11691 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
11692 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
11696 * Get the widget contained by the field.
11698 * @return {OO.ui.Widget} Field widget
11700 OO
.ui
.FieldLayout
.prototype.getField = function () {
11701 return this.fieldWidget
;
11705 * Return `true` if the given field widget can be used with `'inline'` alignment (see
11706 * #setAlignment). Return `false` if it can't or if this can't be determined.
11708 * @return {boolean}
11710 OO
.ui
.FieldLayout
.prototype.isFieldInline = function () {
11711 // This is very simplistic, but should be good enough.
11712 return this.getField().$element
.prop( 'tagName' ).toLowerCase() === 'span';
11717 * @param {string} kind 'error' or 'notice'
11718 * @param {string|OO.ui.HtmlSnippet} text
11721 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
11722 var $listItem
, $icon
, message
;
11723 $listItem
= $( '<li>' );
11724 if ( kind
=== 'error' ) {
11725 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
11726 $listItem
.attr( 'role', 'alert' );
11727 } else if ( kind
=== 'notice' ) {
11728 $icon
= new OO
.ui
.IconWidget( { icon
: 'notice' } ).$element
;
11732 message
= new OO
.ui
.LabelWidget( { label
: text
} );
11734 .append( $icon
, message
.$element
)
11735 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
11740 * Set the field alignment mode.
11743 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
11745 * @return {OO.ui.BookletLayout} The layout, for chaining
11747 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
11748 if ( value
!== this.align
) {
11749 // Default to 'left'
11750 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
11754 if ( value
=== 'inline' && !this.isFieldInline() ) {
11757 // Reorder elements
11759 if ( this.helpInline
) {
11760 if ( value
=== 'top' ) {
11761 this.$header
.append( this.$label
);
11762 this.$body
.append( this.$header
, this.$field
, this.$help
);
11763 } else if ( value
=== 'inline' ) {
11764 this.$header
.append( this.$label
, this.$help
);
11765 this.$body
.append( this.$field
, this.$header
);
11767 this.$header
.append( this.$label
, this.$help
);
11768 this.$body
.append( this.$header
, this.$field
);
11771 if ( value
=== 'top' ) {
11772 this.$header
.append( this.$help
, this.$label
);
11773 this.$body
.append( this.$header
, this.$field
);
11774 } else if ( value
=== 'inline' ) {
11775 this.$header
.append( this.$help
, this.$label
);
11776 this.$body
.append( this.$field
, this.$header
);
11778 this.$header
.append( this.$label
);
11779 this.$body
.append( this.$header
, this.$help
, this.$field
);
11782 // Set classes. The following classes can be used here:
11783 // * oo-ui-fieldLayout-align-left
11784 // * oo-ui-fieldLayout-align-right
11785 // * oo-ui-fieldLayout-align-top
11786 // * oo-ui-fieldLayout-align-inline
11787 if ( this.align
) {
11788 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
11790 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
11791 this.align
= value
;
11798 * Set the list of error messages.
11800 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
11801 * The array may contain strings or OO.ui.HtmlSnippet instances.
11803 * @return {OO.ui.BookletLayout} The layout, for chaining
11805 OO
.ui
.FieldLayout
.prototype.setErrors = function ( errors
) {
11806 this.errors
= errors
.slice();
11807 this.updateMessages();
11812 * Set the list of notice messages.
11814 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
11815 * The array may contain strings or OO.ui.HtmlSnippet instances.
11817 * @return {OO.ui.BookletLayout} The layout, for chaining
11819 OO
.ui
.FieldLayout
.prototype.setNotices = function ( notices
) {
11820 this.notices
= notices
.slice();
11821 this.updateMessages();
11826 * Update the rendering of error and notice messages.
11830 OO
.ui
.FieldLayout
.prototype.updateMessages = function () {
11832 this.$messages
.empty();
11834 if ( this.errors
.length
|| this.notices
.length
) {
11835 this.$body
.after( this.$messages
);
11837 this.$messages
.remove();
11841 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
11842 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
11844 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
11845 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
11850 * Include information about the widget's accessKey in our title. TitledElement calls this method.
11851 * (This is a bit of a hack.)
11854 * @param {string} title Tooltip label for 'title' attribute
11857 OO
.ui
.FieldLayout
.prototype.formatTitleWithAccessKey = function ( title
) {
11858 if ( this.fieldWidget
&& this.fieldWidget
.formatTitleWithAccessKey
) {
11859 return this.fieldWidget
.formatTitleWithAccessKey( title
);
11865 * Creates and returns the help element. Also sets the `aria-describedby`
11866 * attribute on the main element of the `fieldWidget`.
11869 * @param {string|OO.ui.HtmlSnippet} [help] Help text.
11870 * @param {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup.
11871 * @return {jQuery} The element that should become `this.$help`.
11873 OO
.ui
.FieldLayout
.prototype.createHelpElement = function ( help
, $overlay
) {
11874 var helpId
, helpWidget
;
11876 if ( this.helpInline
) {
11877 helpWidget
= new OO
.ui
.LabelWidget( {
11879 classes
: [ 'oo-ui-inline-help' ]
11882 helpId
= helpWidget
.getElementId();
11884 helpWidget
= new OO
.ui
.PopupButtonWidget( {
11885 $overlay
: $overlay
,
11889 classes
: [ 'oo-ui-fieldLayout-help' ],
11892 label
: OO
.ui
.msg( 'ooui-field-help' ),
11893 invisibleLabel
: true
11895 if ( help
instanceof OO
.ui
.HtmlSnippet
) {
11896 helpWidget
.getPopup().$body
.html( help
.toString() );
11898 helpWidget
.getPopup().$body
.text( help
);
11901 helpId
= helpWidget
.getPopup().getBodyId();
11904 // Set the 'aria-describedby' attribute on the fieldWidget
11905 // Preference given to an input or a button
11907 this.fieldWidget
.$input
||
11908 this.fieldWidget
.$button
||
11909 this.fieldWidget
.$element
11910 ).attr( 'aria-describedby', helpId
);
11912 return helpWidget
.$element
;
11916 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
11917 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
11918 * is required and is specified before any optional configuration settings.
11920 * Labels can be aligned in one of four ways:
11922 * - **left**: The label is placed before the field-widget and aligned with the left margin.
11923 * A left-alignment is used for forms with many fields.
11924 * - **right**: The label is placed before the field-widget and aligned to the right margin.
11925 * A right-alignment is used for long but familiar forms which users tab through,
11926 * verifying the current field with a quick glance at the label.
11927 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
11928 * that users fill out from top to bottom.
11929 * - **inline**: The label is placed after the field-widget and aligned to the left.
11930 * An inline-alignment is best used with checkboxes or radio buttons.
11932 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
11933 * text is specified.
11936 * // Example of an ActionFieldLayout
11937 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
11938 * new OO.ui.TextInputWidget( {
11939 * placeholder: 'Field widget'
11941 * new OO.ui.ButtonWidget( {
11945 * label: 'An ActionFieldLayout. This label is aligned top',
11947 * help: 'This is help text'
11951 * $( 'body' ).append( actionFieldLayout.$element );
11954 * @extends OO.ui.FieldLayout
11957 * @param {OO.ui.Widget} fieldWidget Field widget
11958 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
11959 * @param {Object} config
11961 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
11962 // Allow passing positional parameters inside the config object
11963 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
11964 config
= fieldWidget
;
11965 fieldWidget
= config
.fieldWidget
;
11966 buttonWidget
= config
.buttonWidget
;
11969 // Parent constructor
11970 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
11973 this.buttonWidget
= buttonWidget
;
11974 this.$button
= $( '<span>' );
11975 this.$input
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
11979 .addClass( 'oo-ui-actionFieldLayout' );
11981 .addClass( 'oo-ui-actionFieldLayout-button' )
11982 .append( this.buttonWidget
.$element
);
11984 .addClass( 'oo-ui-actionFieldLayout-input' )
11985 .append( this.fieldWidget
.$element
);
11987 .append( this.$input
, this.$button
);
11992 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
11995 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
11996 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
11997 * configured with a label as well. For more information and examples,
11998 * please see the [OOUI documentation on MediaWiki][1].
12001 * // Example of a fieldset layout
12002 * var input1 = new OO.ui.TextInputWidget( {
12003 * placeholder: 'A text input field'
12006 * var input2 = new OO.ui.TextInputWidget( {
12007 * placeholder: 'A text input field'
12010 * var fieldset = new OO.ui.FieldsetLayout( {
12011 * label: 'Example of a fieldset layout'
12014 * fieldset.addItems( [
12015 * new OO.ui.FieldLayout( input1, {
12016 * label: 'Field One'
12018 * new OO.ui.FieldLayout( input2, {
12019 * label: 'Field Two'
12022 * $( 'body' ).append( fieldset.$element );
12024 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
12027 * @extends OO.ui.Layout
12028 * @mixins OO.ui.mixin.IconElement
12029 * @mixins OO.ui.mixin.LabelElement
12030 * @mixins OO.ui.mixin.GroupElement
12033 * @param {Object} [config] Configuration options
12034 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
12035 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
12036 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
12037 * For important messages, you are advised to use `notices`, as they are always shown.
12038 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
12039 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
12041 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
12042 // Configuration initialization
12043 config
= config
|| {};
12045 // Parent constructor
12046 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
12048 // Mixin constructors
12049 OO
.ui
.mixin
.IconElement
.call( this, config
);
12050 OO
.ui
.mixin
.LabelElement
.call( this, config
);
12051 OO
.ui
.mixin
.GroupElement
.call( this, config
);
12054 this.$header
= $( '<legend>' );
12055 if ( config
.help
) {
12056 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
12057 $overlay
: config
.$overlay
,
12061 classes
: [ 'oo-ui-fieldsetLayout-help' ],
12064 label
: OO
.ui
.msg( 'ooui-field-help' ),
12065 invisibleLabel
: true
12067 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
12068 this.popupButtonWidget
.getPopup().$body
.html( config
.help
.toString() );
12070 this.popupButtonWidget
.getPopup().$body
.text( config
.help
);
12072 this.$help
= this.popupButtonWidget
.$element
;
12074 this.$help
= $( [] );
12079 .addClass( 'oo-ui-fieldsetLayout-header' )
12080 .append( this.$icon
, this.$label
, this.$help
);
12081 this.$group
.addClass( 'oo-ui-fieldsetLayout-group' );
12083 .addClass( 'oo-ui-fieldsetLayout' )
12084 .prepend( this.$header
, this.$group
);
12085 if ( Array
.isArray( config
.items
) ) {
12086 this.addItems( config
.items
);
12092 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
12093 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
12094 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
12095 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
12097 /* Static Properties */
12103 OO
.ui
.FieldsetLayout
.static.tagName
= 'fieldset';
12106 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
12107 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
12108 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
12109 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
12111 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
12112 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
12113 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
12114 * some fancier controls. Some controls have both regular and InputWidget variants, for example
12115 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
12116 * often have simplified APIs to match the capabilities of HTML forms.
12117 * See the [OOUI documentation on MediaWiki] [2] for more information about InputWidgets.
12119 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Forms
12120 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
12123 * // Example of a form layout that wraps a fieldset layout
12124 * var input1 = new OO.ui.TextInputWidget( {
12125 * placeholder: 'Username'
12127 * var input2 = new OO.ui.TextInputWidget( {
12128 * placeholder: 'Password',
12131 * var submit = new OO.ui.ButtonInputWidget( {
12135 * var fieldset = new OO.ui.FieldsetLayout( {
12136 * label: 'A form layout'
12138 * fieldset.addItems( [
12139 * new OO.ui.FieldLayout( input1, {
12140 * label: 'Username',
12143 * new OO.ui.FieldLayout( input2, {
12144 * label: 'Password',
12147 * new OO.ui.FieldLayout( submit )
12149 * var form = new OO.ui.FormLayout( {
12150 * items: [ fieldset ],
12151 * action: '/api/formhandler',
12154 * $( 'body' ).append( form.$element );
12157 * @extends OO.ui.Layout
12158 * @mixins OO.ui.mixin.GroupElement
12161 * @param {Object} [config] Configuration options
12162 * @cfg {string} [method] HTML form `method` attribute
12163 * @cfg {string} [action] HTML form `action` attribute
12164 * @cfg {string} [enctype] HTML form `enctype` attribute
12165 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
12167 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
12170 // Configuration initialization
12171 config
= config
|| {};
12173 // Parent constructor
12174 OO
.ui
.FormLayout
.parent
.call( this, config
);
12176 // Mixin constructors
12177 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
12180 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
12182 // Make sure the action is safe
12183 action
= config
.action
;
12184 if ( action
!== undefined && !OO
.ui
.isSafeUrl( action
) ) {
12185 action
= './' + action
;
12190 .addClass( 'oo-ui-formLayout' )
12192 method
: config
.method
,
12194 enctype
: config
.enctype
12196 if ( Array
.isArray( config
.items
) ) {
12197 this.addItems( config
.items
);
12203 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
12204 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
12209 * A 'submit' event is emitted when the form is submitted.
12214 /* Static Properties */
12220 OO
.ui
.FormLayout
.static.tagName
= 'form';
12225 * Handle form submit events.
12228 * @param {jQuery.Event} e Submit event
12230 * @return {OO.ui.FormLayout} The layout, for chaining
12232 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
12233 if ( this.emit( 'submit' ) ) {
12239 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
12240 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
12243 * // Example of a panel layout
12244 * var panel = new OO.ui.PanelLayout( {
12248 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
12250 * $( 'body' ).append( panel.$element );
12253 * @extends OO.ui.Layout
12256 * @param {Object} [config] Configuration options
12257 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
12258 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
12259 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
12260 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
12262 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
12263 // Configuration initialization
12264 config
= $.extend( {
12271 // Parent constructor
12272 OO
.ui
.PanelLayout
.parent
.call( this, config
);
12275 this.$element
.addClass( 'oo-ui-panelLayout' );
12276 if ( config
.scrollable
) {
12277 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
12279 if ( config
.padded
) {
12280 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
12282 if ( config
.expanded
) {
12283 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
12285 if ( config
.framed
) {
12286 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
12292 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
12297 * Focus the panel layout
12299 * The default implementation just focuses the first focusable element in the panel
12301 OO
.ui
.PanelLayout
.prototype.focus = function () {
12302 OO
.ui
.findFocusable( this.$element
).focus();
12306 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
12307 * items), with small margins between them. Convenient when you need to put a number of block-level
12308 * widgets on a single line next to each other.
12310 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
12313 * // HorizontalLayout with a text input and a label
12314 * var layout = new OO.ui.HorizontalLayout( {
12316 * new OO.ui.LabelWidget( { label: 'Label' } ),
12317 * new OO.ui.TextInputWidget( { value: 'Text' } )
12320 * $( 'body' ).append( layout.$element );
12323 * @extends OO.ui.Layout
12324 * @mixins OO.ui.mixin.GroupElement
12327 * @param {Object} [config] Configuration options
12328 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
12330 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
12331 // Configuration initialization
12332 config
= config
|| {};
12334 // Parent constructor
12335 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
12337 // Mixin constructors
12338 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
12341 this.$element
.addClass( 'oo-ui-horizontalLayout' );
12342 if ( Array
.isArray( config
.items
) ) {
12343 this.addItems( config
.items
);
12349 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
12350 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);
12353 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
12354 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
12355 * (to adjust the value in increments) to allow the user to enter a number.
12358 * // Example: A NumberInputWidget.
12359 * var numberInput = new OO.ui.NumberInputWidget( {
12360 * label: 'NumberInputWidget',
12361 * input: { value: 5 },
12365 * $( 'body' ).append( numberInput.$element );
12368 * @extends OO.ui.TextInputWidget
12371 * @param {Object} [config] Configuration options
12372 * @cfg {Object} [minusButton] Configuration options to pass to the
12373 * {@link OO.ui.ButtonWidget decrementing button widget}.
12374 * @cfg {Object} [plusButton] Configuration options to pass to the
12375 * {@link OO.ui.ButtonWidget incrementing button widget}.
12376 * @cfg {number} [min=-Infinity] Minimum allowed value
12377 * @cfg {number} [max=Infinity] Maximum allowed value
12378 * @cfg {number|null} [step] If specified, the field only accepts values that are multiples of this.
12379 * @cfg {number} [buttonStep=step||1] Delta when using the buttons or up/down arrow keys.
12380 * Defaults to `step` if specified, otherwise `1`.
12381 * @cfg {number} [pageStep=10*buttonStep] Delta when using the page-up/page-down keys.
12382 * Defaults to 10 times `buttonStep`.
12383 * @cfg {boolean} [showButtons=true] Whether to show the plus and minus buttons.
12385 OO
.ui
.NumberInputWidget
= function OoUiNumberInputWidget( config
) {
12386 var $field
= $( '<div>' )
12387 .addClass( 'oo-ui-numberInputWidget-field' );
12389 // Configuration initialization
12390 config
= $.extend( {
12396 // For backward compatibility
12397 $.extend( config
, config
.input
);
12400 // Parent constructor
12401 OO
.ui
.NumberInputWidget
.parent
.call( this, $.extend( config
, {
12405 if ( config
.showButtons
) {
12406 this.minusButton
= new OO
.ui
.ButtonWidget( $.extend(
12408 disabled
: this.isDisabled(),
12410 classes
: [ 'oo-ui-numberInputWidget-minusButton' ],
12415 this.minusButton
.$element
.attr( 'aria-hidden', 'true' );
12416 this.plusButton
= new OO
.ui
.ButtonWidget( $.extend(
12418 disabled
: this.isDisabled(),
12420 classes
: [ 'oo-ui-numberInputWidget-plusButton' ],
12425 this.plusButton
.$element
.attr( 'aria-hidden', 'true' );
12430 keydown
: this.onKeyDown
.bind( this ),
12431 'wheel mousewheel DOMMouseScroll': this.onWheel
.bind( this )
12433 if ( config
.showButtons
) {
12434 this.plusButton
.connect( this, {
12435 click
: [ 'onButtonClick', +1 ]
12437 this.minusButton
.connect( this, {
12438 click
: [ 'onButtonClick', -1 ]
12443 $field
.append( this.$input
);
12444 if ( config
.showButtons
) {
12446 .prepend( this.minusButton
.$element
)
12447 .append( this.plusButton
.$element
);
12451 if ( config
.allowInteger
|| config
.isInteger
) {
12452 // Backward compatibility
12455 this.setRange( config
.min
, config
.max
);
12456 this.setStep( config
.buttonStep
, config
.pageStep
, config
.step
);
12457 // Set the validation method after we set step and range
12458 // so that it doesn't immediately call setValidityFlag
12459 this.setValidation( this.validateNumber
.bind( this ) );
12462 .addClass( 'oo-ui-numberInputWidget' )
12463 .toggleClass( 'oo-ui-numberInputWidget-buttoned', config
.showButtons
)
12469 OO
.inheritClass( OO
.ui
.NumberInputWidget
, OO
.ui
.TextInputWidget
);
12473 // Backward compatibility
12474 OO
.ui
.NumberInputWidget
.prototype.setAllowInteger = function ( flag
) {
12475 this.setStep( flag
? 1 : null );
12477 // Backward compatibility
12478 OO
.ui
.NumberInputWidget
.prototype.setIsInteger
= OO
.ui
.NumberInputWidget
.prototype.setAllowInteger
;
12480 // Backward compatibility
12481 OO
.ui
.NumberInputWidget
.prototype.getAllowInteger = function () {
12482 return this.step
=== 1;
12484 // Backward compatibility
12485 OO
.ui
.NumberInputWidget
.prototype.getIsInteger
= OO
.ui
.NumberInputWidget
.prototype.getAllowInteger
;
12488 * Set the range of allowed values
12490 * @param {number} min Minimum allowed value
12491 * @param {number} max Maximum allowed value
12493 OO
.ui
.NumberInputWidget
.prototype.setRange = function ( min
, max
) {
12495 throw new Error( 'Minimum (' + min
+ ') must not be greater than maximum (' + max
+ ')' );
12499 this.$input
.attr( 'min', this.min
);
12500 this.$input
.attr( 'max', this.max
);
12501 this.setValidityFlag();
12505 * Get the current range
12507 * @return {number[]} Minimum and maximum values
12509 OO
.ui
.NumberInputWidget
.prototype.getRange = function () {
12510 return [ this.min
, this.max
];
12514 * Set the stepping deltas
12516 * @param {number} [buttonStep=step||1] Delta when using the buttons or up/down arrow keys.
12517 * Defaults to `step` if specified, otherwise `1`.
12518 * @param {number} [pageStep=10*buttonStep] Delta when using the page-up/page-down keys.
12519 * Defaults to 10 times `buttonStep`.
12520 * @param {number|null} [step] If specified, the field only accepts values that are multiples of this.
12522 OO
.ui
.NumberInputWidget
.prototype.setStep = function ( buttonStep
, pageStep
, step
) {
12523 if ( buttonStep
=== undefined ) {
12524 buttonStep
= step
|| 1;
12526 if ( pageStep
=== undefined ) {
12527 pageStep
= 10 * buttonStep
;
12529 if ( step
!== null && step
<= 0 ) {
12530 throw new Error( 'Step value, if given, must be positive' );
12532 if ( buttonStep
<= 0 ) {
12533 throw new Error( 'Button step value must be positive' );
12535 if ( pageStep
<= 0 ) {
12536 throw new Error( 'Page step value must be positive' );
12539 this.buttonStep
= buttonStep
;
12540 this.pageStep
= pageStep
;
12541 this.$input
.attr( 'step', this.step
|| 'any' );
12542 this.setValidityFlag();
12548 OO
.ui
.NumberInputWidget
.prototype.setValue = function ( value
) {
12549 if ( value
=== '' ) {
12550 // Some browsers allow a value in the input even if there isn't one reported by $input.val()
12551 // so here we make sure an 'empty' value is actually displayed as such.
12552 this.$input
.val( '' );
12554 return OO
.ui
.NumberInputWidget
.parent
.prototype.setValue
.call( this, value
);
12558 * Get the current stepping values
12560 * @return {number[]} Button step, page step, and validity step
12562 OO
.ui
.NumberInputWidget
.prototype.getStep = function () {
12563 return [ this.buttonStep
, this.pageStep
, this.step
];
12567 * Get the current value of the widget as a number
12569 * @return {number} May be NaN, or an invalid number
12571 OO
.ui
.NumberInputWidget
.prototype.getNumericValue = function () {
12572 return +this.getValue();
12576 * Adjust the value of the widget
12578 * @param {number} delta Adjustment amount
12580 OO
.ui
.NumberInputWidget
.prototype.adjustValue = function ( delta
) {
12581 var n
, v
= this.getNumericValue();
12584 if ( isNaN( delta
) || !isFinite( delta
) ) {
12585 throw new Error( 'Delta must be a finite number' );
12588 if ( isNaN( v
) ) {
12592 n
= Math
.max( Math
.min( n
, this.max
), this.min
);
12594 n
= Math
.round( n
/ this.step
) * this.step
;
12599 this.setValue( n
);
12606 * @param {string} value Field value
12607 * @return {boolean}
12609 OO
.ui
.NumberInputWidget
.prototype.validateNumber = function ( value
) {
12611 if ( value
=== '' ) {
12612 return !this.isRequired();
12615 if ( isNaN( n
) || !isFinite( n
) ) {
12619 if ( this.step
&& Math
.floor( n
/ this.step
) !== n
/ this.step
) {
12623 if ( n
< this.min
|| n
> this.max
) {
12631 * Handle mouse click events.
12634 * @param {number} dir +1 or -1
12636 OO
.ui
.NumberInputWidget
.prototype.onButtonClick = function ( dir
) {
12637 this.adjustValue( dir
* this.buttonStep
);
12641 * Handle mouse wheel events.
12644 * @param {jQuery.Event} event
12645 * @return {undefined/boolean} False to prevent default if event is handled
12647 OO
.ui
.NumberInputWidget
.prototype.onWheel = function ( event
) {
12650 if ( !this.isDisabled() && this.$input
.is( ':focus' ) ) {
12651 // Standard 'wheel' event
12652 if ( event
.originalEvent
.deltaMode
!== undefined ) {
12653 this.sawWheelEvent
= true;
12655 if ( event
.originalEvent
.deltaY
) {
12656 delta
= -event
.originalEvent
.deltaY
;
12657 } else if ( event
.originalEvent
.deltaX
) {
12658 delta
= event
.originalEvent
.deltaX
;
12661 // Non-standard events
12662 if ( !this.sawWheelEvent
) {
12663 if ( event
.originalEvent
.wheelDeltaX
) {
12664 delta
= -event
.originalEvent
.wheelDeltaX
;
12665 } else if ( event
.originalEvent
.wheelDeltaY
) {
12666 delta
= event
.originalEvent
.wheelDeltaY
;
12667 } else if ( event
.originalEvent
.wheelDelta
) {
12668 delta
= event
.originalEvent
.wheelDelta
;
12669 } else if ( event
.originalEvent
.detail
) {
12670 delta
= -event
.originalEvent
.detail
;
12675 delta
= delta
< 0 ? -1 : 1;
12676 this.adjustValue( delta
* this.buttonStep
);
12684 * Handle key down events.
12687 * @param {jQuery.Event} e Key down event
12688 * @return {undefined/boolean} False to prevent default if event is handled
12690 OO
.ui
.NumberInputWidget
.prototype.onKeyDown = function ( e
) {
12691 if ( !this.isDisabled() ) {
12692 switch ( e
.which
) {
12693 case OO
.ui
.Keys
.UP
:
12694 this.adjustValue( this.buttonStep
);
12696 case OO
.ui
.Keys
.DOWN
:
12697 this.adjustValue( -this.buttonStep
);
12699 case OO
.ui
.Keys
.PAGEUP
:
12700 this.adjustValue( this.pageStep
);
12702 case OO
.ui
.Keys
.PAGEDOWN
:
12703 this.adjustValue( -this.pageStep
);
12712 OO
.ui
.NumberInputWidget
.prototype.setDisabled = function ( disabled
) {
12714 OO
.ui
.NumberInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
12716 if ( this.minusButton
) {
12717 this.minusButton
.setDisabled( this.isDisabled() );
12719 if ( this.plusButton
) {
12720 this.plusButton
.setDisabled( this.isDisabled() );
12728 //# sourceMappingURL=oojs-ui-core.js.map.json