3 * https://www.mediawiki.org/wiki/OOUI
5 * Copyright 2011–2019 OOUI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: 2019-03-20T23:07:02Z
16 * Namespace for all classes, static methods and static properties.
48 * Constants for MouseEvent.which
52 OO
.ui
.MouseButtons
= {
65 * Generate a unique ID for element
69 OO
.ui
.generateElementId = function () {
71 return 'ooui-' + OO
.ui
.elementId
;
75 * Check if an element is focusable.
76 * Inspired by :focusable in jQueryUI v1.11.4 - 2015-04-14
78 * @param {jQuery} $element Element to test
79 * @return {boolean} Element is focusable
81 OO
.ui
.isFocusableElement = function ( $element
) {
83 element
= $element
[ 0 ];
85 // Anything disabled is not focusable
86 if ( element
.disabled
) {
90 // Check if the element is visible
92 // This is quicker than calling $element.is( ':visible' )
93 $.expr
.pseudos
.visible( element
) &&
94 // Check that all parents are visible
95 !$element
.parents().addBack().filter( function () {
96 return $.css( this, 'visibility' ) === 'hidden';
102 // Check if the element is ContentEditable, which is the string 'true'
103 if ( element
.contentEditable
=== 'true' ) {
107 // Anything with a non-negative numeric tabIndex is focusable.
108 // Use .prop to avoid browser bugs
109 if ( $element
.prop( 'tabIndex' ) >= 0 ) {
113 // Some element types are naturally focusable
114 // (indexOf is much faster than regex in Chrome and about the
115 // same in FF: https://jsperf.com/regex-vs-indexof-array2)
116 nodeName
= element
.nodeName
.toLowerCase();
117 if ( [ 'input', 'select', 'textarea', 'button', 'object' ].indexOf( nodeName
) !== -1 ) {
121 // Links and areas are focusable if they have an href
122 if ( ( nodeName
=== 'a' || nodeName
=== 'area' ) && $element
.attr( 'href' ) !== undefined ) {
130 * Find a focusable child.
132 * @param {jQuery} $container Container to search in
133 * @param {boolean} [backwards] Search backwards
134 * @return {jQuery} Focusable child, or an empty jQuery object if none found
136 OO
.ui
.findFocusable = function ( $container
, backwards
) {
137 var $focusable
= $( [] ),
138 // $focusableCandidates is a superset of things that
139 // could get matched by isFocusableElement
140 $focusableCandidates
= $container
141 .find( 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]' );
144 $focusableCandidates
= Array
.prototype.reverse
.call( $focusableCandidates
);
147 $focusableCandidates
.each( function () {
148 var $this = $( this );
149 if ( OO
.ui
.isFocusableElement( $this ) ) {
158 * Get the user's language and any fallback languages.
160 * These language codes are used to localize user interface elements in the user's language.
162 * In environments that provide a localization system, this function should be overridden to
163 * return the user's language(s). The default implementation returns English (en) only.
165 * @return {string[]} Language codes, in descending order of priority
167 OO
.ui
.getUserLanguages = function () {
172 * Get a value in an object keyed by language code.
174 * @param {Object.<string,Mixed>} obj Object keyed by language code
175 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
176 * @param {string} [fallback] Fallback code, used if no matching language can be found
177 * @return {Mixed} Local value
179 OO
.ui
.getLocalValue = function ( obj
, lang
, fallback
) {
182 // Requested language
186 // Known user language
187 langs
= OO
.ui
.getUserLanguages();
188 for ( i
= 0, len
= langs
.length
; i
< len
; i
++ ) {
195 if ( obj
[ fallback
] ) {
196 return obj
[ fallback
];
198 // First existing language
199 for ( lang
in obj
) {
207 * Check if a node is contained within another node.
209 * Similar to jQuery#contains except a list of containers can be supplied
210 * and a boolean argument allows you to include the container in the match list
212 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
213 * @param {HTMLElement} contained Node to find
214 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match,
215 * otherwise only match descendants
216 * @return {boolean} The node is in the list of target nodes
218 OO
.ui
.contains = function ( containers
, contained
, matchContainers
) {
220 if ( !Array
.isArray( containers
) ) {
221 containers
= [ containers
];
223 for ( i
= containers
.length
- 1; i
>= 0; i
-- ) {
225 ( matchContainers
&& contained
=== containers
[ i
] ) ||
226 $.contains( containers
[ i
], contained
)
235 * Return a function, that, as long as it continues to be invoked, will not
236 * be triggered. The function will be called after it stops being called for
237 * N milliseconds. If `immediate` is passed, trigger the function on the
238 * leading edge, instead of the trailing.
240 * Ported from: http://underscorejs.org/underscore.js
242 * @param {Function} func Function to debounce
243 * @param {number} [wait=0] Wait period in milliseconds
244 * @param {boolean} [immediate] Trigger on leading edge
245 * @return {Function} Debounced function
247 OO
.ui
.debounce = function ( func
, wait
, immediate
) {
252 later = function () {
255 func
.apply( context
, args
);
258 if ( immediate
&& !timeout
) {
259 func
.apply( context
, args
);
261 if ( !timeout
|| wait
) {
262 clearTimeout( timeout
);
263 timeout
= setTimeout( later
, wait
);
269 * Puts a console warning with provided message.
271 * @param {string} message Message
273 OO
.ui
.warnDeprecation = function ( message
) {
274 if ( OO
.getProp( window
, 'console', 'warn' ) !== undefined ) {
275 // eslint-disable-next-line no-console
276 console
.warn( message
);
281 * Returns a function, that, when invoked, will only be triggered at most once
282 * during a given window of time. If called again during that window, it will
283 * wait until the window ends and then trigger itself again.
285 * As it's not knowable to the caller whether the function will actually run
286 * when the wrapper is called, return values from the function are entirely
289 * @param {Function} func Function to throttle
290 * @param {number} wait Throttle window length, in milliseconds
291 * @return {Function} Throttled function
293 OO
.ui
.throttle = function ( func
, wait
) {
294 var context
, args
, timeout
,
298 previous
= OO
.ui
.now();
299 func
.apply( context
, args
);
302 // Check how long it's been since the last time the function was
303 // called, and whether it's more or less than the requested throttle
304 // period. If it's less, run the function immediately. If it's more,
305 // set a timeout for the remaining time -- but don't replace an
306 // existing timeout, since that'd indefinitely prolong the wait.
307 var remaining
= wait
- ( OO
.ui
.now() - previous
);
310 if ( remaining
<= 0 ) {
311 // Note: unless wait was ridiculously large, this means we'll
312 // automatically run the first time the function was called in a
313 // given period. (If you provide a wait period larger than the
314 // current Unix timestamp, you *deserve* unexpected behavior.)
315 clearTimeout( timeout
);
317 } else if ( !timeout
) {
318 timeout
= setTimeout( run
, remaining
);
324 * A (possibly faster) way to get the current timestamp as an integer.
326 * @return {number} Current timestamp, in milliseconds since the Unix epoch
328 OO
.ui
.now
= Date
.now
|| function () {
329 return new Date().getTime();
333 * Reconstitute a JavaScript object corresponding to a widget created by
334 * the PHP implementation.
336 * This is an alias for `OO.ui.Element.static.infuse()`.
338 * @param {string|HTMLElement|jQuery} idOrNode
339 * A DOM id (if a string) or node for the widget to infuse.
340 * @param {Object} [config] Configuration options
341 * @return {OO.ui.Element}
342 * The `OO.ui.Element` corresponding to this (infusable) document node.
344 OO
.ui
.infuse = function ( idOrNode
, config
) {
345 return OO
.ui
.Element
.static.infuse( idOrNode
, config
);
350 * Message store for the default implementation of OO.ui.msg.
352 * Environments that provide a localization system should not use this, but should override
353 * OO.ui.msg altogether.
358 // Tool tip for a button that moves items in a list down one place
359 'ooui-outline-control-move-down': 'Move item down',
360 // Tool tip for a button that moves items in a list up one place
361 'ooui-outline-control-move-up': 'Move item up',
362 // Tool tip for a button that removes items from a list
363 'ooui-outline-control-remove': 'Remove item',
364 // Label for the toolbar group that contains a list of all other available tools
365 'ooui-toolbar-more': 'More',
366 // Label for the fake tool that expands the full list of tools in a toolbar group
367 'ooui-toolgroup-expand': 'More',
368 // Label for the fake tool that collapses the full list of tools in a toolbar group
369 'ooui-toolgroup-collapse': 'Fewer',
370 // Default label for the tooltip for the button that removes a tag item
371 'ooui-item-remove': 'Remove',
372 // Default label for the accept button of a confirmation dialog
373 'ooui-dialog-message-accept': 'OK',
374 // Default label for the reject button of a confirmation dialog
375 'ooui-dialog-message-reject': 'Cancel',
376 // Title for process dialog error description
377 'ooui-dialog-process-error': 'Something went wrong',
378 // Label for process dialog dismiss error button, visible when describing errors
379 'ooui-dialog-process-dismiss': 'Dismiss',
380 // Label for process dialog retry action button, visible when describing only recoverable
382 'ooui-dialog-process-retry': 'Try again',
383 // Label for process dialog retry action button, visible when describing only warnings
384 'ooui-dialog-process-continue': 'Continue',
385 // Label for button in combobox input that triggers its dropdown
386 'ooui-combobox-button-label': 'Dropdown for combobox',
387 // Label for the file selection widget's select file button
388 'ooui-selectfile-button-select': 'Select a file',
389 // Label for the file selection widget if file selection is not supported
390 'ooui-selectfile-not-supported': 'File selection is not supported',
391 // Label for the file selection widget when no file is currently selected
392 'ooui-selectfile-placeholder': 'No file is selected',
393 // Label for the file selection widget's drop target
394 'ooui-selectfile-dragdrop-placeholder': 'Drop file here',
395 // Label for the help icon attached to a form field
396 'ooui-field-help': 'Help'
400 * Get a localized message.
402 * After the message key, message parameters may optionally be passed. In the default
403 * implementation, any occurrences of $1 are replaced with the first parameter, $2 with the
404 * second parameter, etc.
405 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long
406 * as they support unnamed, ordered message parameters.
408 * In environments that provide a localization system, this function should be overridden to
409 * return the message translated in the user's language. The default implementation always
410 * returns English messages. An example of doing this with
411 * [jQuery.i18n](https://github.com/wikimedia/jquery.i18n) follows.
414 * var i, iLen, button,
415 * messagePath = 'oojs-ui/dist/i18n/',
416 * languages = [ $.i18n().locale, 'ur', 'en' ],
419 * for ( i = 0, iLen = languages.length; i < iLen; i++ ) {
420 * languageMap[ languages[ i ] ] = messagePath + languages[ i ].toLowerCase() + '.json';
423 * $.i18n().load( languageMap ).done( function() {
424 * // Replace the built-in `msg` only once we've loaded the internationalization.
425 * // OOUI uses `OO.ui.deferMsg` for all initially-loaded messages. So long as
426 * // you put off creating any widgets until this promise is complete, no English
427 * // will be displayed.
428 * OO.ui.msg = $.i18n;
430 * // A button displaying "OK" in the default locale
431 * button = new OO.ui.ButtonWidget( {
432 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
435 * $( document.body ).append( button.$element );
437 * // A button displaying "OK" in Urdu
438 * $.i18n().locale = 'ur';
439 * button = new OO.ui.ButtonWidget( {
440 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
443 * $( document.body ).append( button.$element );
446 * @param {string} key Message key
447 * @param {...Mixed} [params] Message parameters
448 * @return {string} Translated message with parameters substituted
450 OO
.ui
.msg = function ( key
) {
451 var message
= messages
[ key
],
452 params
= Array
.prototype.slice
.call( arguments
, 1 );
453 if ( typeof message
=== 'string' ) {
454 // Perform $1 substitution
455 message
= message
.replace( /\$(\d+)/g, function ( unused
, n
) {
456 var i
= parseInt( n
, 10 );
457 return params
[ i
- 1 ] !== undefined ? params
[ i
- 1 ] : '$' + n
;
460 // Return placeholder if message not found
461 message
= '[' + key
+ ']';
468 * Package a message and arguments for deferred resolution.
470 * Use this when you are statically specifying a message and the message may not yet be present.
472 * @param {string} key Message key
473 * @param {...Mixed} [params] Message parameters
474 * @return {Function} Function that returns the resolved message when executed
476 OO
.ui
.deferMsg = function () {
477 var args
= arguments
;
479 return OO
.ui
.msg
.apply( OO
.ui
, args
);
486 * If the message is a function it will be executed, otherwise it will pass through directly.
488 * @param {Function|string} msg Deferred message, or message text
489 * @return {string} Resolved message
491 OO
.ui
.resolveMsg = function ( msg
) {
492 if ( typeof msg
=== 'function' ) {
499 * @param {string} url
502 OO
.ui
.isSafeUrl = function ( url
) {
503 // Keep this function in sync with php/Tag.php
504 var i
, protocolWhitelist
;
506 function stringStartsWith( haystack
, needle
) {
507 return haystack
.substr( 0, needle
.length
) === needle
;
510 protocolWhitelist
= [
511 'bitcoin', 'ftp', 'ftps', 'geo', 'git', 'gopher', 'http', 'https', 'irc', 'ircs',
512 'magnet', 'mailto', 'mms', 'news', 'nntp', 'redis', 'sftp', 'sip', 'sips', 'sms', 'ssh',
513 'svn', 'tel', 'telnet', 'urn', 'worldwind', 'xmpp'
520 for ( i
= 0; i
< protocolWhitelist
.length
; i
++ ) {
521 if ( stringStartsWith( url
, protocolWhitelist
[ i
] + ':' ) ) {
526 // This matches '//' too
527 if ( stringStartsWith( url
, '/' ) || stringStartsWith( url
, './' ) ) {
530 if ( stringStartsWith( url
, '?' ) || stringStartsWith( url
, '#' ) ) {
538 * Check if the user has a 'mobile' device.
540 * For our purposes this means the user is primarily using an
541 * on-screen keyboard, touch input instead of a mouse and may
542 * have a physically small display.
544 * It is left up to implementors to decide how to compute this
545 * so the default implementation always returns false.
547 * @return {boolean} User is on a mobile device
549 OO
.ui
.isMobile = function () {
554 * Get the additional spacing that should be taken into account when displaying elements that are
555 * clipped to the viewport, e.g. dropdown menus and popups. This is meant to be overridden to avoid
556 * such menus overlapping any fixed headers/toolbars/navigation used by the site.
558 * @return {Object} Object with the properties 'top', 'right', 'bottom', 'left', each representing
559 * the extra spacing from that edge of viewport (in pixels)
561 OO
.ui
.getViewportSpacing = function () {
571 * Get the default overlay, which is used by various widgets when they are passed `$overlay: true`.
572 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
574 * @return {jQuery} Default overlay node
576 OO
.ui
.getDefaultOverlay = function () {
577 if ( !OO
.ui
.$defaultOverlay
) {
578 OO
.ui
.$defaultOverlay
= $( '<div>' ).addClass( 'oo-ui-defaultOverlay' );
579 $( document
.body
).append( OO
.ui
.$defaultOverlay
);
581 return OO
.ui
.$defaultOverlay
;
589 * Namespace for OOUI mixins.
591 * Mixins are named according to the type of object they are intended to
592 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
593 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
594 * is intended to be mixed in to an instance of OO.ui.Widget.
602 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
603 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not
604 * have events connected to them and can't be interacted with.
610 * @param {Object} [config] Configuration options
611 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are
612 * added to the top level (e.g., the outermost div) of the element. See the
613 * [OOUI documentation on MediaWiki][2] for an example.
614 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches#cssExample
615 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
616 * @cfg {string} [text] Text to insert
617 * @cfg {Array} [content] An array of content elements to append (after #text).
618 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
619 * Instances of OO.ui.Element will have their $element appended.
620 * @cfg {jQuery} [$content] Content elements to append (after #text).
621 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
622 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number,
624 * Data can also be specified with the #setData method.
626 OO
.ui
.Element
= function OoUiElement( config
) {
627 if ( OO
.ui
.isDemo
) {
628 this.initialConfig
= config
;
630 // Configuration initialization
631 config
= config
|| {};
634 this.$ = function () {
635 OO
.ui
.warnDeprecation( 'this.$ is deprecated, use global $ instead' );
636 return $.apply( this, arguments
);
638 this.elementId
= null;
640 this.data
= config
.data
;
641 this.$element
= config
.$element
||
642 $( document
.createElement( this.getTagName() ) );
643 this.elementGroup
= null;
646 if ( Array
.isArray( config
.classes
) ) {
647 this.$element
.addClass( config
.classes
);
650 this.setElementId( config
.id
);
653 this.$element
.text( config
.text
);
655 if ( config
.content
) {
656 // The `content` property treats plain strings as text; use an
657 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
658 // appropriate $element appended.
659 this.$element
.append( config
.content
.map( function ( v
) {
660 if ( typeof v
=== 'string' ) {
661 // Escape string so it is properly represented in HTML.
662 // Don't create empty text nodes for empty strings.
663 return v
? document
.createTextNode( v
) : undefined;
664 } else if ( v
instanceof OO
.ui
.HtmlSnippet
) {
667 } else if ( v
instanceof OO
.ui
.Element
) {
673 if ( config
.$content
) {
674 // The `$content` property treats plain strings as HTML.
675 this.$element
.append( config
.$content
);
681 OO
.initClass( OO
.ui
.Element
);
683 /* Static Properties */
686 * The name of the HTML tag used by the element.
688 * The static value may be ignored if the #getTagName method is overridden.
694 OO
.ui
.Element
.static.tagName
= 'div';
699 * Reconstitute a JavaScript object corresponding to a widget created
700 * by the PHP implementation.
702 * @param {string|HTMLElement|jQuery} idOrNode
703 * A DOM id (if a string) or node for the widget to infuse.
704 * @param {Object} [config] Configuration options
705 * @return {OO.ui.Element}
706 * The `OO.ui.Element` corresponding to this (infusable) document node.
707 * For `Tag` objects emitted on the HTML side (used occasionally for content)
708 * the value returned is a newly-created Element wrapping around the existing
711 OO
.ui
.Element
.static.infuse = function ( idOrNode
, config
) {
712 var obj
= OO
.ui
.Element
.static.unsafeInfuse( idOrNode
, config
, false );
714 if ( typeof idOrNode
=== 'string' ) {
715 // IDs deprecated since 0.29.7
716 OO
.ui
.warnDeprecation(
717 'Passing a string ID to infuse is deprecated. Use an HTMLElement or jQuery collection instead.'
720 // Verify that the type matches up.
721 // FIXME: uncomment after T89721 is fixed, see T90929.
723 if ( !( obj instanceof this['class'] ) ) {
724 throw new Error( 'Infusion type mismatch!' );
731 * Implementation helper for `infuse`; skips the type check and has an
732 * extra property so that only the top-level invocation touches the DOM.
735 * @param {string|HTMLElement|jQuery} idOrNode
736 * @param {Object} [config] Configuration options
737 * @param {jQuery.Promise} [domPromise] A promise that will be resolved
738 * when the top-level widget of this infusion is inserted into DOM,
739 * replacing the original node; only used internally.
740 * @return {OO.ui.Element}
742 OO
.ui
.Element
.static.unsafeInfuse = function ( idOrNode
, config
, domPromise
) {
743 // look for a cached result of a previous infusion.
744 var id
, $elem
, error
, data
, cls
, parts
, parent
, obj
, top
, state
, infusedChildren
;
745 if ( typeof idOrNode
=== 'string' ) {
747 $elem
= $( document
.getElementById( id
) );
749 $elem
= $( idOrNode
);
750 id
= $elem
.attr( 'id' );
752 if ( !$elem
.length
) {
753 if ( typeof idOrNode
=== 'string' ) {
754 error
= 'Widget not found: ' + idOrNode
;
755 } else if ( idOrNode
&& idOrNode
.selector
) {
756 error
= 'Widget not found: ' + idOrNode
.selector
;
758 error
= 'Widget not found';
760 throw new Error( error
);
762 if ( $elem
[ 0 ].oouiInfused
) {
763 $elem
= $elem
[ 0 ].oouiInfused
;
765 data
= $elem
.data( 'ooui-infused' );
768 if ( data
=== true ) {
769 throw new Error( 'Circular dependency! ' + id
);
772 // Pick up dynamic state, like focus, value of form inputs, scroll position, etc.
773 state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
774 // Restore dynamic state after the new element is re-inserted into DOM under
776 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
777 infusedChildren
= $elem
.data( 'ooui-infused-children' );
778 if ( infusedChildren
&& infusedChildren
.length
) {
779 infusedChildren
.forEach( function ( data
) {
780 var state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
781 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
787 data
= $elem
.attr( 'data-ooui' );
789 throw new Error( 'No infusion data found: ' + id
);
792 data
= JSON
.parse( data
);
796 if ( !( data
&& data
._
) ) {
797 throw new Error( 'No valid infusion data found: ' + id
);
799 if ( data
._
=== 'Tag' ) {
800 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
801 return new OO
.ui
.Element( $.extend( {}, config
, { $element
: $elem
} ) );
803 parts
= data
._
.split( '.' );
804 cls
= OO
.getProp
.apply( OO
, [ window
].concat( parts
) );
805 if ( cls
=== undefined ) {
806 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
809 // Verify that we're creating an OO.ui.Element instance
812 while ( parent
!== undefined ) {
813 if ( parent
=== OO
.ui
.Element
) {
818 parent
= parent
.parent
;
821 if ( parent
!== OO
.ui
.Element
) {
822 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
827 domPromise
= top
.promise();
829 $elem
.data( 'ooui-infused', true ); // prevent loops
830 data
.id
= id
; // implicit
831 infusedChildren
= [];
832 data
= OO
.copy( data
, null, function deserialize( value
) {
834 if ( OO
.isPlainObject( value
) ) {
836 infused
= OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, config
, domPromise
);
837 infusedChildren
.push( infused
);
838 // Flatten the structure
839 infusedChildren
.push
.apply(
841 infused
.$element
.data( 'ooui-infused-children' ) || []
843 infused
.$element
.removeData( 'ooui-infused-children' );
846 if ( value
.html
!== undefined ) {
847 return new OO
.ui
.HtmlSnippet( value
.html
);
851 // allow widgets to reuse parts of the DOM
852 data
= cls
.static.reusePreInfuseDOM( $elem
[ 0 ], data
);
853 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
854 state
= cls
.static.gatherPreInfuseState( $elem
[ 0 ], data
);
856 // eslint-disable-next-line new-cap
857 obj
= new cls( $.extend( {}, config
, data
) );
858 // If anyone is holding a reference to the old DOM element,
859 // let's allow them to OO.ui.infuse() it and do what they expect, see T105828.
860 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
861 $elem
[ 0 ].oouiInfused
= obj
.$element
;
862 // now replace old DOM with this new DOM.
864 // An efficient constructor might be able to reuse the entire DOM tree of the original
865 // element, so only mutate the DOM if we need to.
866 if ( $elem
[ 0 ] !== obj
.$element
[ 0 ] ) {
867 $elem
.replaceWith( obj
.$element
);
871 obj
.$element
.data( 'ooui-infused', obj
);
872 obj
.$element
.data( 'ooui-infused-children', infusedChildren
);
873 // set the 'data-ooui' attribute so we can identify infused widgets
874 obj
.$element
.attr( 'data-ooui', '' );
875 // restore dynamic state after the new element is inserted into DOM
876 domPromise
.done( obj
.restorePreInfuseState
.bind( obj
, state
) );
881 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
883 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
884 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
885 * constructor, which will be given the enhanced config.
888 * @param {HTMLElement} node
889 * @param {Object} config
892 OO
.ui
.Element
.static.reusePreInfuseDOM = function ( node
, config
) {
897 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of an HTML DOM
898 * node (and its children) that represent an Element of the same class and the given configuration,
899 * generated by the PHP implementation.
901 * This method is called just before `node` is detached from the DOM. The return value of this
902 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
903 * is inserted into DOM to replace `node`.
906 * @param {HTMLElement} node
907 * @param {Object} config
910 OO
.ui
.Element
.static.gatherPreInfuseState = function () {
915 * Get a jQuery function within a specific document.
918 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
919 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
921 * @return {Function} Bound jQuery function
923 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
924 function wrapper( selector
) {
925 return $( selector
, wrapper
.context
);
928 wrapper
.context
= this.getDocument( context
);
931 wrapper
.$iframe
= $iframe
;
938 * Get the document of an element.
941 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
942 * @return {HTMLDocument|null} Document object
944 OO
.ui
.Element
.static.getDocument = function ( obj
) {
945 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
946 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
947 // Empty jQuery selections might have a context
954 ( obj
.nodeType
=== Node
.DOCUMENT_NODE
&& obj
) ||
959 * Get the window of an element or document.
962 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
963 * @return {Window} Window object
965 OO
.ui
.Element
.static.getWindow = function ( obj
) {
966 var doc
= this.getDocument( obj
);
967 return doc
.defaultView
;
971 * Get the direction of an element or document.
974 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
975 * @return {string} Text direction, either 'ltr' or 'rtl'
977 OO
.ui
.Element
.static.getDir = function ( obj
) {
980 if ( obj
instanceof $ ) {
983 isDoc
= obj
.nodeType
=== Node
.DOCUMENT_NODE
;
984 isWin
= obj
.document
!== undefined;
985 if ( isDoc
|| isWin
) {
991 return $( obj
).css( 'direction' );
995 * Get the offset between two frames.
997 * TODO: Make this function not use recursion.
1000 * @param {Window} from Window of the child frame
1001 * @param {Window} [to=window] Window of the parent frame
1002 * @param {Object} [offset] Offset to start with, used internally
1003 * @return {Object} Offset object, containing left and top properties
1005 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
1006 var i
, len
, frames
, frame
, rect
;
1012 offset
= { top
: 0, left
: 0 };
1014 if ( from.parent
=== from ) {
1018 // Get iframe element
1019 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
1020 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
1021 if ( frames
[ i
].contentWindow
=== from ) {
1022 frame
= frames
[ i
];
1027 // Recursively accumulate offset values
1029 rect
= frame
.getBoundingClientRect();
1030 offset
.left
+= rect
.left
;
1031 offset
.top
+= rect
.top
;
1032 if ( from !== to
) {
1033 this.getFrameOffset( from.parent
, offset
);
1040 * Get the offset between two elements.
1042 * The two elements may be in a different frame, but in that case the frame $element is in must
1043 * be contained in the frame $anchor is in.
1046 * @param {jQuery} $element Element whose position to get
1047 * @param {jQuery} $anchor Element to get $element's position relative to
1048 * @return {Object} Translated position coordinates, containing top and left properties
1050 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
1051 var iframe
, iframePos
,
1052 pos
= $element
.offset(),
1053 anchorPos
= $anchor
.offset(),
1054 elementDocument
= this.getDocument( $element
),
1055 anchorDocument
= this.getDocument( $anchor
);
1057 // If $element isn't in the same document as $anchor, traverse up
1058 while ( elementDocument
!== anchorDocument
) {
1059 iframe
= elementDocument
.defaultView
.frameElement
;
1061 throw new Error( '$element frame is not contained in $anchor frame' );
1063 iframePos
= $( iframe
).offset();
1064 pos
.left
+= iframePos
.left
;
1065 pos
.top
+= iframePos
.top
;
1066 elementDocument
= iframe
.ownerDocument
;
1068 pos
.left
-= anchorPos
.left
;
1069 pos
.top
-= anchorPos
.top
;
1074 * Get element border sizes.
1077 * @param {HTMLElement} el Element to measure
1078 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1080 OO
.ui
.Element
.static.getBorders = function ( el
) {
1081 var doc
= el
.ownerDocument
,
1082 win
= doc
.defaultView
,
1083 style
= win
.getComputedStyle( el
, null ),
1085 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
1086 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
1087 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
1088 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
1099 * Get dimensions of an element or window.
1102 * @param {HTMLElement|Window} el Element to measure
1103 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1105 OO
.ui
.Element
.static.getDimensions = function ( el
) {
1107 doc
= el
.ownerDocument
|| el
.document
,
1108 win
= doc
.defaultView
;
1110 if ( win
=== el
|| el
=== doc
.documentElement
) {
1113 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
1115 top
: $win
.scrollTop(),
1116 left
: $win
.scrollLeft()
1118 scrollbar
: { right
: 0, bottom
: 0 },
1122 bottom
: $win
.innerHeight(),
1123 right
: $win
.innerWidth()
1129 borders
: this.getBorders( el
),
1131 top
: $el
.scrollTop(),
1132 left
: $el
.scrollLeft()
1135 right
: $el
.innerWidth() - el
.clientWidth
,
1136 bottom
: $el
.innerHeight() - el
.clientHeight
1138 rect
: el
.getBoundingClientRect()
1144 * Get the number of pixels that an element's content is scrolled to the left.
1146 * Adapted from <https://github.com/othree/jquery.rtl-scroll-type>.
1147 * Original code copyright 2012 Wei-Ko Kao, licensed under the MIT License.
1149 * This function smooths out browser inconsistencies (nicely described in the README at
1150 * <https://github.com/othree/jquery.rtl-scroll-type>) and produces a result consistent
1151 * with Firefox's 'scrollLeft', which seems the sanest.
1155 * @param {HTMLElement|Window} el Element to measure
1156 * @return {number} Scroll position from the left.
1157 * If the element's direction is LTR, this is a positive number between `0` (initial scroll
1158 * position) and `el.scrollWidth - el.clientWidth` (furthest possible scroll position).
1159 * If the element's direction is RTL, this is a negative number between `0` (initial scroll
1160 * position) and `-el.scrollWidth + el.clientWidth` (furthest possible scroll position).
1162 OO
.ui
.Element
.static.getScrollLeft
= ( function () {
1163 var rtlScrollType
= null;
1166 var $definer
= $( '<div>' ).attr( {
1168 style
: 'font-size: 14px; width: 4px; height: 1px; position: absolute; top: -1000px; overflow: scroll;'
1170 definer
= $definer
[ 0 ];
1172 $definer
.appendTo( 'body' );
1173 if ( definer
.scrollLeft
> 0 ) {
1175 rtlScrollType
= 'default';
1177 definer
.scrollLeft
= 1;
1178 if ( definer
.scrollLeft
=== 0 ) {
1179 // Firefox, old Opera
1180 rtlScrollType
= 'negative';
1182 // Internet Explorer, Edge
1183 rtlScrollType
= 'reverse';
1189 return function getScrollLeft( el
) {
1190 var isRoot
= el
.window
=== el
||
1191 el
=== el
.ownerDocument
.body
||
1192 el
=== el
.ownerDocument
.documentElement
,
1193 scrollLeft
= isRoot
? $( window
).scrollLeft() : el
.scrollLeft
,
1194 // All browsers use the correct scroll type ('negative') on the root, so don't
1195 // do any fixups when looking at the root element
1196 direction
= isRoot
? 'ltr' : $( el
).css( 'direction' );
1198 if ( direction
=== 'rtl' ) {
1199 if ( rtlScrollType
=== null ) {
1202 if ( rtlScrollType
=== 'reverse' ) {
1203 scrollLeft
= -scrollLeft
;
1204 } else if ( rtlScrollType
=== 'default' ) {
1205 scrollLeft
= scrollLeft
- el
.scrollWidth
+ el
.clientWidth
;
1214 * Get the root scrollable element of given element's document.
1216 * On Blink-based browsers (Chrome etc.), `document.documentElement` can't be used to get or set
1217 * the scrollTop property; instead we have to use `document.body`. Changing and testing the value
1218 * lets us use 'body' or 'documentElement' based on what is working.
1220 * https://code.google.com/p/chromium/issues/detail?id=303131
1223 * @param {HTMLElement} el Element to find root scrollable parent for
1224 * @return {HTMLElement} Scrollable parent, `document.body` or `document.documentElement`
1225 * depending on browser
1227 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1228 var scrollTop
, body
;
1230 if ( OO
.ui
.scrollableElement
=== undefined ) {
1231 body
= el
.ownerDocument
.body
;
1232 scrollTop
= body
.scrollTop
;
1235 // In some browsers (observed in Chrome 56 on Linux Mint 18.1),
1236 // body.scrollTop doesn't become exactly 1, but a fractional value like 0.76
1237 if ( Math
.round( body
.scrollTop
) === 1 ) {
1238 body
.scrollTop
= scrollTop
;
1239 OO
.ui
.scrollableElement
= 'body';
1241 OO
.ui
.scrollableElement
= 'documentElement';
1245 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1249 * Get closest scrollable container.
1251 * Traverses up until either a scrollable element or the root is reached, in which case the root
1252 * scrollable element will be returned (see #getRootScrollableElement).
1255 * @param {HTMLElement} el Element to find scrollable container for
1256 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1257 * @return {HTMLElement} Closest scrollable container
1259 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1261 // Browsers do not correctly return the computed value of 'overflow' when 'overflow-x' and
1262 // 'overflow-y' have different values, so we need to check the separate properties.
1263 props
= [ 'overflow-x', 'overflow-y' ],
1264 $parent
= $( el
).parent();
1266 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1267 props
= [ 'overflow-' + dimension
];
1270 // Special case for the document root (which doesn't really have any scrollable container,
1271 // since it is the ultimate scrollable container, but this is probably saner than null or
1273 if ( $( el
).is( 'html, body' ) ) {
1274 return this.getRootScrollableElement( el
);
1277 while ( $parent
.length
) {
1278 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1279 return $parent
[ 0 ];
1283 val
= $parent
.css( props
[ i
] );
1284 // We assume that elements with 'overflow' (in any direction) set to 'hidden' will
1285 // never be scrolled in that direction, but they can actually be scrolled
1286 // programatically. The user can unintentionally perform a scroll in such case even if
1287 // the application doesn't scroll programatically, e.g. when jumping to an anchor, or
1288 // when using built-in find functionality.
1289 // This could cause funny issues...
1290 if ( val
=== 'auto' || val
=== 'scroll' ) {
1291 return $parent
[ 0 ];
1294 $parent
= $parent
.parent();
1296 // The element is unattached... return something mostly sane
1297 return this.getRootScrollableElement( el
);
1301 * Scroll element into view.
1304 * @param {HTMLElement} el Element to scroll into view
1305 * @param {Object} [config] Configuration options
1306 * @param {string} [config.duration='fast'] jQuery animation duration value
1307 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1308 * to scroll in both directions
1309 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1311 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1312 var position
, animations
, container
, $container
, elementDimensions
, containerDimensions
,
1314 deferred
= $.Deferred();
1316 // Configuration initialization
1317 config
= config
|| {};
1320 container
= this.getClosestScrollableContainer( el
, config
.direction
);
1321 $container
= $( container
);
1322 elementDimensions
= this.getDimensions( el
);
1323 containerDimensions
= this.getDimensions( container
);
1324 $window
= $( this.getWindow( el
) );
1326 // Compute the element's position relative to the container
1327 if ( $container
.is( 'html, body' ) ) {
1328 // If the scrollable container is the root, this is easy
1330 top
: elementDimensions
.rect
.top
,
1331 bottom
: $window
.innerHeight() - elementDimensions
.rect
.bottom
,
1332 left
: elementDimensions
.rect
.left
,
1333 right
: $window
.innerWidth() - elementDimensions
.rect
.right
1336 // Otherwise, we have to subtract el's coordinates from container's coordinates
1338 top
: elementDimensions
.rect
.top
-
1339 ( containerDimensions
.rect
.top
+ containerDimensions
.borders
.top
),
1340 bottom
: containerDimensions
.rect
.bottom
- containerDimensions
.borders
.bottom
-
1341 containerDimensions
.scrollbar
.bottom
- elementDimensions
.rect
.bottom
,
1342 left
: elementDimensions
.rect
.left
-
1343 ( containerDimensions
.rect
.left
+ containerDimensions
.borders
.left
),
1344 right
: containerDimensions
.rect
.right
- containerDimensions
.borders
.right
-
1345 containerDimensions
.scrollbar
.right
- elementDimensions
.rect
.right
1349 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1350 if ( position
.top
< 0 ) {
1351 animations
.scrollTop
= containerDimensions
.scroll
.top
+ position
.top
;
1352 } else if ( position
.top
> 0 && position
.bottom
< 0 ) {
1353 animations
.scrollTop
= containerDimensions
.scroll
.top
+
1354 Math
.min( position
.top
, -position
.bottom
);
1357 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1358 if ( position
.left
< 0 ) {
1359 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ position
.left
;
1360 } else if ( position
.left
> 0 && position
.right
< 0 ) {
1361 animations
.scrollLeft
= containerDimensions
.scroll
.left
+
1362 Math
.min( position
.left
, -position
.right
);
1365 if ( !$.isEmptyObject( animations
) ) {
1366 // eslint-disable-next-line no-jquery/no-animate
1367 $container
.stop( true ).animate( animations
, config
.duration
=== undefined ?
1368 'fast' : config
.duration
);
1369 $container
.queue( function ( next
) {
1376 return deferred
.promise();
1380 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1381 * and reserve space for them, because it probably doesn't.
1383 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1384 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1385 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a
1386 * reflow, and then reattach (or show) them back.
1389 * @param {HTMLElement} el Element to reconsider the scrollbars on
1391 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1392 var i
, len
, scrollLeft
, scrollTop
, nodes
= [];
1393 // Save scroll position
1394 scrollLeft
= el
.scrollLeft
;
1395 scrollTop
= el
.scrollTop
;
1396 // Detach all children
1397 while ( el
.firstChild
) {
1398 nodes
.push( el
.firstChild
);
1399 el
.removeChild( el
.firstChild
);
1402 // eslint-disable-next-line no-void
1403 void el
.offsetHeight
;
1404 // Reattach all children
1405 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1406 el
.appendChild( nodes
[ i
] );
1408 // Restore scroll position (no-op if scrollbars disappeared)
1409 el
.scrollLeft
= scrollLeft
;
1410 el
.scrollTop
= scrollTop
;
1416 * Toggle visibility of an element.
1418 * @param {boolean} [show] Make element visible, omit to toggle visibility
1421 * @return {OO.ui.Element} The element, for chaining
1423 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1424 show
= show
=== undefined ? !this.visible
: !!show
;
1426 if ( show
!== this.isVisible() ) {
1427 this.visible
= show
;
1428 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1429 this.emit( 'toggle', show
);
1436 * Check if element is visible.
1438 * @return {boolean} element is visible
1440 OO
.ui
.Element
.prototype.isVisible = function () {
1441 return this.visible
;
1447 * @return {Mixed} Element data
1449 OO
.ui
.Element
.prototype.getData = function () {
1456 * @param {Mixed} data Element data
1458 * @return {OO.ui.Element} The element, for chaining
1460 OO
.ui
.Element
.prototype.setData = function ( data
) {
1466 * Set the element has an 'id' attribute.
1468 * @param {string} id
1470 * @return {OO.ui.Element} The element, for chaining
1472 OO
.ui
.Element
.prototype.setElementId = function ( id
) {
1473 this.elementId
= id
;
1474 this.$element
.attr( 'id', id
);
1479 * Ensure that the element has an 'id' attribute, setting it to an unique value if it's missing,
1480 * and return its value.
1484 OO
.ui
.Element
.prototype.getElementId = function () {
1485 if ( this.elementId
=== null ) {
1486 this.setElementId( OO
.ui
.generateElementId() );
1488 return this.elementId
;
1492 * Check if element supports one or more methods.
1494 * @param {string|string[]} methods Method or list of methods to check
1495 * @return {boolean} All methods are supported
1497 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1501 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1502 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1503 if ( typeof this[ methods
[ i
] ] === 'function' ) {
1508 return methods
.length
=== support
;
1512 * Update the theme-provided classes.
1514 * @localdoc This is called in element mixins and widget classes any time state changes.
1515 * Updating is debounced, minimizing overhead of changing multiple attributes and
1516 * guaranteeing that theme updates do not occur within an element's constructor
1518 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1519 OO
.ui
.theme
.queueUpdateElementClasses( this );
1523 * Get the HTML tag name.
1525 * Override this method to base the result on instance information.
1527 * @return {string} HTML tag name
1529 OO
.ui
.Element
.prototype.getTagName = function () {
1530 return this.constructor.static.tagName
;
1534 * Check if the element is attached to the DOM
1536 * @return {boolean} The element is attached to the DOM
1538 OO
.ui
.Element
.prototype.isElementAttached = function () {
1539 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1543 * Get the DOM document.
1545 * @return {HTMLDocument} Document object
1547 OO
.ui
.Element
.prototype.getElementDocument = function () {
1548 // Don't cache this in other ways either because subclasses could can change this.$element
1549 return OO
.ui
.Element
.static.getDocument( this.$element
);
1553 * Get the DOM window.
1555 * @return {Window} Window object
1557 OO
.ui
.Element
.prototype.getElementWindow = function () {
1558 return OO
.ui
.Element
.static.getWindow( this.$element
);
1562 * Get closest scrollable container.
1564 * @return {HTMLElement} Closest scrollable container
1566 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1567 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1571 * Get group element is in.
1573 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1575 OO
.ui
.Element
.prototype.getElementGroup = function () {
1576 return this.elementGroup
;
1580 * Set group element is in.
1582 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1584 * @return {OO.ui.Element} The element, for chaining
1586 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1587 this.elementGroup
= group
;
1592 * Scroll element into view.
1594 * @param {Object} [config] Configuration options
1595 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1597 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1599 !this.isElementAttached() ||
1600 !this.isVisible() ||
1601 ( this.getElementGroup() && !this.getElementGroup().isVisible() )
1603 return $.Deferred().resolve();
1605 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1609 * Restore the pre-infusion dynamic state for this widget.
1611 * This method is called after #$element has been inserted into DOM. The parameter is the return
1612 * value of #gatherPreInfuseState.
1615 * @param {Object} state
1617 OO
.ui
.Element
.prototype.restorePreInfuseState = function () {
1621 * Wraps an HTML snippet for use with configuration values which default
1622 * to strings. This bypasses the default html-escaping done to string
1628 * @param {string} [content] HTML content
1630 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
1632 this.content
= content
;
1637 OO
.initClass( OO
.ui
.HtmlSnippet
);
1644 * @return {string} Unchanged HTML snippet.
1646 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
1647 return this.content
;
1651 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in
1652 * a way that is centrally controlled and can be updated dynamically. Layouts can be, and usually
1654 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout},
1655 * {@link OO.ui.FormLayout FormLayout}, {@link OO.ui.PanelLayout PanelLayout},
1656 * {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1657 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout}
1658 * for more information and examples.
1662 * @extends OO.ui.Element
1663 * @mixins OO.EventEmitter
1666 * @param {Object} [config] Configuration options
1668 OO
.ui
.Layout
= function OoUiLayout( config
) {
1669 // Configuration initialization
1670 config
= config
|| {};
1672 // Parent constructor
1673 OO
.ui
.Layout
.parent
.call( this, config
);
1675 // Mixin constructors
1676 OO
.EventEmitter
.call( this );
1679 this.$element
.addClass( 'oo-ui-layout' );
1684 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1685 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1690 * Reset scroll offsets
1693 * @return {OO.ui.Layout} The layout, for chaining
1695 OO
.ui
.Layout
.prototype.resetScroll = function () {
1696 this.$element
[ 0 ].scrollTop
= 0;
1697 // TODO: Reset scrollLeft in an RTL-aware manner, see OO.ui.Element.static.getScrollLeft.
1703 * Widgets are compositions of one or more OOUI elements that users can both view
1704 * and interact with. All widgets can be configured and modified via a standard API,
1705 * and their state can change dynamically according to a model.
1709 * @extends OO.ui.Element
1710 * @mixins OO.EventEmitter
1713 * @param {Object} [config] Configuration options
1714 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1715 * appearance reflects this state.
1717 OO
.ui
.Widget
= function OoUiWidget( config
) {
1718 // Initialize config
1719 config
= $.extend( { disabled
: false }, config
);
1721 // Parent constructor
1722 OO
.ui
.Widget
.parent
.call( this, config
);
1724 // Mixin constructors
1725 OO
.EventEmitter
.call( this );
1728 this.disabled
= null;
1729 this.wasDisabled
= null;
1732 this.$element
.addClass( 'oo-ui-widget' );
1733 this.setDisabled( !!config
.disabled
);
1738 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1739 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1746 * A 'disable' event is emitted when the disabled state of the widget changes
1747 * (i.e. on disable **and** enable).
1749 * @param {boolean} disabled Widget is disabled
1755 * A 'toggle' event is emitted when the visibility of the widget changes.
1757 * @param {boolean} visible Widget is visible
1763 * Check if the widget is disabled.
1765 * @return {boolean} Widget is disabled
1767 OO
.ui
.Widget
.prototype.isDisabled = function () {
1768 return this.disabled
;
1772 * Set the 'disabled' state of the widget.
1774 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1776 * @param {boolean} disabled Disable widget
1778 * @return {OO.ui.Widget} The widget, for chaining
1780 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
1783 this.disabled
= !!disabled
;
1784 isDisabled
= this.isDisabled();
1785 if ( isDisabled
!== this.wasDisabled
) {
1786 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
1787 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
1788 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
1789 this.emit( 'disable', isDisabled
);
1790 this.updateThemeClasses();
1792 this.wasDisabled
= isDisabled
;
1798 * Update the disabled state, in case of changes in parent widget.
1801 * @return {OO.ui.Widget} The widget, for chaining
1803 OO
.ui
.Widget
.prototype.updateDisabled = function () {
1804 this.setDisabled( this.disabled
);
1809 * Get an ID of a labelable node which is part of this widget, if any, to be used for `<label for>`
1812 * If this function returns null, the widget should have a meaningful #simulateLabelClick method
1815 * @return {string|null} The ID of the labelable element
1817 OO
.ui
.Widget
.prototype.getInputId = function () {
1822 * Simulate the behavior of clicking on a label (a HTML `<label>` element) bound to this input.
1823 * HTML only allows `<label>` to act on specific "labelable" elements; complex widgets might need to
1824 * override this method to provide intuitive, accessible behavior.
1826 * By default, this does nothing. OO.ui.mixin.TabIndexedElement overrides it for focusable widgets.
1827 * Individual widgets may override it too.
1829 * This method is called by OO.ui.LabelWidget and OO.ui.FieldLayout. It should not be called
1832 OO
.ui
.Widget
.prototype.simulateLabelClick = function () {
1843 OO
.ui
.Theme
= function OoUiTheme() {
1844 this.elementClassesQueue
= [];
1845 this.debouncedUpdateQueuedElementClasses
= OO
.ui
.debounce( this.updateQueuedElementClasses
);
1850 OO
.initClass( OO
.ui
.Theme
);
1855 * Get a list of classes to be applied to a widget.
1857 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
1858 * otherwise state transitions will not work properly.
1860 * @param {OO.ui.Element} element Element for which to get classes
1861 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1863 OO
.ui
.Theme
.prototype.getElementClasses = function () {
1864 return { on
: [], off
: [] };
1868 * Update CSS classes provided by the theme.
1870 * For elements with theme logic hooks, this should be called any time there's a state change.
1872 * @param {OO.ui.Element} element Element for which to update classes
1874 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
1875 var $elements
= $( [] ),
1876 classes
= this.getElementClasses( element
);
1878 if ( element
.$icon
) {
1879 $elements
= $elements
.add( element
.$icon
);
1881 if ( element
.$indicator
) {
1882 $elements
= $elements
.add( element
.$indicator
);
1886 .removeClass( classes
.off
)
1887 .addClass( classes
.on
);
1893 OO
.ui
.Theme
.prototype.updateQueuedElementClasses = function () {
1895 for ( i
= 0; i
< this.elementClassesQueue
.length
; i
++ ) {
1896 this.updateElementClasses( this.elementClassesQueue
[ i
] );
1899 this.elementClassesQueue
= [];
1903 * Queue #updateElementClasses to be called for this element.
1905 * @localdoc QUnit tests override this method to directly call #queueUpdateElementClasses,
1906 * to make them synchronous.
1908 * @param {OO.ui.Element} element Element for which to update classes
1910 OO
.ui
.Theme
.prototype.queueUpdateElementClasses = function ( element
) {
1911 // Keep items in the queue unique. Use lastIndexOf to start checking from the end because that's
1912 // the most common case (this method is often called repeatedly for the same element).
1913 if ( this.elementClassesQueue
.lastIndexOf( element
) !== -1 ) {
1916 this.elementClassesQueue
.push( element
);
1917 this.debouncedUpdateQueuedElementClasses();
1921 * Get the transition duration in milliseconds for dialogs opening/closing
1923 * The dialog should be fully rendered this many milliseconds after the
1924 * ready process has executed.
1926 * @return {number} Transition duration in milliseconds
1928 OO
.ui
.Theme
.prototype.getDialogTransitionDuration = function () {
1933 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
1934 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
1935 * order in which users will navigate through the focusable elements via the Tab key.
1938 * // TabIndexedElement is mixed into the ButtonWidget class
1939 * // to provide a tabIndex property.
1940 * var button1 = new OO.ui.ButtonWidget( {
1944 * button2 = new OO.ui.ButtonWidget( {
1948 * button3 = new OO.ui.ButtonWidget( {
1952 * button4 = new OO.ui.ButtonWidget( {
1956 * $( document.body ).append(
1967 * @param {Object} [config] Configuration options
1968 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
1969 * the functionality is applied to the element created by the class ($element). If a different
1970 * element is specified, the tabindex functionality will be applied to it instead.
1971 * @cfg {string|number|null} [tabIndex=0] Number that specifies the element’s position in the
1972 * tab-navigation order (e.g., 1 for the first focusable element). Use 0 to use the default
1973 * navigation order; use -1 to remove the element from the tab-navigation flow.
1975 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
1976 // Configuration initialization
1977 config
= $.extend( { tabIndex
: 0 }, config
);
1980 this.$tabIndexed
= null;
1981 this.tabIndex
= null;
1984 this.connect( this, {
1985 disable
: 'onTabIndexedElementDisable'
1989 this.setTabIndex( config
.tabIndex
);
1990 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
1995 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
2000 * Set the element that should use the tabindex functionality.
2002 * This method is used to retarget a tabindex mixin so that its functionality applies
2003 * to the specified element. If an element is currently using the functionality, the mixin’s
2004 * effect on that element is removed before the new element is set up.
2006 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
2008 * @return {OO.ui.Element} The element, for chaining
2010 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
2011 var tabIndex
= this.tabIndex
;
2012 // Remove attributes from old $tabIndexed
2013 this.setTabIndex( null );
2014 // Force update of new $tabIndexed
2015 this.$tabIndexed
= $tabIndexed
;
2016 this.tabIndex
= tabIndex
;
2017 return this.updateTabIndex();
2021 * Set the value of the tabindex.
2023 * @param {string|number|null} tabIndex Tabindex value, or `null` for no tabindex
2025 * @return {OO.ui.Element} The element, for chaining
2027 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
2028 tabIndex
= /^-?\d+$/.test( tabIndex
) ? Number( tabIndex
) : null;
2030 if ( this.tabIndex
!== tabIndex
) {
2031 this.tabIndex
= tabIndex
;
2032 this.updateTabIndex();
2039 * Update the `tabindex` attribute, in case of changes to tab index or
2044 * @return {OO.ui.Element} The element, for chaining
2046 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
2047 if ( this.$tabIndexed
) {
2048 if ( this.tabIndex
!== null ) {
2049 // Do not index over disabled elements
2050 this.$tabIndexed
.attr( {
2051 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
2052 // Support: ChromeVox and NVDA
2053 // These do not seem to inherit aria-disabled from parent elements
2054 'aria-disabled': this.isDisabled().toString()
2057 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
2064 * Handle disable events.
2067 * @param {boolean} disabled Element is disabled
2069 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
2070 this.updateTabIndex();
2074 * Get the value of the tabindex.
2076 * @return {number|null} Tabindex value
2078 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
2079 return this.tabIndex
;
2083 * Get an ID of a focusable element of this widget, if any, to be used for `<label for>` value.
2085 * If the element already has an ID then that is returned, otherwise unique ID is
2086 * generated, set on the element, and returned.
2088 * @return {string|null} The ID of the focusable element
2090 OO
.ui
.mixin
.TabIndexedElement
.prototype.getInputId = function () {
2093 if ( !this.$tabIndexed
) {
2096 if ( !this.isLabelableNode( this.$tabIndexed
) ) {
2100 id
= this.$tabIndexed
.attr( 'id' );
2101 if ( id
=== undefined ) {
2102 id
= OO
.ui
.generateElementId();
2103 this.$tabIndexed
.attr( 'id', id
);
2110 * Whether the node is 'labelable' according to the HTML spec
2111 * (i.e., whether it can be interacted with through a `<label for="…">`).
2112 * See: <https://html.spec.whatwg.org/multipage/forms.html#category-label>.
2115 * @param {jQuery} $node
2118 OO
.ui
.mixin
.TabIndexedElement
.prototype.isLabelableNode = function ( $node
) {
2120 labelableTags
= [ 'button', 'meter', 'output', 'progress', 'select', 'textarea' ],
2121 tagName
= $node
.prop( 'tagName' ).toLowerCase();
2123 if ( tagName
=== 'input' && $node
.attr( 'type' ) !== 'hidden' ) {
2126 if ( labelableTags
.indexOf( tagName
) !== -1 ) {
2133 * Focus this element.
2136 * @return {OO.ui.Element} The element, for chaining
2138 OO
.ui
.mixin
.TabIndexedElement
.prototype.focus = function () {
2139 if ( !this.isDisabled() ) {
2140 this.$tabIndexed
.trigger( 'focus' );
2146 * Blur this element.
2149 * @return {OO.ui.Element} The element, for chaining
2151 OO
.ui
.mixin
.TabIndexedElement
.prototype.blur = function () {
2152 this.$tabIndexed
.trigger( 'blur' );
2157 * @inheritdoc OO.ui.Widget
2159 OO
.ui
.mixin
.TabIndexedElement
.prototype.simulateLabelClick = function () {
2164 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
2165 * interface element that can be configured with access keys for keyboard interaction.
2166 * See the [OOUI documentation on MediaWiki] [1] for examples.
2168 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches#Buttons
2174 * @param {Object} [config] Configuration options
2175 * @cfg {jQuery} [$button] The button element created by the class.
2176 * If this configuration is omitted, the button element will use a generated `<a>`.
2177 * @cfg {boolean} [framed=true] Render the button with a frame
2179 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
2180 // Configuration initialization
2181 config
= config
|| {};
2184 this.$button
= null;
2186 this.active
= config
.active
!== undefined && config
.active
;
2187 this.onDocumentMouseUpHandler
= this.onDocumentMouseUp
.bind( this );
2188 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
2189 this.onDocumentKeyUpHandler
= this.onDocumentKeyUp
.bind( this );
2190 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
2191 this.onClickHandler
= this.onClick
.bind( this );
2192 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
2195 this.$element
.addClass( 'oo-ui-buttonElement' );
2196 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
2197 this.setButtonElement( config
.$button
|| $( '<a>' ) );
2202 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
2204 /* Static Properties */
2207 * Cancel mouse down events.
2209 * This property is usually set to `true` to prevent the focus from changing when the button is
2211 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and
2212 * {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} use a value of `false` so that dragging
2213 * behavior is possible and mousedown events can be handled by a parent widget.
2217 * @property {boolean}
2219 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
2224 * A 'click' event is emitted when the button element is clicked.
2232 * Set the button element.
2234 * This method is used to retarget a button mixin so that its functionality applies to
2235 * the specified button element instead of the one created by the class. If a button element
2236 * is already set, the method will remove the mixin’s effect on that element.
2238 * @param {jQuery} $button Element to use as button
2240 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
2241 if ( this.$button
) {
2243 .removeClass( 'oo-ui-buttonElement-button' )
2244 .removeAttr( 'role accesskey' )
2246 mousedown
: this.onMouseDownHandler
,
2247 keydown
: this.onKeyDownHandler
,
2248 click
: this.onClickHandler
,
2249 keypress
: this.onKeyPressHandler
2253 this.$button
= $button
2254 .addClass( 'oo-ui-buttonElement-button' )
2256 mousedown
: this.onMouseDownHandler
,
2257 keydown
: this.onKeyDownHandler
,
2258 click
: this.onClickHandler
,
2259 keypress
: this.onKeyPressHandler
2262 // Add `role="button"` on `<a>` elements, where it's needed
2263 // `toUpperCase()` is added for XHTML documents
2264 if ( this.$button
.prop( 'tagName' ).toUpperCase() === 'A' ) {
2265 this.$button
.attr( 'role', 'button' );
2270 * Handles mouse down events.
2273 * @param {jQuery.Event} e Mouse down event
2274 * @return {undefined/boolean} False to prevent default if event is handled
2276 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
2277 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
2280 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
2281 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
2282 // reliably remove the pressed class
2283 this.getElementDocument().addEventListener( 'mouseup', this.onDocumentMouseUpHandler
, true );
2284 // Prevent change of focus unless specifically configured otherwise
2285 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
2291 * Handles document mouse up events.
2294 * @param {MouseEvent} e Mouse up event
2296 OO
.ui
.mixin
.ButtonElement
.prototype.onDocumentMouseUp = function ( e
) {
2297 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
2300 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
2301 // Stop listening for mouseup, since we only needed this once
2302 this.getElementDocument().removeEventListener( 'mouseup', this.onDocumentMouseUpHandler
, true );
2306 * Handles mouse click events.
2309 * @param {jQuery.Event} e Mouse click event
2311 * @return {undefined/boolean} False to prevent default if event is handled
2313 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
2314 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
2315 if ( this.emit( 'click' ) ) {
2322 * Handles key down events.
2325 * @param {jQuery.Event} e Key down event
2327 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
2328 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2331 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
2332 // Run the keyup handler no matter where the key is when the button is let go, so we can
2333 // reliably remove the pressed class
2334 this.getElementDocument().addEventListener( 'keyup', this.onDocumentKeyUpHandler
, true );
2338 * Handles document key up events.
2341 * @param {KeyboardEvent} e Key up event
2343 OO
.ui
.mixin
.ButtonElement
.prototype.onDocumentKeyUp = function ( e
) {
2344 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2347 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
2348 // Stop listening for keyup, since we only needed this once
2349 this.getElementDocument().removeEventListener( 'keyup', this.onDocumentKeyUpHandler
, true );
2353 * Handles key press events.
2356 * @param {jQuery.Event} e Key press event
2358 * @return {undefined/boolean} False to prevent default if event is handled
2360 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
2361 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
2362 if ( this.emit( 'click' ) ) {
2369 * Check if button has a frame.
2371 * @return {boolean} Button is framed
2373 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
2378 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame
2381 * @param {boolean} [framed] Make button framed, omit to toggle
2383 * @return {OO.ui.Element} The element, for chaining
2385 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
2386 framed
= framed
=== undefined ? !this.framed
: !!framed
;
2387 if ( framed
!== this.framed
) {
2388 this.framed
= framed
;
2390 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
2391 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
2392 this.updateThemeClasses();
2399 * Set the button's active state.
2401 * The active state can be set on:
2403 * - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected
2404 * - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on
2405 * - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page
2408 * @param {boolean} value Make button active
2410 * @return {OO.ui.Element} The element, for chaining
2412 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
2413 this.active
= !!value
;
2414 this.$element
.toggleClass( 'oo-ui-buttonElement-active', this.active
);
2415 this.updateThemeClasses();
2420 * Check if the button is active
2423 * @return {boolean} The button is active
2425 OO
.ui
.mixin
.ButtonElement
.prototype.isActive = function () {
2430 * Any OOUI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
2431 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
2432 * items from the group is done through the interface the class provides.
2433 * For more information, please see the [OOUI documentation on MediaWiki] [1].
2435 * [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Groups
2438 * @mixins OO.EmitterList
2442 * @param {Object} [config] Configuration options
2443 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
2444 * is omitted, the group element will use a generated `<div>`.
2446 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
2447 // Configuration initialization
2448 config
= config
|| {};
2450 // Mixin constructors
2451 OO
.EmitterList
.call( this, config
);
2457 this.setGroupElement( config
.$group
|| $( '<div>' ) );
2462 OO
.mixinClass( OO
.ui
.mixin
.GroupElement
, OO
.EmitterList
);
2469 * A change event is emitted when the set of selected items changes.
2471 * @param {OO.ui.Element[]} items Items currently in the group
2477 * Set the group element.
2479 * If an element is already set, items will be moved to the new element.
2481 * @param {jQuery} $group Element to use as group
2483 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
2486 this.$group
= $group
;
2487 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2488 this.$group
.append( this.items
[ i
].$element
);
2493 * Find an item by its data.
2495 * Only the first item with matching data will be returned. To return all matching items,
2496 * use the #findItemsFromData method.
2498 * @param {Object} data Item data to search for
2499 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2501 OO
.ui
.mixin
.GroupElement
.prototype.findItemFromData = function ( data
) {
2503 hash
= OO
.getHash( data
);
2505 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2506 item
= this.items
[ i
];
2507 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2516 * Find items by their data.
2518 * All items with matching data will be returned. To return only the first match, use the
2519 * #findItemFromData method instead.
2521 * @param {Object} data Item data to search for
2522 * @return {OO.ui.Element[]} Items with equivalent data
2524 OO
.ui
.mixin
.GroupElement
.prototype.findItemsFromData = function ( data
) {
2526 hash
= OO
.getHash( data
),
2529 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2530 item
= this.items
[ i
];
2531 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2540 * Add items to the group.
2542 * Items will be added to the end of the group array unless the optional `index` parameter
2543 * specifies a different insertion point. Adding an existing item will move it to the end of the
2544 * array or the point specified by the `index`.
2546 * @param {OO.ui.Element[]} items An array of items to add to the group
2547 * @param {number} [index] Index of the insertion point
2549 * @return {OO.ui.Element} The element, for chaining
2551 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
2553 if ( items
.length
=== 0 ) {
2558 OO
.EmitterList
.prototype.addItems
.call( this, items
, index
);
2560 this.emit( 'change', this.getItems() );
2567 OO
.ui
.mixin
.GroupElement
.prototype.moveItem = function ( items
, newIndex
) {
2568 // insertItemElements expects this.items to not have been modified yet, so call before the mixin
2569 this.insertItemElements( items
, newIndex
);
2572 newIndex
= OO
.EmitterList
.prototype.moveItem
.call( this, items
, newIndex
);
2580 OO
.ui
.mixin
.GroupElement
.prototype.insertItem = function ( item
, index
) {
2581 item
.setElementGroup( this );
2582 this.insertItemElements( item
, index
);
2585 index
= OO
.EmitterList
.prototype.insertItem
.call( this, item
, index
);
2591 * Insert elements into the group
2594 * @param {OO.ui.Element} itemWidget Item to insert
2595 * @param {number} index Insertion index
2597 OO
.ui
.mixin
.GroupElement
.prototype.insertItemElements = function ( itemWidget
, index
) {
2598 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
2599 this.$group
.append( itemWidget
.$element
);
2600 } else if ( index
=== 0 ) {
2601 this.$group
.prepend( itemWidget
.$element
);
2603 this.items
[ index
].$element
.before( itemWidget
.$element
);
2608 * Remove the specified items from a group.
2610 * Removed items are detached (not removed) from the DOM so that they may be reused.
2611 * To remove all items from a group, you may wish to use the #clearItems method instead.
2613 * @param {OO.ui.Element[]} items An array of items to remove
2615 * @return {OO.ui.Element} The element, for chaining
2617 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
2618 var i
, len
, item
, index
;
2620 if ( items
.length
=== 0 ) {
2624 // Remove specific items elements
2625 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
2627 index
= this.items
.indexOf( item
);
2628 if ( index
!== -1 ) {
2629 item
.setElementGroup( null );
2630 item
.$element
.detach();
2635 OO
.EmitterList
.prototype.removeItems
.call( this, items
);
2637 this.emit( 'change', this.getItems() );
2642 * Clear all items from the group.
2644 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2645 * To remove only a subset of items from a group, use the #removeItems method.
2648 * @return {OO.ui.Element} The element, for chaining
2650 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
2653 // Remove all item elements
2654 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2655 this.items
[ i
].setElementGroup( null );
2656 this.items
[ i
].$element
.detach();
2660 OO
.EmitterList
.prototype.clearItems
.call( this );
2662 this.emit( 'change', this.getItems() );
2667 * LabelElement is often mixed into other classes to generate a label, which
2668 * helps identify the function of an interface element.
2669 * See the [OOUI documentation on MediaWiki] [1] for more information.
2671 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
2677 * @param {Object} [config] Configuration options
2678 * @cfg {jQuery} [$label] The label element created by the class. If this
2679 * configuration is omitted, the label element will use a generated `<span>`.
2680 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be
2681 * specified as a plaintext string, a jQuery selection of elements, or a function that will
2682 * produce a string in the future. See the [OOUI documentation on MediaWiki] [2] for examples.
2683 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
2684 * @cfg {boolean} [invisibleLabel] Whether the label should be visually hidden (but still
2685 * accessible to screen-readers).
2687 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
2688 // Configuration initialization
2689 config
= config
|| {};
2694 this.invisibleLabel
= null;
2697 this.setLabel( config
.label
|| this.constructor.static.label
);
2698 this.setLabelElement( config
.$label
|| $( '<span>' ) );
2699 this.setInvisibleLabel( config
.invisibleLabel
);
2704 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
2709 * @event labelChange
2710 * @param {string} value
2713 /* Static Properties */
2716 * The label text. The label can be specified as a plaintext string, a function that will
2717 * produce a string in the future, or `null` for no label. The static value will
2718 * be overridden if a label is specified with the #label config option.
2722 * @property {string|Function|null}
2724 OO
.ui
.mixin
.LabelElement
.static.label
= null;
2726 /* Static methods */
2729 * Highlight the first occurrence of the query in the given text
2731 * @param {string} text Text
2732 * @param {string} query Query to find
2733 * @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
2734 * @return {jQuery} Text with the first match of the query
2735 * sub-string wrapped in highlighted span
2737 OO
.ui
.mixin
.LabelElement
.static.highlightQuery = function ( text
, query
, compare
) {
2740 $result
= $( '<span>' );
2744 qLen
= query
.length
;
2745 for ( i
= 0; offset
=== -1 && i
<= tLen
- qLen
; i
++ ) {
2746 if ( compare( query
, text
.slice( i
, i
+ qLen
) ) === 0 ) {
2751 offset
= text
.toLowerCase().indexOf( query
.toLowerCase() );
2754 if ( !query
.length
|| offset
=== -1 ) {
2755 $result
.text( text
);
2758 document
.createTextNode( text
.slice( 0, offset
) ),
2760 .addClass( 'oo-ui-labelElement-label-highlight' )
2761 .text( text
.slice( offset
, offset
+ query
.length
) ),
2762 document
.createTextNode( text
.slice( offset
+ query
.length
) )
2765 return $result
.contents();
2771 * Set the label element.
2773 * If an element is already set, it will be cleaned up before setting up the new element.
2775 * @param {jQuery} $label Element to use as label
2777 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
2778 if ( this.$label
) {
2779 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
2782 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
2783 this.setLabelContent( this.label
);
2789 * An empty string will result in the label being hidden. A string containing only whitespace will
2790 * be converted to a single ` `.
2792 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that
2793 * returns nodes or text; or null for no label
2795 * @return {OO.ui.Element} The element, for chaining
2797 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
2798 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
2799 label
= ( ( typeof label
=== 'string' || label
instanceof $ ) && label
.length
) || ( label
instanceof OO
.ui
.HtmlSnippet
&& label
.toString().length
) ? label
: null;
2801 if ( this.label
!== label
) {
2802 if ( this.$label
) {
2803 this.setLabelContent( label
);
2806 this.emit( 'labelChange' );
2809 this.$element
.toggleClass( 'oo-ui-labelElement', !!this.label
&& !this.invisibleLabel
);
2815 * Set whether the label should be visually hidden (but still accessible to screen-readers).
2817 * @param {boolean} invisibleLabel
2819 * @return {OO.ui.Element} The element, for chaining
2821 OO
.ui
.mixin
.LabelElement
.prototype.setInvisibleLabel = function ( invisibleLabel
) {
2822 invisibleLabel
= !!invisibleLabel
;
2824 if ( this.invisibleLabel
!== invisibleLabel
) {
2825 this.invisibleLabel
= invisibleLabel
;
2826 this.emit( 'labelChange' );
2829 this.$label
.toggleClass( 'oo-ui-labelElement-invisible', this.invisibleLabel
);
2830 // Pretend that there is no label, a lot of CSS has been written with this assumption
2831 this.$element
.toggleClass( 'oo-ui-labelElement', !!this.label
&& !this.invisibleLabel
);
2837 * Set the label as plain text with a highlighted query
2839 * @param {string} text Text label to set
2840 * @param {string} query Substring of text to highlight
2841 * @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
2843 * @return {OO.ui.Element} The element, for chaining
2845 OO
.ui
.mixin
.LabelElement
.prototype.setHighlightedQuery = function ( text
, query
, compare
) {
2846 return this.setLabel( this.constructor.static.highlightQuery( text
, query
, compare
) );
2852 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
2853 * text; or null for no label
2855 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
2860 * Set the content of the label.
2862 * Do not call this method until after the label element has been set by #setLabelElement.
2865 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
2866 * text; or null for no label
2868 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
2869 if ( typeof label
=== 'string' ) {
2870 if ( label
.match( /^\s*$/ ) ) {
2871 // Convert whitespace only string to a single non-breaking space
2872 this.$label
.html( ' ' );
2874 this.$label
.text( label
);
2876 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
2877 this.$label
.html( label
.toString() );
2878 } else if ( label
instanceof $ ) {
2879 this.$label
.empty().append( label
);
2881 this.$label
.empty();
2886 * IconElement is often mixed into other classes to generate an icon.
2887 * Icons are graphics, about the size of normal text. They are used to aid the user
2888 * in locating a control or to convey information in a space-efficient way. See the
2889 * [OOUI documentation on MediaWiki] [1] for a list of icons
2890 * included in the library.
2892 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
2898 * @param {Object} [config] Configuration options
2899 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2900 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2901 * the icon element be set to an existing icon instead of the one generated by this class, set a
2902 * value using a jQuery selection. For example:
2904 * // Use a <div> tag instead of a <span>
2905 * $icon: $( '<div>' )
2906 * // Use an existing icon element instead of the one generated by the class
2907 * $icon: this.$element
2908 * // Use an icon element from a child widget
2909 * $icon: this.childwidget.$element
2910 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a
2911 * map of symbolic names. A map is used for i18n purposes and contains a `default` icon
2912 * name and additional names keyed by language code. The `default` name is used when no icon is
2913 * keyed by the user's language.
2915 * Example of an i18n map:
2917 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2918 * See the [OOUI documentation on MediaWiki] [2] for a list of icons included in the library.
2919 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
2921 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
2922 // Configuration initialization
2923 config
= config
|| {};
2930 this.setIcon( config
.icon
|| this.constructor.static.icon
);
2931 this.setIconElement( config
.$icon
|| $( '<span>' ) );
2936 OO
.initClass( OO
.ui
.mixin
.IconElement
);
2938 /* Static Properties */
2941 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map
2942 * is used for i18n purposes and contains a `default` icon name and additional names keyed by
2943 * language code. The `default` name is used when no icon is keyed by the user's language.
2945 * Example of an i18n map:
2947 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2949 * Note: the static property will be overridden if the #icon configuration is used.
2953 * @property {Object|string}
2955 OO
.ui
.mixin
.IconElement
.static.icon
= null;
2958 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2959 * function that returns title text, or `null` for no title.
2961 * The static property will be overridden if the #iconTitle configuration is used.
2965 * @property {string|Function|null}
2967 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
2972 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2973 * applies to the specified icon element instead of the one created by the class. If an icon
2974 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2975 * and mixin methods will no longer affect the element.
2977 * @param {jQuery} $icon Element to use as icon
2979 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
2982 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
2983 .removeAttr( 'title' );
2987 .addClass( 'oo-ui-iconElement-icon' )
2988 .toggleClass( 'oo-ui-iconElement-noIcon', !this.icon
)
2989 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
2990 if ( this.iconTitle
!== null ) {
2991 this.$icon
.attr( 'title', this.iconTitle
);
2994 this.updateThemeClasses();
2998 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
2999 * The icon parameter can also be set to a map of icon names. See the #icon config setting
3002 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
3003 * by language code, or `null` to remove the icon.
3005 * @return {OO.ui.Element} The element, for chaining
3007 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
3008 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
3009 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
3011 if ( this.icon
!== icon
) {
3013 if ( this.icon
!== null ) {
3014 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
3016 if ( icon
!== null ) {
3017 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
3023 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
3025 this.$icon
.toggleClass( 'oo-ui-iconElement-noIcon', !this.icon
);
3027 this.updateThemeClasses();
3033 * Get the symbolic name of the icon.
3035 * @return {string} Icon name
3037 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
3042 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
3044 * @return {string} Icon title text
3047 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
3048 return this.iconTitle
;
3052 * IndicatorElement is often mixed into other classes to generate an indicator.
3053 * Indicators are small graphics that are generally used in two ways:
3055 * - To draw attention to the status of an item. For example, an indicator might be
3056 * used to show that an item in a list has errors that need to be resolved.
3057 * - To clarify the function of a control that acts in an exceptional way (a button
3058 * that opens a menu instead of performing an action directly, for example).
3060 * For a list of indicators included in the library, please see the
3061 * [OOUI documentation on MediaWiki] [1].
3063 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3069 * @param {Object} [config] Configuration options
3070 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
3071 * configuration is omitted, the indicator element will use a generated `<span>`.
3072 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3073 * See the [OOUI documentation on MediaWiki][2] for a list of indicators included
3075 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3077 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
3078 // Configuration initialization
3079 config
= config
|| {};
3082 this.$indicator
= null;
3083 this.indicator
= null;
3086 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
3087 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
3092 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
3094 /* Static Properties */
3097 * Symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3098 * The static property will be overridden if the #indicator configuration is used.
3102 * @property {string|null}
3104 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
3107 * A text string used as the indicator title, a function that returns title text, or `null`
3108 * for no title. The static property will be overridden if the #indicatorTitle configuration is
3113 * @property {string|Function|null}
3115 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
3120 * Set the indicator element.
3122 * If an element is already set, it will be cleaned up before setting up the new element.
3124 * @param {jQuery} $indicator Element to use as indicator
3126 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
3127 if ( this.$indicator
) {
3129 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
3130 .removeAttr( 'title' );
3133 this.$indicator
= $indicator
3134 .addClass( 'oo-ui-indicatorElement-indicator' )
3135 .toggleClass( 'oo-ui-indicatorElement-noIndicator', !this.indicator
)
3136 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
3137 if ( this.indicatorTitle
!== null ) {
3138 this.$indicator
.attr( 'title', this.indicatorTitle
);
3141 this.updateThemeClasses();
3145 * Set the indicator by its symbolic name: ‘clear’, ‘down’, ‘required’, ‘search’, ‘up’. Use `null`
3146 * to remove the indicator.
3148 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
3150 * @return {OO.ui.Element} The element, for chaining
3152 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
3153 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
3155 if ( this.indicator
!== indicator
) {
3156 if ( this.$indicator
) {
3157 if ( this.indicator
!== null ) {
3158 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
3160 if ( indicator
!== null ) {
3161 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
3164 this.indicator
= indicator
;
3167 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
3168 if ( this.$indicator
) {
3169 this.$indicator
.toggleClass( 'oo-ui-indicatorElement-noIndicator', !this.indicator
);
3171 this.updateThemeClasses();
3177 * Get the symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3179 * @return {string} Symbolic name of indicator
3181 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
3182 return this.indicator
;
3186 * Get the indicator title.
3188 * The title is displayed when a user moves the mouse over the indicator.
3190 * @return {string} Indicator title text
3193 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
3194 return this.indicatorTitle
;
3198 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
3199 * additional functionality to an element created by another class. The class provides
3200 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
3201 * which are used to customize the look and feel of a widget to better describe its
3202 * importance and functionality.
3204 * The library currently contains the following styling flags for general use:
3206 * - **progressive**: Progressive styling is applied to convey that the widget will move the user
3207 * forward in a process.
3208 * - **destructive**: Destructive styling is applied to convey that the widget will remove
3211 * The flags affect the appearance of the buttons:
3214 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
3215 * var button1 = new OO.ui.ButtonWidget( {
3216 * label: 'Progressive',
3217 * flags: 'progressive'
3219 * button2 = new OO.ui.ButtonWidget( {
3220 * label: 'Destructive',
3221 * flags: 'destructive'
3223 * $( document.body ).append( button1.$element, button2.$element );
3225 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an
3226 * action, use these flags: **primary** and **safe**.
3227 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
3229 * [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
3235 * @param {Object} [config] Configuration options
3236 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'progressive' or 'primary')
3238 * Please see the [OOUI documentation on MediaWiki] [2] for more information about available flags.
3239 * [2]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
3240 * @cfg {jQuery} [$flagged] The flagged element. By default,
3241 * the flagged functionality is applied to the element created by the class ($element).
3242 * If a different element is specified, the flagged functionality will be applied to it instead.
3244 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
3245 // Configuration initialization
3246 config
= config
|| {};
3250 this.$flagged
= null;
3253 this.setFlags( config
.flags
);
3254 this.setFlaggedElement( config
.$flagged
|| this.$element
);
3261 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
3262 * parameter contains the name of each modified flag and indicates whether it was
3265 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
3266 * that the flag was added, `false` that the flag was removed.
3272 * Set the flagged element.
3274 * This method is used to retarget a flagged mixin so that its functionality applies to the
3275 * specified element.
3276 * If an element is already set, the method will remove the mixin’s effect on that element.
3278 * @param {jQuery} $flagged Element that should be flagged
3280 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
3281 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
3282 return 'oo-ui-flaggedElement-' + flag
;
3285 if ( this.$flagged
) {
3286 this.$flagged
.removeClass( classNames
);
3289 this.$flagged
= $flagged
.addClass( classNames
);
3293 * Check if the specified flag is set.
3295 * @param {string} flag Name of flag
3296 * @return {boolean} The flag is set
3298 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
3299 // This may be called before the constructor, thus before this.flags is set
3300 return this.flags
&& ( flag
in this.flags
);
3304 * Get the names of all flags set.
3306 * @return {string[]} Flag names
3308 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
3309 // This may be called before the constructor, thus before this.flags is set
3310 return Object
.keys( this.flags
|| {} );
3317 * @return {OO.ui.Element} The element, for chaining
3320 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
3321 var flag
, className
,
3324 classPrefix
= 'oo-ui-flaggedElement-';
3326 for ( flag
in this.flags
) {
3327 className
= classPrefix
+ flag
;
3328 changes
[ flag
] = false;
3329 delete this.flags
[ flag
];
3330 remove
.push( className
);
3333 if ( this.$flagged
) {
3334 this.$flagged
.removeClass( remove
);
3337 this.updateThemeClasses();
3338 this.emit( 'flag', changes
);
3344 * Add one or more flags.
3346 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
3347 * or an object keyed by flag name with a boolean value that indicates whether the flag should
3348 * be added (`true`) or removed (`false`).
3350 * @return {OO.ui.Element} The element, for chaining
3353 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
3354 var i
, len
, flag
, className
,
3358 classPrefix
= 'oo-ui-flaggedElement-';
3360 if ( typeof flags
=== 'string' ) {
3361 className
= classPrefix
+ flags
;
3363 if ( !this.flags
[ flags
] ) {
3364 this.flags
[ flags
] = true;
3365 add
.push( className
);
3367 } else if ( Array
.isArray( flags
) ) {
3368 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
3370 className
= classPrefix
+ flag
;
3372 if ( !this.flags
[ flag
] ) {
3373 changes
[ flag
] = true;
3374 this.flags
[ flag
] = true;
3375 add
.push( className
);
3378 } else if ( OO
.isPlainObject( flags
) ) {
3379 for ( flag
in flags
) {
3380 className
= classPrefix
+ flag
;
3381 if ( flags
[ flag
] ) {
3383 if ( !this.flags
[ flag
] ) {
3384 changes
[ flag
] = true;
3385 this.flags
[ flag
] = true;
3386 add
.push( className
);
3390 if ( this.flags
[ flag
] ) {
3391 changes
[ flag
] = false;
3392 delete this.flags
[ flag
];
3393 remove
.push( className
);
3399 if ( this.$flagged
) {
3402 .removeClass( remove
);
3405 this.updateThemeClasses();
3406 this.emit( 'flag', changes
);
3412 * TitledElement is mixed into other classes to provide a `title` attribute.
3413 * Titles are rendered by the browser and are made visible when the user moves
3414 * the mouse over the element. Titles are not visible on touch devices.
3417 * // TitledElement provides a `title` attribute to the
3418 * // ButtonWidget class.
3419 * var button = new OO.ui.ButtonWidget( {
3420 * label: 'Button with Title',
3421 * title: 'I am a button'
3423 * $( document.body ).append( button.$element );
3429 * @param {Object} [config] Configuration options
3430 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
3431 * If this config is omitted, the title functionality is applied to $element, the
3432 * element created by the class.
3433 * @cfg {string|Function} [title] The title text or a function that returns text. If
3434 * this config is omitted, the value of the {@link #static-title static title} property is used.
3436 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
3437 // Configuration initialization
3438 config
= config
|| {};
3441 this.$titled
= null;
3445 this.setTitle( config
.title
!== undefined ? config
.title
: this.constructor.static.title
);
3446 this.setTitledElement( config
.$titled
|| this.$element
);
3451 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
3453 /* Static Properties */
3456 * The title text, a function that returns text, or `null` for no title. The value of the static
3457 * property is overridden if the #title config option is used.
3461 * @property {string|Function|null}
3463 OO
.ui
.mixin
.TitledElement
.static.title
= null;
3468 * Set the titled element.
3470 * This method is used to retarget a TitledElement mixin so that its functionality applies to the
3471 * specified element.
3472 * If an element is already set, the mixin’s effect on that element is removed before the new
3473 * element is set up.
3475 * @param {jQuery} $titled Element that should use the 'titled' functionality
3477 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
3478 if ( this.$titled
) {
3479 this.$titled
.removeAttr( 'title' );
3482 this.$titled
= $titled
;
3491 * @param {string|Function|null} title Title text, a function that returns text, or `null`
3494 * @return {OO.ui.Element} The element, for chaining
3496 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
3497 title
= typeof title
=== 'function' ? OO
.ui
.resolveMsg( title
) : title
;
3498 title
= ( typeof title
=== 'string' && title
.length
) ? title
: null;
3500 if ( this.title
!== title
) {
3509 * Update the title attribute, in case of changes to title or accessKey.
3513 * @return {OO.ui.Element} The element, for chaining
3515 OO
.ui
.mixin
.TitledElement
.prototype.updateTitle = function () {
3516 var title
= this.getTitle();
3517 if ( this.$titled
) {
3518 if ( title
!== null ) {
3519 // Only if this is an AccessKeyedElement
3520 if ( this.formatTitleWithAccessKey
) {
3521 title
= this.formatTitleWithAccessKey( title
);
3523 this.$titled
.attr( 'title', title
);
3525 this.$titled
.removeAttr( 'title' );
3534 * @return {string} Title string
3536 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
3541 * AccessKeyedElement is mixed into other classes to provide an `accesskey` HTML attribute.
3542 * Access keys allow an user to go to a specific element by using
3543 * a shortcut combination of a browser specific keys + the key
3547 * // AccessKeyedElement provides an `accesskey` attribute to the
3548 * // ButtonWidget class.
3549 * var button = new OO.ui.ButtonWidget( {
3550 * label: 'Button with access key',
3553 * $( document.body ).append( button.$element );
3559 * @param {Object} [config] Configuration options
3560 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3561 * If this config is omitted, the access key functionality is applied to $element, the
3562 * element created by the class.
3563 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3564 * this config is omitted, no access key will be added.
3566 OO
.ui
.mixin
.AccessKeyedElement
= function OoUiMixinAccessKeyedElement( config
) {
3567 // Configuration initialization
3568 config
= config
|| {};
3571 this.$accessKeyed
= null;
3572 this.accessKey
= null;
3575 this.setAccessKey( config
.accessKey
|| null );
3576 this.setAccessKeyedElement( config
.$accessKeyed
|| this.$element
);
3578 // If this is also a TitledElement and it initialized before we did, we may have
3579 // to update the title with the access key
3580 if ( this.updateTitle
) {
3587 OO
.initClass( OO
.ui
.mixin
.AccessKeyedElement
);
3589 /* Static Properties */
3592 * The access key, a function that returns a key, or `null` for no access key.
3596 * @property {string|Function|null}
3598 OO
.ui
.mixin
.AccessKeyedElement
.static.accessKey
= null;
3603 * Set the access keyed element.
3605 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to
3606 * the specified element.
3607 * If an element is already set, the mixin's effect on that element is removed before the new
3608 * element is set up.
3610 * @param {jQuery} $accessKeyed Element that should use the 'access keyed' functionality
3612 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKeyedElement = function ( $accessKeyed
) {
3613 if ( this.$accessKeyed
) {
3614 this.$accessKeyed
.removeAttr( 'accesskey' );
3617 this.$accessKeyed
= $accessKeyed
;
3618 if ( this.accessKey
) {
3619 this.$accessKeyed
.attr( 'accesskey', this.accessKey
);
3626 * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no
3629 * @return {OO.ui.Element} The element, for chaining
3631 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKey = function ( accessKey
) {
3632 accessKey
= typeof accessKey
=== 'string' ? OO
.ui
.resolveMsg( accessKey
) : null;
3634 if ( this.accessKey
!== accessKey
) {
3635 if ( this.$accessKeyed
) {
3636 if ( accessKey
!== null ) {
3637 this.$accessKeyed
.attr( 'accesskey', accessKey
);
3639 this.$accessKeyed
.removeAttr( 'accesskey' );
3642 this.accessKey
= accessKey
;
3644 // Only if this is a TitledElement
3645 if ( this.updateTitle
) {
3656 * @return {string} accessKey string
3658 OO
.ui
.mixin
.AccessKeyedElement
.prototype.getAccessKey = function () {
3659 return this.accessKey
;
3663 * Add information about the access key to the element's tooltip label.
3664 * (This is only public for hacky usage in FieldLayout.)
3666 * @param {string} title Tooltip label for `title` attribute
3669 OO
.ui
.mixin
.AccessKeyedElement
.prototype.formatTitleWithAccessKey = function ( title
) {
3672 if ( !this.$accessKeyed
) {
3673 // Not initialized yet; the constructor will call updateTitle() which will rerun this
3677 // Use jquery.accessKeyLabel if available to show modifiers, otherwise just display the
3679 if ( $.fn
.updateTooltipAccessKeys
&& $.fn
.updateTooltipAccessKeys
.getAccessKeyLabel
) {
3680 accessKey
= $.fn
.updateTooltipAccessKeys
.getAccessKeyLabel( this.$accessKeyed
[ 0 ] );
3682 accessKey
= this.getAccessKey();
3685 title
+= ' [' + accessKey
+ ']';
3691 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3692 * feels, and functionality can be customized via the class’s configuration options
3693 * and methods. Please see the [OOUI documentation on MediaWiki] [1] for more information
3696 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches
3699 * // A button widget.
3700 * var button = new OO.ui.ButtonWidget( {
3701 * label: 'Button with Icon',
3705 * $( document.body ).append( button.$element );
3707 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3710 * @extends OO.ui.Widget
3711 * @mixins OO.ui.mixin.ButtonElement
3712 * @mixins OO.ui.mixin.IconElement
3713 * @mixins OO.ui.mixin.IndicatorElement
3714 * @mixins OO.ui.mixin.LabelElement
3715 * @mixins OO.ui.mixin.TitledElement
3716 * @mixins OO.ui.mixin.FlaggedElement
3717 * @mixins OO.ui.mixin.TabIndexedElement
3718 * @mixins OO.ui.mixin.AccessKeyedElement
3721 * @param {Object} [config] Configuration options
3722 * @cfg {boolean} [active=false] Whether button should be shown as active
3723 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3724 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3725 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3727 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
3728 // Configuration initialization
3729 config
= config
|| {};
3731 // Parent constructor
3732 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
3734 // Mixin constructors
3735 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
3736 OO
.ui
.mixin
.IconElement
.call( this, config
);
3737 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
3738 OO
.ui
.mixin
.LabelElement
.call( this, config
);
3739 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {
3740 $titled
: this.$button
3742 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
3743 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {
3744 $tabIndexed
: this.$button
3746 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {
3747 $accessKeyed
: this.$button
3753 this.noFollow
= false;
3756 this.connect( this, {
3757 disable
: 'onDisable'
3761 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
3763 .addClass( 'oo-ui-buttonWidget' )
3764 .append( this.$button
);
3765 this.setActive( config
.active
);
3766 this.setHref( config
.href
);
3767 this.setTarget( config
.target
);
3768 this.setNoFollow( config
.noFollow
);
3773 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
3774 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
3775 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
3776 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
3777 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
3778 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
3779 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
3780 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
3781 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
3783 /* Static Properties */
3789 OO
.ui
.ButtonWidget
.static.cancelButtonMouseDownEvents
= false;
3795 OO
.ui
.ButtonWidget
.static.tagName
= 'span';
3800 * Get hyperlink location.
3802 * @return {string} Hyperlink location
3804 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
3809 * Get hyperlink target.
3811 * @return {string} Hyperlink target
3813 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
3818 * Get search engine traversal hint.
3820 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3822 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
3823 return this.noFollow
;
3827 * Set hyperlink location.
3829 * @param {string|null} href Hyperlink location, null to remove
3831 * @return {OO.ui.Widget} The widget, for chaining
3833 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
3834 href
= typeof href
=== 'string' ? href
: null;
3835 if ( href
!== null && !OO
.ui
.isSafeUrl( href
) ) {
3839 if ( href
!== this.href
) {
3848 * Update the `href` attribute, in case of changes to href or
3853 * @return {OO.ui.Widget} The widget, for chaining
3855 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
3856 if ( this.href
!== null && !this.isDisabled() ) {
3857 this.$button
.attr( 'href', this.href
);
3859 this.$button
.removeAttr( 'href' );
3866 * Handle disable events.
3869 * @param {boolean} disabled Element is disabled
3871 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
3876 * Set hyperlink target.
3878 * @param {string|null} target Hyperlink target, null to remove
3879 * @return {OO.ui.Widget} The widget, for chaining
3881 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
3882 target
= typeof target
=== 'string' ? target
: null;
3884 if ( target
!== this.target
) {
3885 this.target
= target
;
3886 if ( target
!== null ) {
3887 this.$button
.attr( 'target', target
);
3889 this.$button
.removeAttr( 'target' );
3897 * Set search engine traversal hint.
3899 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3900 * @return {OO.ui.Widget} The widget, for chaining
3902 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
3903 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
3905 if ( noFollow
!== this.noFollow
) {
3906 this.noFollow
= noFollow
;
3908 this.$button
.attr( 'rel', 'nofollow' );
3910 this.$button
.removeAttr( 'rel' );
3917 // Override method visibility hints from ButtonElement
3928 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3929 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3930 * removed, and cleared from the group.
3933 * // A ButtonGroupWidget with two buttons.
3934 * var button1 = new OO.ui.PopupButtonWidget( {
3935 * label: 'Select a category',
3938 * $content: $( '<p>List of categories…</p>' ),
3943 * button2 = new OO.ui.ButtonWidget( {
3946 * buttonGroup = new OO.ui.ButtonGroupWidget( {
3947 * items: [ button1, button2 ]
3949 * $( document.body ).append( buttonGroup.$element );
3952 * @extends OO.ui.Widget
3953 * @mixins OO.ui.mixin.GroupElement
3954 * @mixins OO.ui.mixin.TitledElement
3957 * @param {Object} [config] Configuration options
3958 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
3960 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
3961 // Configuration initialization
3962 config
= config
|| {};
3964 // Parent constructor
3965 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
3967 // Mixin constructors
3968 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {
3969 $group
: this.$element
3971 OO
.ui
.mixin
.TitledElement
.call( this, config
);
3974 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
3975 if ( Array
.isArray( config
.items
) ) {
3976 this.addItems( config
.items
);
3982 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
3983 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
3984 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.TitledElement
);
3986 /* Static Properties */
3992 OO
.ui
.ButtonGroupWidget
.static.tagName
= 'span';
4000 * @return {OO.ui.Widget} The widget, for chaining
4002 OO
.ui
.ButtonGroupWidget
.prototype.focus = function () {
4003 if ( !this.isDisabled() ) {
4004 if ( this.items
[ 0 ] ) {
4005 this.items
[ 0 ].focus();
4014 OO
.ui
.ButtonGroupWidget
.prototype.simulateLabelClick = function () {
4019 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}.
4020 * In general, IconWidgets should be used with OO.ui.LabelWidget, which creates a label that
4021 * identifies the icon’s function. See the [OOUI documentation on MediaWiki] [1]
4022 * for a list of icons included in the library.
4025 * // An IconWidget with a label via LabelWidget.
4026 * var myIcon = new OO.ui.IconWidget( {
4030 * // Create a label.
4031 * iconLabel = new OO.ui.LabelWidget( {
4034 * $( document.body ).append( myIcon.$element, iconLabel.$element );
4036 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
4039 * @extends OO.ui.Widget
4040 * @mixins OO.ui.mixin.IconElement
4041 * @mixins OO.ui.mixin.TitledElement
4042 * @mixins OO.ui.mixin.LabelElement
4043 * @mixins OO.ui.mixin.FlaggedElement
4046 * @param {Object} [config] Configuration options
4048 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
4049 // Configuration initialization
4050 config
= config
|| {};
4052 // Parent constructor
4053 OO
.ui
.IconWidget
.parent
.call( this, config
);
4055 // Mixin constructors
4056 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {
4057 $icon
: this.$element
4059 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {
4060 $titled
: this.$element
4062 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {
4063 $label
: this.$element
,
4064 invisibleLabel
: true
4066 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {
4067 $flagged
: this.$element
4071 this.$element
.addClass( 'oo-ui-iconWidget' );
4072 // Remove class added by LabelElement initialization. It causes unexpected CSS to apply when
4073 // nested in other widgets, because this widget used to not mix in LabelElement.
4074 this.$element
.removeClass( 'oo-ui-labelElement-label' );
4079 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
4080 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
4081 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
4082 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.LabelElement
);
4083 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
4085 /* Static Properties */
4091 OO
.ui
.IconWidget
.static.tagName
= 'span';
4094 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
4095 * attention to the status of an item or to clarify the function within a control. For a list of
4096 * indicators included in the library, please see the [OOUI documentation on MediaWiki][1].
4099 * // An indicator widget.
4100 * var indicator1 = new OO.ui.IndicatorWidget( {
4101 * indicator: 'required'
4103 * // Create a fieldset layout to add a label.
4104 * fieldset = new OO.ui.FieldsetLayout();
4105 * fieldset.addItems( [
4106 * new OO.ui.FieldLayout( indicator1, {
4107 * label: 'A required indicator:'
4110 * $( document.body ).append( fieldset.$element );
4112 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
4115 * @extends OO.ui.Widget
4116 * @mixins OO.ui.mixin.IndicatorElement
4117 * @mixins OO.ui.mixin.TitledElement
4118 * @mixins OO.ui.mixin.LabelElement
4121 * @param {Object} [config] Configuration options
4123 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
4124 // Configuration initialization
4125 config
= config
|| {};
4127 // Parent constructor
4128 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
4130 // Mixin constructors
4131 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {
4132 $indicator
: this.$element
4134 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {
4135 $titled
: this.$element
4137 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {
4138 $label
: this.$element
,
4139 invisibleLabel
: true
4143 this.$element
.addClass( 'oo-ui-indicatorWidget' );
4144 // Remove class added by LabelElement initialization. It causes unexpected CSS to apply when
4145 // nested in other widgets, because this widget used to not mix in LabelElement.
4146 this.$element
.removeClass( 'oo-ui-labelElement-label' );
4151 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
4152 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
4153 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
4154 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.LabelElement
);
4156 /* Static Properties */
4162 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
4165 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
4166 * be configured with a `label` option that is set to a string, a label node, or a function:
4168 * - String: a plaintext string
4169 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
4170 * label that includes a link or special styling, such as a gray color or additional
4171 * graphical elements.
4172 * - Function: a function that will produce a string in the future. Functions are used
4173 * in cases where the value of the label is not currently defined.
4175 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget},
4176 * which will come into focus when the label is clicked.
4179 * // Two LabelWidgets.
4180 * var label1 = new OO.ui.LabelWidget( {
4181 * label: 'plaintext label'
4183 * label2 = new OO.ui.LabelWidget( {
4184 * label: $( '<a>' ).attr( 'href', 'default.html' ).text( 'jQuery label' )
4186 * // Create a fieldset layout with fields for each example.
4187 * fieldset = new OO.ui.FieldsetLayout();
4188 * fieldset.addItems( [
4189 * new OO.ui.FieldLayout( label1 ),
4190 * new OO.ui.FieldLayout( label2 )
4192 * $( document.body ).append( fieldset.$element );
4195 * @extends OO.ui.Widget
4196 * @mixins OO.ui.mixin.LabelElement
4197 * @mixins OO.ui.mixin.TitledElement
4200 * @param {Object} [config] Configuration options
4201 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
4202 * Clicking the label will focus the specified input field.
4204 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
4205 // Configuration initialization
4206 config
= config
|| {};
4208 // Parent constructor
4209 OO
.ui
.LabelWidget
.parent
.call( this, config
);
4211 // Mixin constructors
4212 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {
4213 $label
: this.$element
4215 OO
.ui
.mixin
.TitledElement
.call( this, config
);
4218 this.input
= config
.input
;
4222 if ( this.input
.getInputId() ) {
4223 this.$element
.attr( 'for', this.input
.getInputId() );
4225 this.$label
.on( 'click', function () {
4226 this.input
.simulateLabelClick();
4230 this.$element
.addClass( 'oo-ui-labelWidget' );
4235 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
4236 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
4237 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
4239 /* Static Properties */
4245 OO
.ui
.LabelWidget
.static.tagName
= 'label';
4248 * PendingElement is a mixin that is used to create elements that notify users that something is
4249 * happening and that they should wait before proceeding. The pending state is visually represented
4250 * with a pending texture that appears in the head of a pending
4251 * {@link OO.ui.ProcessDialog process dialog} or in the input field of a
4252 * {@link OO.ui.TextInputWidget text input widget}.
4254 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked
4255 * as pending, but only when used in {@link OO.ui.MessageDialog message dialogs}. The behavior is
4256 * not currently supported for action widgets used in process dialogs.
4259 * function MessageDialog( config ) {
4260 * MessageDialog.parent.call( this, config );
4262 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
4264 * MessageDialog.static.name = 'myMessageDialog';
4265 * MessageDialog.static.actions = [
4266 * { action: 'save', label: 'Done', flags: 'primary' },
4267 * { label: 'Cancel', flags: 'safe' }
4270 * MessageDialog.prototype.initialize = function () {
4271 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
4272 * this.content = new OO.ui.PanelLayout( { padded: true } );
4273 * this.content.$element.append( '<p>Click the \'Done\' action widget to see its pending ' +
4274 * 'state. Note that action widgets can be marked pending in message dialogs but not ' +
4275 * 'process dialogs.</p>' );
4276 * this.$body.append( this.content.$element );
4278 * MessageDialog.prototype.getBodyHeight = function () {
4281 * MessageDialog.prototype.getActionProcess = function ( action ) {
4282 * var dialog = this;
4283 * if ( action === 'save' ) {
4284 * dialog.getActions().get({actions: 'save'})[0].pushPending();
4285 * return new OO.ui.Process()
4287 * .next( function () {
4288 * dialog.getActions().get({actions: 'save'})[0].popPending();
4291 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
4294 * var windowManager = new OO.ui.WindowManager();
4295 * $( document.body ).append( windowManager.$element );
4297 * var dialog = new MessageDialog();
4298 * windowManager.addWindows( [ dialog ] );
4299 * windowManager.openWindow( dialog );
4305 * @param {Object} [config] Configuration options
4306 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
4308 OO
.ui
.mixin
.PendingElement
= function OoUiMixinPendingElement( config
) {
4309 // Configuration initialization
4310 config
= config
|| {};
4314 this.$pending
= null;
4317 this.setPendingElement( config
.$pending
|| this.$element
);
4322 OO
.initClass( OO
.ui
.mixin
.PendingElement
);
4327 * Set the pending element (and clean up any existing one).
4329 * @param {jQuery} $pending The element to set to pending.
4331 OO
.ui
.mixin
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
4332 if ( this.$pending
) {
4333 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
4336 this.$pending
= $pending
;
4337 if ( this.pending
> 0 ) {
4338 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
4343 * Check if an element is pending.
4345 * @return {boolean} Element is pending
4347 OO
.ui
.mixin
.PendingElement
.prototype.isPending = function () {
4348 return !!this.pending
;
4352 * Increase the pending counter. The pending state will remain active until the counter is zero
4353 * (i.e., the number of calls to #pushPending and #popPending is the same).
4356 * @return {OO.ui.Element} The element, for chaining
4358 OO
.ui
.mixin
.PendingElement
.prototype.pushPending = function () {
4359 if ( this.pending
=== 0 ) {
4360 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
4361 this.updateThemeClasses();
4369 * Decrease the pending counter. The pending state will remain active until the counter is zero
4370 * (i.e., the number of calls to #pushPending and #popPending is the same).
4373 * @return {OO.ui.Element} The element, for chaining
4375 OO
.ui
.mixin
.PendingElement
.prototype.popPending = function () {
4376 if ( this.pending
=== 1 ) {
4377 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
4378 this.updateThemeClasses();
4380 this.pending
= Math
.max( 0, this.pending
- 1 );
4386 * Element that will stick adjacent to a specified container, even when it is inserted elsewhere
4387 * in the document (for example, in an OO.ui.Window's $overlay).
4389 * The elements's position is automatically calculated and maintained when window is resized or the
4390 * page is scrolled. If you reposition the container manually, you have to call #position to make
4391 * sure the element is still placed correctly.
4393 * As positioning is only possible when both the element and the container are attached to the DOM
4394 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
4395 * the #toggle method to display a floating popup, for example.
4401 * @param {Object} [config] Configuration options
4402 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
4403 * @cfg {jQuery} [$floatableContainer] Node to position adjacent to
4404 * @cfg {string} [verticalPosition='below'] Where to position $floatable vertically:
4405 * 'below': Directly below $floatableContainer, aligning f's top edge with fC's bottom edge
4406 * 'above': Directly above $floatableContainer, aligning f's bottom edge with fC's top edge
4407 * 'top': Align the top edge with $floatableContainer's top edge
4408 * 'bottom': Align the bottom edge with $floatableContainer's bottom edge
4409 * 'center': Vertically align the center with $floatableContainer's center
4410 * @cfg {string} [horizontalPosition='start'] Where to position $floatable horizontally:
4411 * 'before': Directly before $floatableContainer, aligning f's end edge with fC's start edge
4412 * 'after': Directly after $floatableContainer, aligning f's start edge with fC's end edge
4413 * 'start': Align the start (left in LTR, right in RTL) edge with $floatableContainer's start edge
4414 * 'end': Align the end (right in LTR, left in RTL) edge with $floatableContainer's end edge
4415 * 'center': Horizontally align the center with $floatableContainer's center
4416 * @cfg {boolean} [hideWhenOutOfView=true] Whether to hide the floatable element if the container
4419 OO
.ui
.mixin
.FloatableElement
= function OoUiMixinFloatableElement( config
) {
4420 // Configuration initialization
4421 config
= config
|| {};
4424 this.$floatable
= null;
4425 this.$floatableContainer
= null;
4426 this.$floatableWindow
= null;
4427 this.$floatableClosestScrollable
= null;
4428 this.floatableOutOfView
= false;
4429 this.onFloatableScrollHandler
= this.position
.bind( this );
4430 this.onFloatableWindowResizeHandler
= this.position
.bind( this );
4433 this.setFloatableContainer( config
.$floatableContainer
);
4434 this.setFloatableElement( config
.$floatable
|| this.$element
);
4435 this.setVerticalPosition( config
.verticalPosition
|| 'below' );
4436 this.setHorizontalPosition( config
.horizontalPosition
|| 'start' );
4437 this.hideWhenOutOfView
= config
.hideWhenOutOfView
=== undefined ?
4438 true : !!config
.hideWhenOutOfView
;
4444 * Set floatable element.
4446 * If an element is already set, it will be cleaned up before setting up the new element.
4448 * @param {jQuery} $floatable Element to make floatable
4450 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableElement = function ( $floatable
) {
4451 if ( this.$floatable
) {
4452 this.$floatable
.removeClass( 'oo-ui-floatableElement-floatable' );
4453 this.$floatable
.css( { left
: '', top
: '' } );
4456 this.$floatable
= $floatable
.addClass( 'oo-ui-floatableElement-floatable' );
4461 * Set floatable container.
4463 * The element will be positioned relative to the specified container.
4465 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
4467 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableContainer = function ( $floatableContainer
) {
4468 this.$floatableContainer
= $floatableContainer
;
4469 if ( this.$floatable
) {
4475 * Change how the element is positioned vertically.
4477 * @param {string} position 'below', 'above', 'top', 'bottom' or 'center'
4479 OO
.ui
.mixin
.FloatableElement
.prototype.setVerticalPosition = function ( position
) {
4480 if ( [ 'below', 'above', 'top', 'bottom', 'center' ].indexOf( position
) === -1 ) {
4481 throw new Error( 'Invalid value for vertical position: ' + position
);
4483 if ( this.verticalPosition
!== position
) {
4484 this.verticalPosition
= position
;
4485 if ( this.$floatable
) {
4492 * Change how the element is positioned horizontally.
4494 * @param {string} position 'before', 'after', 'start', 'end' or 'center'
4496 OO
.ui
.mixin
.FloatableElement
.prototype.setHorizontalPosition = function ( position
) {
4497 if ( [ 'before', 'after', 'start', 'end', 'center' ].indexOf( position
) === -1 ) {
4498 throw new Error( 'Invalid value for horizontal position: ' + position
);
4500 if ( this.horizontalPosition
!== position
) {
4501 this.horizontalPosition
= position
;
4502 if ( this.$floatable
) {
4509 * Toggle positioning.
4511 * Do not turn positioning on until after the element is attached to the DOM and visible.
4513 * @param {boolean} [positioning] Enable positioning, omit to toggle
4515 * @return {OO.ui.Element} The element, for chaining
4517 OO
.ui
.mixin
.FloatableElement
.prototype.togglePositioning = function ( positioning
) {
4518 var closestScrollableOfContainer
;
4520 if ( !this.$floatable
|| !this.$floatableContainer
) {
4524 positioning
= positioning
=== undefined ? !this.positioning
: !!positioning
;
4526 if ( positioning
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4527 OO
.ui
.warnDeprecation( 'FloatableElement#togglePositioning: Before calling this method, the element must be attached to the DOM.' );
4528 this.warnedUnattached
= true;
4531 if ( this.positioning
!== positioning
) {
4532 this.positioning
= positioning
;
4534 closestScrollableOfContainer
= OO
.ui
.Element
.static.getClosestScrollableContainer(
4535 this.$floatableContainer
[ 0 ]
4537 // If the scrollable is the root, we have to listen to scroll events
4538 // on the window because of browser inconsistencies.
4539 if ( $( closestScrollableOfContainer
).is( 'html, body' ) ) {
4540 closestScrollableOfContainer
= OO
.ui
.Element
.static.getWindow(
4541 closestScrollableOfContainer
4545 if ( positioning
) {
4546 this.$floatableWindow
= $( this.getElementWindow() );
4547 this.$floatableWindow
.on( 'resize', this.onFloatableWindowResizeHandler
);
4549 this.$floatableClosestScrollable
= $( closestScrollableOfContainer
);
4550 this.$floatableClosestScrollable
.on( 'scroll', this.onFloatableScrollHandler
);
4552 // Initial position after visible
4555 if ( this.$floatableWindow
) {
4556 this.$floatableWindow
.off( 'resize', this.onFloatableWindowResizeHandler
);
4557 this.$floatableWindow
= null;
4560 if ( this.$floatableClosestScrollable
) {
4561 this.$floatableClosestScrollable
.off( 'scroll', this.onFloatableScrollHandler
);
4562 this.$floatableClosestScrollable
= null;
4565 this.$floatable
.css( { left
: '', right
: '', top
: '' } );
4573 * Check whether the bottom edge of the given element is within the viewport of the given
4577 * @param {jQuery} $element
4578 * @param {jQuery} $container
4581 OO
.ui
.mixin
.FloatableElement
.prototype.isElementInViewport = function ( $element
, $container
) {
4582 var elemRect
, contRect
, topEdgeInBounds
, bottomEdgeInBounds
, leftEdgeInBounds
,
4583 rightEdgeInBounds
, startEdgeInBounds
, endEdgeInBounds
, viewportSpacing
,
4584 direction
= $element
.css( 'direction' );
4586 elemRect
= $element
[ 0 ].getBoundingClientRect();
4587 if ( $container
[ 0 ] === window
) {
4588 viewportSpacing
= OO
.ui
.getViewportSpacing();
4592 right
: document
.documentElement
.clientWidth
,
4593 bottom
: document
.documentElement
.clientHeight
4595 contRect
.top
+= viewportSpacing
.top
;
4596 contRect
.left
+= viewportSpacing
.left
;
4597 contRect
.right
-= viewportSpacing
.right
;
4598 contRect
.bottom
-= viewportSpacing
.bottom
;
4600 contRect
= $container
[ 0 ].getBoundingClientRect();
4603 topEdgeInBounds
= elemRect
.top
>= contRect
.top
&& elemRect
.top
<= contRect
.bottom
;
4604 bottomEdgeInBounds
= elemRect
.bottom
>= contRect
.top
&& elemRect
.bottom
<= contRect
.bottom
;
4605 leftEdgeInBounds
= elemRect
.left
>= contRect
.left
&& elemRect
.left
<= contRect
.right
;
4606 rightEdgeInBounds
= elemRect
.right
>= contRect
.left
&& elemRect
.right
<= contRect
.right
;
4607 if ( direction
=== 'rtl' ) {
4608 startEdgeInBounds
= rightEdgeInBounds
;
4609 endEdgeInBounds
= leftEdgeInBounds
;
4611 startEdgeInBounds
= leftEdgeInBounds
;
4612 endEdgeInBounds
= rightEdgeInBounds
;
4615 if ( this.verticalPosition
=== 'below' && !bottomEdgeInBounds
) {
4618 if ( this.verticalPosition
=== 'above' && !topEdgeInBounds
) {
4621 if ( this.horizontalPosition
=== 'before' && !startEdgeInBounds
) {
4624 if ( this.horizontalPosition
=== 'after' && !endEdgeInBounds
) {
4628 // The other positioning values are all about being inside the container,
4629 // so in those cases all we care about is that any part of the container is visible.
4630 return elemRect
.top
<= contRect
.bottom
&& elemRect
.bottom
>= contRect
.top
&&
4631 elemRect
.left
<= contRect
.right
&& elemRect
.right
>= contRect
.left
;
4635 * Check if the floatable is hidden to the user because it was offscreen.
4637 * @return {boolean} Floatable is out of view
4639 OO
.ui
.mixin
.FloatableElement
.prototype.isFloatableOutOfView = function () {
4640 return this.floatableOutOfView
;
4644 * Position the floatable below its container.
4646 * This should only be done when both of them are attached to the DOM and visible.
4649 * @return {OO.ui.Element} The element, for chaining
4651 OO
.ui
.mixin
.FloatableElement
.prototype.position = function () {
4652 if ( !this.positioning
) {
4657 // To continue, some things need to be true:
4658 // The element must actually be in the DOM
4659 this.isElementAttached() && (
4660 // The closest scrollable is the current window
4661 this.$floatableClosestScrollable
[ 0 ] === this.getElementWindow() ||
4662 // OR is an element in the element's DOM
4663 $.contains( this.getElementDocument(), this.$floatableClosestScrollable
[ 0 ] )
4666 // Abort early if important parts of the widget are no longer attached to the DOM
4670 this.floatableOutOfView
= this.hideWhenOutOfView
&&
4671 !this.isElementInViewport( this.$floatableContainer
, this.$floatableClosestScrollable
);
4672 if ( this.floatableOutOfView
) {
4673 this.$floatable
.addClass( 'oo-ui-element-hidden' );
4676 this.$floatable
.removeClass( 'oo-ui-element-hidden' );
4679 this.$floatable
.css( this.computePosition() );
4681 // We updated the position, so re-evaluate the clipping state.
4682 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
4683 // will not notice the need to update itself.)
4684 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here.
4685 // Why does it not listen to the right events in the right places?
4694 * Compute how #$floatable should be positioned based on the position of #$floatableContainer
4695 * and the positioning settings. This is a helper for #position that shouldn't be called directly,
4696 * but may be overridden by subclasses if they want to change or add to the positioning logic.
4698 * @return {Object} New position to apply with .css(). Keys are 'top', 'left', 'bottom' and 'right'.
4700 OO
.ui
.mixin
.FloatableElement
.prototype.computePosition = function () {
4701 var isBody
, scrollableX
, scrollableY
, containerPos
,
4702 horizScrollbarHeight
, vertScrollbarWidth
, scrollTop
, scrollLeft
,
4703 newPos
= { top
: '', left
: '', bottom
: '', right
: '' },
4704 direction
= this.$floatableContainer
.css( 'direction' ),
4705 $offsetParent
= this.$floatable
.offsetParent();
4707 if ( $offsetParent
.is( 'html' ) ) {
4708 // The innerHeight/Width and clientHeight/Width calculations don't work well on the
4709 // <html> element, but they do work on the <body>
4710 $offsetParent
= $( $offsetParent
[ 0 ].ownerDocument
.body
);
4712 isBody
= $offsetParent
.is( 'body' );
4713 scrollableX
= $offsetParent
.css( 'overflow-x' ) === 'scroll' ||
4714 $offsetParent
.css( 'overflow-x' ) === 'auto';
4715 scrollableY
= $offsetParent
.css( 'overflow-y' ) === 'scroll' ||
4716 $offsetParent
.css( 'overflow-y' ) === 'auto';
4718 vertScrollbarWidth
= $offsetParent
.innerWidth() - $offsetParent
.prop( 'clientWidth' );
4719 horizScrollbarHeight
= $offsetParent
.innerHeight() - $offsetParent
.prop( 'clientHeight' );
4720 // We don't need to compute and add scrollTop and scrollLeft if the scrollable container
4721 // is the body, or if it isn't scrollable
4722 scrollTop
= scrollableY
&& !isBody
?
4723 $offsetParent
.scrollTop() : 0;
4724 scrollLeft
= scrollableX
&& !isBody
?
4725 OO
.ui
.Element
.static.getScrollLeft( $offsetParent
[ 0 ] ) : 0;
4727 // Avoid passing the <body> to getRelativePosition(), because it won't return what we expect
4728 // if the <body> has a margin
4729 containerPos
= isBody
?
4730 this.$floatableContainer
.offset() :
4731 OO
.ui
.Element
.static.getRelativePosition( this.$floatableContainer
, $offsetParent
);
4732 containerPos
.bottom
= containerPos
.top
+ this.$floatableContainer
.outerHeight();
4733 containerPos
.right
= containerPos
.left
+ this.$floatableContainer
.outerWidth();
4734 containerPos
.start
= direction
=== 'rtl' ? containerPos
.right
: containerPos
.left
;
4735 containerPos
.end
= direction
=== 'rtl' ? containerPos
.left
: containerPos
.right
;
4737 if ( this.verticalPosition
=== 'below' ) {
4738 newPos
.top
= containerPos
.bottom
;
4739 } else if ( this.verticalPosition
=== 'above' ) {
4740 newPos
.bottom
= $offsetParent
.outerHeight() - containerPos
.top
;
4741 } else if ( this.verticalPosition
=== 'top' ) {
4742 newPos
.top
= containerPos
.top
;
4743 } else if ( this.verticalPosition
=== 'bottom' ) {
4744 newPos
.bottom
= $offsetParent
.outerHeight() - containerPos
.bottom
;
4745 } else if ( this.verticalPosition
=== 'center' ) {
4746 newPos
.top
= containerPos
.top
+
4747 ( this.$floatableContainer
.height() - this.$floatable
.height() ) / 2;
4750 if ( this.horizontalPosition
=== 'before' ) {
4751 newPos
.end
= containerPos
.start
;
4752 } else if ( this.horizontalPosition
=== 'after' ) {
4753 newPos
.start
= containerPos
.end
;
4754 } else if ( this.horizontalPosition
=== 'start' ) {
4755 newPos
.start
= containerPos
.start
;
4756 } else if ( this.horizontalPosition
=== 'end' ) {
4757 newPos
.end
= containerPos
.end
;
4758 } else if ( this.horizontalPosition
=== 'center' ) {
4759 newPos
.left
= containerPos
.left
+
4760 ( this.$floatableContainer
.width() - this.$floatable
.width() ) / 2;
4763 if ( newPos
.start
!== undefined ) {
4764 if ( direction
=== 'rtl' ) {
4765 newPos
.right
= ( isBody
? $( $offsetParent
[ 0 ].ownerDocument
.documentElement
) :
4766 $offsetParent
).outerWidth() - newPos
.start
;
4768 newPos
.left
= newPos
.start
;
4770 delete newPos
.start
;
4772 if ( newPos
.end
!== undefined ) {
4773 if ( direction
=== 'rtl' ) {
4774 newPos
.left
= newPos
.end
;
4776 newPos
.right
= ( isBody
? $( $offsetParent
[ 0 ].ownerDocument
.documentElement
) :
4777 $offsetParent
).outerWidth() - newPos
.end
;
4782 // Account for scroll position
4783 if ( newPos
.top
!== '' ) {
4784 newPos
.top
+= scrollTop
;
4786 if ( newPos
.bottom
!== '' ) {
4787 newPos
.bottom
-= scrollTop
;
4789 if ( newPos
.left
!== '' ) {
4790 newPos
.left
+= scrollLeft
;
4792 if ( newPos
.right
!== '' ) {
4793 newPos
.right
-= scrollLeft
;
4796 // Account for scrollbar gutter
4797 if ( newPos
.bottom
!== '' ) {
4798 newPos
.bottom
-= horizScrollbarHeight
;
4800 if ( direction
=== 'rtl' ) {
4801 if ( newPos
.left
!== '' ) {
4802 newPos
.left
-= vertScrollbarWidth
;
4805 if ( newPos
.right
!== '' ) {
4806 newPos
.right
-= vertScrollbarWidth
;
4814 * Element that can be automatically clipped to visible boundaries.
4816 * Whenever the element's natural height changes, you have to call
4817 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
4818 * clipping correctly.
4820 * The dimensions of #$clippableContainer will be compared to the boundaries of the
4821 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
4822 * then #$clippable will be given a fixed reduced height and/or width and will be made
4823 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
4824 * but you can build a static footer by setting #$clippableContainer to an element that contains
4825 * #$clippable and the footer.
4831 * @param {Object} [config] Configuration options
4832 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
4833 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
4834 * omit to use #$clippable
4836 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
4837 // Configuration initialization
4838 config
= config
|| {};
4841 this.$clippable
= null;
4842 this.$clippableContainer
= null;
4843 this.clipping
= false;
4844 this.clippedHorizontally
= false;
4845 this.clippedVertically
= false;
4846 this.$clippableScrollableContainer
= null;
4847 this.$clippableScroller
= null;
4848 this.$clippableWindow
= null;
4849 this.idealWidth
= null;
4850 this.idealHeight
= null;
4851 this.onClippableScrollHandler
= this.clip
.bind( this );
4852 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
4855 if ( config
.$clippableContainer
) {
4856 this.setClippableContainer( config
.$clippableContainer
);
4858 this.setClippableElement( config
.$clippable
|| this.$element
);
4864 * Set clippable element.
4866 * If an element is already set, it will be cleaned up before setting up the new element.
4868 * @param {jQuery} $clippable Element to make clippable
4870 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
4871 if ( this.$clippable
) {
4872 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
4873 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
4874 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4877 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
4882 * Set clippable container.
4884 * This is the container that will be measured when deciding whether to clip. When clipping,
4885 * #$clippable will be resized in order to keep the clippable container fully visible.
4887 * If the clippable container is unset, #$clippable will be used.
4889 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
4891 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableContainer = function ( $clippableContainer
) {
4892 this.$clippableContainer
= $clippableContainer
;
4893 if ( this.$clippable
) {
4901 * Do not turn clipping on until after the element is attached to the DOM and visible.
4903 * @param {boolean} [clipping] Enable clipping, omit to toggle
4905 * @return {OO.ui.Element} The element, for chaining
4907 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
4908 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
4910 if ( clipping
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4911 OO
.ui
.warnDeprecation( 'ClippableElement#toggleClipping: Before calling this method, the element must be attached to the DOM.' );
4912 this.warnedUnattached
= true;
4915 if ( this.clipping
!== clipping
) {
4916 this.clipping
= clipping
;
4918 this.$clippableScrollableContainer
= $( this.getClosestScrollableElementContainer() );
4919 // If the clippable container is the root, we have to listen to scroll events and check
4920 // jQuery.scrollTop on the window because of browser inconsistencies
4921 this.$clippableScroller
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
4922 $( OO
.ui
.Element
.static.getWindow( this.$clippableScrollableContainer
) ) :
4923 this.$clippableScrollableContainer
;
4924 this.$clippableScroller
.on( 'scroll', this.onClippableScrollHandler
);
4925 this.$clippableWindow
= $( this.getElementWindow() )
4926 .on( 'resize', this.onClippableWindowResizeHandler
);
4927 // Initial clip after visible
4930 this.$clippable
.css( {
4938 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4940 this.$clippableScrollableContainer
= null;
4941 this.$clippableScroller
.off( 'scroll', this.onClippableScrollHandler
);
4942 this.$clippableScroller
= null;
4943 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
4944 this.$clippableWindow
= null;
4952 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4954 * @return {boolean} Element will be clipped to the visible area
4956 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
4957 return this.clipping
;
4961 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
4963 * @return {boolean} Part of the element is being clipped
4965 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
4966 return this.clippedHorizontally
|| this.clippedVertically
;
4970 * Check if the right of the element is being clipped by the nearest scrollable container.
4972 * @return {boolean} Part of the element is being clipped
4974 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
4975 return this.clippedHorizontally
;
4979 * Check if the bottom of the element is being clipped by the nearest scrollable container.
4981 * @return {boolean} Part of the element is being clipped
4983 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
4984 return this.clippedVertically
;
4988 * Set the ideal size. These are the dimensions #$clippable will have when it's not being clipped.
4990 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
4991 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
4993 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
4994 this.idealWidth
= width
;
4995 this.idealHeight
= height
;
4997 if ( !this.clipping
) {
4998 // Update dimensions
4999 this.$clippable
.css( { width
: width
, height
: height
} );
5001 // While clipping, idealWidth and idealHeight are not considered
5005 * Return the side of the clippable on which it is "anchored" (aligned to something else).
5006 * ClippableElement will clip the opposite side when reducing element's width.
5008 * Classes that mix in ClippableElement should override this to return 'right' if their
5009 * clippable is absolutely positioned and using 'right: Npx' (and not using 'left').
5010 * If your class also mixes in FloatableElement, this is handled automatically.
5012 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
5013 * always in pixels, even if they were unset or set to 'auto'.)
5015 * When in doubt, 'left' (or 'right' in RTL) is a sane fallback.
5017 * @return {string} 'left' or 'right'
5019 OO
.ui
.mixin
.ClippableElement
.prototype.getHorizontalAnchorEdge = function () {
5020 if ( this.computePosition
&& this.positioning
&& this.computePosition().right
!== '' ) {
5027 * Return the side of the clippable on which it is "anchored" (aligned to something else).
5028 * ClippableElement will clip the opposite side when reducing element's width.
5030 * Classes that mix in ClippableElement should override this to return 'bottom' if their
5031 * clippable is absolutely positioned and using 'bottom: Npx' (and not using 'top').
5032 * If your class also mixes in FloatableElement, this is handled automatically.
5034 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
5035 * always in pixels, even if they were unset or set to 'auto'.)
5037 * When in doubt, 'top' is a sane fallback.
5039 * @return {string} 'top' or 'bottom'
5041 OO
.ui
.mixin
.ClippableElement
.prototype.getVerticalAnchorEdge = function () {
5042 if ( this.computePosition
&& this.positioning
&& this.computePosition().bottom
!== '' ) {
5049 * Clip element to visible boundaries and allow scrolling when needed. You should call this method
5050 * when the element's natural height changes.
5052 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
5053 * overlapped by, the visible area of the nearest scrollable container.
5055 * Because calling clip() when the natural height changes isn't always possible, we also set
5056 * max-height when the element isn't being clipped. This means that if the element tries to grow
5057 * beyond the edge, something reasonable will happen before clip() is called.
5060 * @return {OO.ui.Element} The element, for chaining
5062 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
5063 var extraHeight
, extraWidth
, viewportSpacing
,
5064 desiredWidth
, desiredHeight
, allotedWidth
, allotedHeight
,
5065 naturalWidth
, naturalHeight
, clipWidth
, clipHeight
,
5066 $item
, itemRect
, $viewport
, viewportRect
, availableRect
,
5067 direction
, vertScrollbarWidth
, horizScrollbarHeight
,
5068 // Extra tolerance so that the sloppy code below doesn't result in results that are off
5069 // by one or two pixels. (And also so that we have space to display drop shadows.)
5070 // Chosen by fair dice roll.
5073 if ( !this.clipping
) {
5074 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below
5079 function rectIntersection( a
, b
) {
5081 out
.top
= Math
.max( a
.top
, b
.top
);
5082 out
.left
= Math
.max( a
.left
, b
.left
);
5083 out
.bottom
= Math
.min( a
.bottom
, b
.bottom
);
5084 out
.right
= Math
.min( a
.right
, b
.right
);
5088 viewportSpacing
= OO
.ui
.getViewportSpacing();
5090 if ( this.$clippableScrollableContainer
.is( 'html, body' ) ) {
5091 $viewport
= $( this.$clippableScrollableContainer
[ 0 ].ownerDocument
.body
);
5092 // Dimensions of the browser window, rather than the element!
5096 right
: document
.documentElement
.clientWidth
,
5097 bottom
: document
.documentElement
.clientHeight
5099 viewportRect
.top
+= viewportSpacing
.top
;
5100 viewportRect
.left
+= viewportSpacing
.left
;
5101 viewportRect
.right
-= viewportSpacing
.right
;
5102 viewportRect
.bottom
-= viewportSpacing
.bottom
;
5104 $viewport
= this.$clippableScrollableContainer
;
5105 viewportRect
= $viewport
[ 0 ].getBoundingClientRect();
5106 // Convert into a plain object
5107 viewportRect
= $.extend( {}, viewportRect
);
5110 // Account for scrollbar gutter
5111 direction
= $viewport
.css( 'direction' );
5112 vertScrollbarWidth
= $viewport
.innerWidth() - $viewport
.prop( 'clientWidth' );
5113 horizScrollbarHeight
= $viewport
.innerHeight() - $viewport
.prop( 'clientHeight' );
5114 viewportRect
.bottom
-= horizScrollbarHeight
;
5115 if ( direction
=== 'rtl' ) {
5116 viewportRect
.left
+= vertScrollbarWidth
;
5118 viewportRect
.right
-= vertScrollbarWidth
;
5121 // Add arbitrary tolerance
5122 viewportRect
.top
+= buffer
;
5123 viewportRect
.left
+= buffer
;
5124 viewportRect
.right
-= buffer
;
5125 viewportRect
.bottom
-= buffer
;
5127 $item
= this.$clippableContainer
|| this.$clippable
;
5129 extraHeight
= $item
.outerHeight() - this.$clippable
.outerHeight();
5130 extraWidth
= $item
.outerWidth() - this.$clippable
.outerWidth();
5132 itemRect
= $item
[ 0 ].getBoundingClientRect();
5133 // Convert into a plain object
5134 itemRect
= $.extend( {}, itemRect
);
5136 // Item might already be clipped, so we can't just use its dimensions (in case we might need to
5137 // make it larger than before). Extend the rectangle to the maximum size we are allowed to take.
5138 if ( this.getHorizontalAnchorEdge() === 'right' ) {
5139 itemRect
.left
= viewportRect
.left
;
5141 itemRect
.right
= viewportRect
.right
;
5143 if ( this.getVerticalAnchorEdge() === 'bottom' ) {
5144 itemRect
.top
= viewportRect
.top
;
5146 itemRect
.bottom
= viewportRect
.bottom
;
5149 availableRect
= rectIntersection( viewportRect
, itemRect
);
5151 desiredWidth
= Math
.max( 0, availableRect
.right
- availableRect
.left
);
5152 desiredHeight
= Math
.max( 0, availableRect
.bottom
- availableRect
.top
);
5153 // It should never be desirable to exceed the dimensions of the browser viewport... right?
5154 desiredWidth
= Math
.min( desiredWidth
,
5155 document
.documentElement
.clientWidth
- viewportSpacing
.left
- viewportSpacing
.right
);
5156 desiredHeight
= Math
.min( desiredHeight
,
5157 document
.documentElement
.clientHeight
- viewportSpacing
.top
- viewportSpacing
.right
);
5158 allotedWidth
= Math
.ceil( desiredWidth
- extraWidth
);
5159 allotedHeight
= Math
.ceil( desiredHeight
- extraHeight
);
5160 naturalWidth
= this.$clippable
.prop( 'scrollWidth' );
5161 naturalHeight
= this.$clippable
.prop( 'scrollHeight' );
5162 clipWidth
= allotedWidth
< naturalWidth
;
5163 clipHeight
= allotedHeight
< naturalHeight
;
5166 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars.
5168 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for
5170 this.$clippable
.css( 'overflowX', 'scroll' );
5171 // eslint-disable-next-line no-void
5172 void this.$clippable
[ 0 ].offsetHeight
; // Force reflow
5173 this.$clippable
.css( {
5174 width
: Math
.max( 0, allotedWidth
),
5178 this.$clippable
.css( {
5180 width
: this.idealWidth
|| '',
5181 maxWidth
: Math
.max( 0, allotedWidth
)
5185 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars.
5187 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for
5189 this.$clippable
.css( 'overflowY', 'scroll' );
5190 // eslint-disable-next-line no-void
5191 void this.$clippable
[ 0 ].offsetHeight
; // Force reflow
5192 this.$clippable
.css( {
5193 height
: Math
.max( 0, allotedHeight
),
5197 this.$clippable
.css( {
5199 height
: this.idealHeight
|| '',
5200 maxHeight
: Math
.max( 0, allotedHeight
)
5204 // If we stopped clipping in at least one of the dimensions
5205 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
5206 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
5209 this.clippedHorizontally
= clipWidth
;
5210 this.clippedVertically
= clipHeight
;
5216 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
5217 * By default, each popup has an anchor that points toward its origin.
5218 * Please see the [OOUI documentation on MediaWiki.org] [1] for more information and examples.
5220 * Unlike most widgets, PopupWidget is initially hidden and must be shown by calling #toggle.
5224 * var popup = new OO.ui.PopupWidget( {
5225 * $content: $( '<p>Hi there!</p>' ),
5230 * $( document.body ).append( popup.$element );
5231 * // To display the popup, toggle the visibility to 'true'.
5232 * popup.toggle( true );
5234 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups
5237 * @extends OO.ui.Widget
5238 * @mixins OO.ui.mixin.LabelElement
5239 * @mixins OO.ui.mixin.ClippableElement
5240 * @mixins OO.ui.mixin.FloatableElement
5243 * @param {Object} [config] Configuration options
5244 * @cfg {number|null} [width=320] Width of popup in pixels. Pass `null` to use automatic width.
5245 * @cfg {number|null} [height=null] Height of popup in pixels. Pass `null` to use automatic height.
5246 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
5247 * @cfg {string} [position='below'] Where to position the popup relative to $floatableContainer
5248 * 'above': Put popup above $floatableContainer; anchor points down to the horizontal center
5249 * of $floatableContainer
5250 * 'below': Put popup below $floatableContainer; anchor points up to the horizontal center
5251 * of $floatableContainer
5252 * 'before': Put popup to the left (LTR) / right (RTL) of $floatableContainer; anchor points
5253 * endwards (right/left) to the vertical center of $floatableContainer
5254 * 'after': Put popup to the right (LTR) / left (RTL) of $floatableContainer; anchor points
5255 * startwards (left/right) to the vertical center of $floatableContainer
5256 * @cfg {string} [align='center'] How to align the popup to $floatableContainer
5257 * 'forwards': If position is above/below, move the popup as far endwards (right in LTR, left in
5258 * RTL) as possible while still keeping the anchor within the popup; if position is before/after,
5259 * move the popup as far downwards as possible.
5260 * 'backwards': If position is above/below, move the popup as far startwards (left in LTR, right in
5261 * RTL) as possible while still keeping the anchor within the popup; if position is before/after,
5262 * move the popup as far upwards as possible.
5263 * 'center': Horizontally (if position is above/below) or vertically (before/after) align the
5264 * center of the popup with the center of $floatableContainer.
5265 * 'force-left': Alias for 'forwards' in LTR and 'backwards' in RTL
5266 * 'force-right': Alias for 'backwards' in RTL and 'forwards' in LTR
5267 * @cfg {boolean} [autoFlip=true] Whether to automatically switch the popup's position between
5268 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5269 * desired direction to display the popup without clipping
5270 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
5271 * See the [OOUI docs on MediaWiki][3] for an example.
5272 * [3]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#containerExample
5273 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a
5275 * @cfg {jQuery} [$content] Content to append to the popup's body
5276 * @cfg {jQuery} [$footer] Content to append to the popup's footer
5277 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
5278 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
5279 * This config option is only relevant if #autoClose is set to `true`. See the
5280 * [OOUI documentation on MediaWiki][2] for an example.
5281 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#autocloseExample
5282 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
5284 * @cfg {boolean} [padded=false] Add padding to the popup's body
5286 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
5287 // Configuration initialization
5288 config
= config
|| {};
5290 // Parent constructor
5291 OO
.ui
.PopupWidget
.parent
.call( this, config
);
5293 // Properties (must be set before ClippableElement constructor call)
5294 this.$body
= $( '<div>' );
5295 this.$popup
= $( '<div>' );
5297 // Mixin constructors
5298 OO
.ui
.mixin
.LabelElement
.call( this, config
);
5299 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {
5300 $clippable
: this.$body
,
5301 $clippableContainer
: this.$popup
5303 OO
.ui
.mixin
.FloatableElement
.call( this, config
);
5306 this.$anchor
= $( '<div>' );
5307 // If undefined, will be computed lazily in computePosition()
5308 this.$container
= config
.$container
;
5309 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
5310 this.autoClose
= !!config
.autoClose
;
5311 this.transitionTimeout
= null;
5312 this.anchored
= false;
5313 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
5314 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
5317 this.setSize( config
.width
, config
.height
);
5318 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
5319 this.setAlignment( config
.align
|| 'center' );
5320 this.setPosition( config
.position
|| 'below' );
5321 this.setAutoFlip( config
.autoFlip
=== undefined || config
.autoFlip
);
5322 this.setAutoCloseIgnore( config
.$autoCloseIgnore
);
5323 this.$body
.addClass( 'oo-ui-popupWidget-body' );
5324 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
5326 .addClass( 'oo-ui-popupWidget-popup' )
5327 .append( this.$body
);
5329 .addClass( 'oo-ui-popupWidget' )
5330 .append( this.$popup
, this.$anchor
);
5331 // Move content, which was added to #$element by OO.ui.Widget, to the body
5332 // FIXME This is gross, we should use '$body' or something for the config
5333 if ( config
.$content
instanceof $ ) {
5334 this.$body
.append( config
.$content
);
5337 if ( config
.padded
) {
5338 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
5341 if ( config
.head
) {
5342 this.closeButton
= new OO
.ui
.ButtonWidget( {
5346 this.closeButton
.connect( this, {
5347 click
: 'onCloseButtonClick'
5349 this.$head
= $( '<div>' )
5350 .addClass( 'oo-ui-popupWidget-head' )
5351 .append( this.$label
, this.closeButton
.$element
);
5352 this.$popup
.prepend( this.$head
);
5355 if ( config
.$footer
) {
5356 this.$footer
= $( '<div>' )
5357 .addClass( 'oo-ui-popupWidget-footer' )
5358 .append( config
.$footer
);
5359 this.$popup
.append( this.$footer
);
5362 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
5363 // that reference properties not initialized at that time of parent class construction
5364 // TODO: Find a better way to handle post-constructor setup
5365 this.visible
= false;
5366 this.$element
.addClass( 'oo-ui-element-hidden' );
5371 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
5372 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
5373 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
5374 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.FloatableElement
);
5381 * The popup is ready: it is visible and has been positioned and clipped.
5387 * Handles document mouse down events.
5390 * @param {MouseEvent} e Mouse down event
5392 OO
.ui
.PopupWidget
.prototype.onDocumentMouseDown = function ( e
) {
5395 !OO
.ui
.contains( this.$element
.add( this.$autoCloseIgnore
).get(), e
.target
, true )
5397 this.toggle( false );
5402 * Bind document mouse down listener.
5406 OO
.ui
.PopupWidget
.prototype.bindDocumentMouseDownListener = function () {
5407 // Capture clicks outside popup
5408 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
5409 // We add 'click' event because iOS safari needs to respond to this event.
5410 // We can't use 'touchstart' (as is usually the equivalent to 'mousedown') because
5411 // then it will trigger when scrolling. While iOS Safari has some reported behavior
5412 // of occasionally not emitting 'click' properly, that event seems to be the standard
5413 // that it should be emitting, so we add it to this and will operate the event handler
5414 // on whichever of these events was triggered first
5415 this.getElementDocument().addEventListener( 'click', this.onDocumentMouseDownHandler
, true );
5419 * Handles close button click events.
5423 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
5424 if ( this.isVisible() ) {
5425 this.toggle( false );
5430 * Unbind document mouse down listener.
5434 OO
.ui
.PopupWidget
.prototype.unbindDocumentMouseDownListener = function () {
5435 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
5436 this.getElementDocument().removeEventListener( 'click', this.onDocumentMouseDownHandler
, true );
5440 * Handles document key down events.
5443 * @param {KeyboardEvent} e Key down event
5445 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
5447 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
5450 this.toggle( false );
5452 e
.stopPropagation();
5457 * Bind document key down listener.
5461 OO
.ui
.PopupWidget
.prototype.bindDocumentKeyDownListener = function () {
5462 this.getElementDocument().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
5466 * Unbind document key down listener.
5470 OO
.ui
.PopupWidget
.prototype.unbindDocumentKeyDownListener = function () {
5471 this.getElementDocument().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
5475 * Show, hide, or toggle the visibility of the anchor.
5477 * @param {boolean} [show] Show anchor, omit to toggle
5479 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
5480 show
= show
=== undefined ? !this.anchored
: !!show
;
5482 if ( this.anchored
!== show
) {
5484 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
5485 this.$element
.addClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5487 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
5488 this.$element
.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5490 this.anchored
= show
;
5495 * Change which edge the anchor appears on.
5497 * @param {string} edge 'top', 'bottom', 'start' or 'end'
5499 OO
.ui
.PopupWidget
.prototype.setAnchorEdge = function ( edge
) {
5500 if ( [ 'top', 'bottom', 'start', 'end' ].indexOf( edge
) === -1 ) {
5501 throw new Error( 'Invalid value for edge: ' + edge
);
5503 if ( this.anchorEdge
!== null ) {
5504 this.$element
.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5506 this.anchorEdge
= edge
;
5507 if ( this.anchored
) {
5508 this.$element
.addClass( 'oo-ui-popupWidget-anchored-' + edge
);
5513 * Check if the anchor is visible.
5515 * @return {boolean} Anchor is visible
5517 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
5518 return this.anchored
;
5522 * Toggle visibility of the popup. The popup is initially hidden and must be shown by calling
5523 * `.toggle( true )` after its #$element is attached to the DOM.
5525 * Do not show the popup while it is not attached to the DOM. The calculations required to display
5526 * it in the right place and with the right dimensions only work correctly while it is attached.
5527 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
5528 * strictly enforced, so currently it only generates a warning in the browser console.
5533 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
5534 var change
, normalHeight
, oppositeHeight
, normalWidth
, oppositeWidth
;
5535 show
= show
=== undefined ? !this.isVisible() : !!show
;
5537 change
= show
!== this.isVisible();
5539 if ( show
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
5540 OO
.ui
.warnDeprecation( 'PopupWidget#toggle: Before calling this method, the popup must be attached to the DOM.' );
5541 this.warnedUnattached
= true;
5543 if ( show
&& !this.$floatableContainer
&& this.isElementAttached() ) {
5544 // Fall back to the parent node if the floatableContainer is not set
5545 this.setFloatableContainer( this.$element
.parent() );
5548 if ( change
&& show
&& this.autoFlip
) {
5549 // Reset auto-flipping before showing the popup again. It's possible we no longer need to
5550 // flip (e.g. if the user scrolled).
5551 this.isAutoFlipped
= false;
5555 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
5558 this.togglePositioning( show
&& !!this.$floatableContainer
);
5561 if ( this.autoClose
) {
5562 this.bindDocumentMouseDownListener();
5563 this.bindDocumentKeyDownListener();
5565 this.updateDimensions();
5566 this.toggleClipping( true );
5568 if ( this.autoFlip
) {
5569 if ( this.popupPosition
=== 'above' || this.popupPosition
=== 'below' ) {
5570 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5571 // If opening the popup in the normal direction causes it to be clipped,
5572 // open in the opposite one instead
5573 normalHeight
= this.$element
.height();
5574 this.isAutoFlipped
= !this.isAutoFlipped
;
5576 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5577 // If that also causes it to be clipped, open in whichever direction
5578 // we have more space
5579 oppositeHeight
= this.$element
.height();
5580 if ( oppositeHeight
< normalHeight
) {
5581 this.isAutoFlipped
= !this.isAutoFlipped
;
5587 if ( this.popupPosition
=== 'before' || this.popupPosition
=== 'after' ) {
5588 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5589 // If opening the popup in the normal direction causes it to be clipped,
5590 // open in the opposite one instead
5591 normalWidth
= this.$element
.width();
5592 this.isAutoFlipped
= !this.isAutoFlipped
;
5593 // Due to T180173 horizontally clipped PopupWidgets have messed up
5594 // dimensions, which causes positioning to be off. Toggle clipping back and
5595 // forth to work around.
5596 this.toggleClipping( false );
5598 this.toggleClipping( true );
5599 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5600 // If that also causes it to be clipped, open in whichever direction
5601 // we have more space
5602 oppositeWidth
= this.$element
.width();
5603 if ( oppositeWidth
< normalWidth
) {
5604 this.isAutoFlipped
= !this.isAutoFlipped
;
5605 // Due to T180173, horizontally clipped PopupWidgets have messed up
5606 // dimensions, which causes positioning to be off. Toggle clipping
5607 // back and forth to work around.
5608 this.toggleClipping( false );
5610 this.toggleClipping( true );
5617 this.emit( 'ready' );
5619 this.toggleClipping( false );
5620 if ( this.autoClose
) {
5621 this.unbindDocumentMouseDownListener();
5622 this.unbindDocumentKeyDownListener();
5631 * Set the size of the popup.
5633 * Changing the size may also change the popup's position depending on the alignment.
5635 * @param {number|null} [width=320] Width in pixels. Pass `null` to use automatic width.
5636 * @param {number|null} [height=null] Height in pixels. Pass `null` to use automatic height.
5637 * @param {boolean} [transition=false] Use a smooth transition
5640 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
5641 this.width
= width
!== undefined ? width
: 320;
5642 this.height
= height
!== undefined ? height
: null;
5643 if ( this.isVisible() ) {
5644 this.updateDimensions( transition
);
5649 * Update the size and position.
5651 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
5652 * be called automatically.
5654 * @param {boolean} [transition=false] Use a smooth transition
5657 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
5660 // Prevent transition from being interrupted
5661 clearTimeout( this.transitionTimeout
);
5663 // Enable transition
5664 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
5670 // Prevent transitioning after transition is complete
5671 this.transitionTimeout
= setTimeout( function () {
5672 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
5675 // Prevent transitioning immediately
5676 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
5683 OO
.ui
.PopupWidget
.prototype.computePosition = function () {
5684 var direction
, align
, vertical
, start
, end
, near
, far
, sizeProp
, popupSize
, anchorSize
,
5685 anchorPos
, anchorOffset
, anchorMargin
, parentPosition
, positionProp
, positionAdjustment
,
5686 floatablePos
, offsetParentPos
, containerPos
, popupPosition
, viewportSpacing
,
5688 anchorCss
= { left
: '', right
: '', top
: '', bottom
: '' },
5689 popupPositionOppositeMap
= {
5697 'force-left': 'backwards',
5698 'force-right': 'forwards'
5701 'force-left': 'forwards',
5702 'force-right': 'backwards'
5714 backwards
: this.anchored
? 'before' : 'end'
5722 if ( !this.$container
) {
5723 // Lazy-initialize $container if not specified in constructor
5724 this.$container
= $( this.getClosestScrollableElementContainer() );
5726 direction
= this.$container
.css( 'direction' );
5728 // Set height and width before we do anything else, since it might cause our measurements
5729 // to change (e.g. due to scrollbars appearing or disappearing), and it also affects centering
5731 width
: this.width
!== null ? this.width
: 'auto',
5732 height
: this.height
!== null ? this.height
: 'auto'
5735 align
= alignMap
[ direction
][ this.align
] || this.align
;
5736 popupPosition
= this.popupPosition
;
5737 if ( this.isAutoFlipped
) {
5738 popupPosition
= popupPositionOppositeMap
[ popupPosition
];
5741 // If the popup is positioned before or after, then the anchor positioning is vertical,
5742 // otherwise horizontal
5743 vertical
= popupPosition
=== 'before' || popupPosition
=== 'after';
5744 start
= vertical
? 'top' : ( direction
=== 'rtl' ? 'right' : 'left' );
5745 end
= vertical
? 'bottom' : ( direction
=== 'rtl' ? 'left' : 'right' );
5746 near
= vertical
? 'top' : 'left';
5747 far
= vertical
? 'bottom' : 'right';
5748 sizeProp
= vertical
? 'Height' : 'Width';
5749 popupSize
= vertical
?
5750 ( this.height
|| this.$popup
.height() ) :
5751 ( this.width
|| this.$popup
.width() );
5753 this.setAnchorEdge( anchorEdgeMap
[ popupPosition
] );
5754 this.horizontalPosition
= vertical
? popupPosition
: hPosMap
[ align
];
5755 this.verticalPosition
= vertical
? vPosMap
[ align
] : popupPosition
;
5758 parentPosition
= OO
.ui
.mixin
.FloatableElement
.prototype.computePosition
.call( this );
5759 // Find out which property FloatableElement used for positioning, and adjust that value
5760 positionProp
= vertical
?
5761 ( parentPosition
.top
!== '' ? 'top' : 'bottom' ) :
5762 ( parentPosition
.left
!== '' ? 'left' : 'right' );
5764 // Figure out where the near and far edges of the popup and $floatableContainer are
5765 floatablePos
= this.$floatableContainer
.offset();
5766 floatablePos
[ far
] = floatablePos
[ near
] + this.$floatableContainer
[ 'outer' + sizeProp
]();
5767 // Measure where the offsetParent is and compute our position based on that and parentPosition
5768 offsetParentPos
= this.$element
.offsetParent()[ 0 ] === document
.documentElement
?
5769 { top
: 0, left
: 0 } :
5770 this.$element
.offsetParent().offset();
5772 if ( positionProp
=== near
) {
5773 popupPos
[ near
] = offsetParentPos
[ near
] + parentPosition
[ near
];
5774 popupPos
[ far
] = popupPos
[ near
] + popupSize
;
5776 popupPos
[ far
] = offsetParentPos
[ near
] +
5777 this.$element
.offsetParent()[ 'inner' + sizeProp
]() - parentPosition
[ far
];
5778 popupPos
[ near
] = popupPos
[ far
] - popupSize
;
5781 if ( this.anchored
) {
5782 // Position the anchor (which is positioned relative to the popup) to point to
5783 // $floatableContainer
5784 anchorPos
= ( floatablePos
[ start
] + floatablePos
[ end
] ) / 2;
5785 anchorOffset
= ( start
=== far
? -1 : 1 ) * ( anchorPos
- popupPos
[ start
] );
5787 // If the anchor is less than 2*anchorSize from either edge, move the popup to make more
5788 // space this.$anchor.width()/height() returns 0 because of the CSS trickery we use, so use
5789 // scrollWidth/Height
5790 anchorSize
= this.$anchor
[ 0 ][ 'scroll' + sizeProp
];
5791 anchorMargin
= parseFloat( this.$anchor
.css( 'margin-' + start
) );
5792 if ( anchorOffset
+ anchorMargin
< 2 * anchorSize
) {
5793 // Not enough space for the anchor on the start side; pull the popup startwards
5794 positionAdjustment
= ( positionProp
=== start
? -1 : 1 ) *
5795 ( 2 * anchorSize
- ( anchorOffset
+ anchorMargin
) );
5796 } else if ( anchorOffset
+ anchorMargin
> popupSize
- 2 * anchorSize
) {
5797 // Not enough space for the anchor on the end side; pull the popup endwards
5798 positionAdjustment
= ( positionProp
=== end
? -1 : 1 ) *
5799 ( anchorOffset
+ anchorMargin
- ( popupSize
- 2 * anchorSize
) );
5801 positionAdjustment
= 0;
5804 positionAdjustment
= 0;
5807 // Check if the popup will go beyond the edge of this.$container
5808 containerPos
= this.$container
[ 0 ] === document
.documentElement
?
5809 { top
: 0, left
: 0 } :
5810 this.$container
.offset();
5811 containerPos
[ far
] = containerPos
[ near
] + this.$container
[ 'inner' + sizeProp
]();
5812 if ( this.$container
[ 0 ] === document
.documentElement
) {
5813 viewportSpacing
= OO
.ui
.getViewportSpacing();
5814 containerPos
[ near
] += viewportSpacing
[ near
];
5815 containerPos
[ far
] -= viewportSpacing
[ far
];
5817 // Take into account how much the popup will move because of the adjustments we're going to make
5818 popupPos
[ near
] += ( positionProp
=== near
? 1 : -1 ) * positionAdjustment
;
5819 popupPos
[ far
] += ( positionProp
=== near
? 1 : -1 ) * positionAdjustment
;
5820 if ( containerPos
[ near
] + this.containerPadding
> popupPos
[ near
] ) {
5821 // Popup goes beyond the near (left/top) edge, move it to the right/bottom
5822 positionAdjustment
+= ( positionProp
=== near
? 1 : -1 ) *
5823 ( containerPos
[ near
] + this.containerPadding
- popupPos
[ near
] );
5824 } else if ( containerPos
[ far
] - this.containerPadding
< popupPos
[ far
] ) {
5825 // Popup goes beyond the far (right/bottom) edge, move it to the left/top
5826 positionAdjustment
+= ( positionProp
=== far
? 1 : -1 ) *
5827 ( popupPos
[ far
] - ( containerPos
[ far
] - this.containerPadding
) );
5830 if ( this.anchored
) {
5831 // Adjust anchorOffset for positionAdjustment
5832 anchorOffset
+= ( positionProp
=== start
? -1 : 1 ) * positionAdjustment
;
5834 // Position the anchor
5835 anchorCss
[ start
] = anchorOffset
;
5836 this.$anchor
.css( anchorCss
);
5839 // Move the popup if needed
5840 parentPosition
[ positionProp
] += positionAdjustment
;
5842 return parentPosition
;
5846 * Set popup alignment
5848 * @param {string} [align=center] Alignment of the popup, `center`, `force-left`, `force-right`,
5849 * `backwards` or `forwards`.
5851 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
5852 // Validate alignment
5853 if ( [ 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
5856 this.align
= 'center';
5862 * Get popup alignment
5864 * @return {string} Alignment of the popup, `center`, `force-left`, `force-right`,
5865 * `backwards` or `forwards`.
5867 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
5872 * Change the positioning of the popup.
5874 * @param {string} position 'above', 'below', 'before' or 'after'
5876 OO
.ui
.PopupWidget
.prototype.setPosition = function ( position
) {
5877 if ( [ 'above', 'below', 'before', 'after' ].indexOf( position
) === -1 ) {
5880 this.popupPosition
= position
;
5885 * Get popup positioning.
5887 * @return {string} 'above', 'below', 'before' or 'after'
5889 OO
.ui
.PopupWidget
.prototype.getPosition = function () {
5890 return this.popupPosition
;
5894 * Set popup auto-flipping.
5896 * @param {boolean} autoFlip Whether to automatically switch the popup's position between
5897 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5898 * desired direction to display the popup without clipping
5900 OO
.ui
.PopupWidget
.prototype.setAutoFlip = function ( autoFlip
) {
5901 autoFlip
= !!autoFlip
;
5903 if ( this.autoFlip
!== autoFlip
) {
5904 this.autoFlip
= autoFlip
;
5909 * Set which elements will not close the popup when clicked.
5911 * For auto-closing popups, clicks on these elements will not cause the popup to auto-close.
5913 * @param {jQuery} $autoCloseIgnore Elements to ignore for auto-closing
5915 OO
.ui
.PopupWidget
.prototype.setAutoCloseIgnore = function ( $autoCloseIgnore
) {
5916 this.$autoCloseIgnore
= $autoCloseIgnore
;
5920 * Get an ID of the body element, this can be used as the
5921 * `aria-describedby` attribute for an input field.
5923 * @return {string} The ID of the body element
5925 OO
.ui
.PopupWidget
.prototype.getBodyId = function () {
5926 var id
= this.$body
.attr( 'id' );
5927 if ( id
=== undefined ) {
5928 id
= OO
.ui
.generateElementId();
5929 this.$body
.attr( 'id', id
);
5935 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5936 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5937 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5938 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5944 * @param {Object} [config] Configuration options
5945 * @cfg {Object} [popup] Configuration to pass to popup
5946 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5948 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
5949 // Configuration initialization
5950 config
= config
|| {};
5953 this.popup
= new OO
.ui
.PopupWidget( $.extend(
5956 $floatableContainer
: this.$element
5960 $autoCloseIgnore
: this.$element
.add( config
.popup
&& config
.popup
.$autoCloseIgnore
)
5970 * @return {OO.ui.PopupWidget} Popup widget
5972 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
5977 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
5978 * which is used to display additional information or options.
5981 * // A PopupButtonWidget.
5982 * var popupButton = new OO.ui.PopupButtonWidget( {
5983 * label: 'Popup button with options',
5986 * $content: $( '<p>Additional options here.</p>' ),
5988 * align: 'force-left'
5991 * // Append the button to the DOM.
5992 * $( document.body ).append( popupButton.$element );
5995 * @extends OO.ui.ButtonWidget
5996 * @mixins OO.ui.mixin.PopupElement
5999 * @param {Object} [config] Configuration options
6000 * @cfg {jQuery} [$overlay] Render the popup into a separate layer. This configuration is useful
6001 * in cases where the expanded popup is larger than its containing `<div>`. The specified overlay
6002 * layer is usually on top of the containing `<div>` and has a larger area. By default, the popup
6003 * uses relative positioning.
6004 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
6006 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
6007 // Configuration initialization
6008 config
= config
|| {};
6010 // Parent constructor
6011 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
6013 // Mixin constructors
6014 OO
.ui
.mixin
.PopupElement
.call( this, config
);
6017 this.$overlay
= ( config
.$overlay
=== true ?
6018 OO
.ui
.getDefaultOverlay() : config
.$overlay
) || this.$element
;
6021 this.connect( this, {
6026 this.$element
.addClass( 'oo-ui-popupButtonWidget' );
6028 .addClass( 'oo-ui-popupButtonWidget-popup' )
6029 .toggleClass( 'oo-ui-popupButtonWidget-framed-popup', this.isFramed() )
6030 .toggleClass( 'oo-ui-popupButtonWidget-frameless-popup', !this.isFramed() );
6031 this.$overlay
.append( this.popup
.$element
);
6036 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
6037 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
6042 * Handle the button action being triggered.
6046 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
6047 this.popup
.toggle();
6051 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
6053 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
6058 * @mixins OO.ui.mixin.GroupElement
6061 * @param {Object} [config] Configuration options
6063 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
6064 // Mixin constructors
6065 OO
.ui
.mixin
.GroupElement
.call( this, config
);
6070 OO
.mixinClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
6075 * Set the disabled state of the widget.
6077 * This will also update the disabled state of child widgets.
6079 * @param {boolean} disabled Disable widget
6081 * @return {OO.ui.Widget} The widget, for chaining
6083 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
6087 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
6088 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
6090 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
6092 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6093 this.items
[ i
].updateDisabled();
6101 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
6103 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group.
6104 * This allows bidirectional communication.
6106 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
6114 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
6121 * Check if widget is disabled.
6123 * Checks parent if present, making disabled state inheritable.
6125 * @return {boolean} Widget is disabled
6127 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
6128 return this.disabled
||
6129 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
6133 * Set group element is in.
6135 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
6137 * @return {OO.ui.Widget} The widget, for chaining
6139 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
6141 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
6142 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
6144 // Initialize item disabled states
6145 this.updateDisabled();
6151 * OptionWidgets are special elements that can be selected and configured with data. The
6152 * data is often unique for each option, but it does not have to be. OptionWidgets are used
6153 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
6154 * and examples, please see the [OOUI documentation on MediaWiki][1].
6156 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6159 * @extends OO.ui.Widget
6160 * @mixins OO.ui.mixin.ItemWidget
6161 * @mixins OO.ui.mixin.LabelElement
6162 * @mixins OO.ui.mixin.FlaggedElement
6163 * @mixins OO.ui.mixin.AccessKeyedElement
6164 * @mixins OO.ui.mixin.TitledElement
6167 * @param {Object} [config] Configuration options
6169 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
6170 // Configuration initialization
6171 config
= config
|| {};
6173 // Parent constructor
6174 OO
.ui
.OptionWidget
.parent
.call( this, config
);
6176 // Mixin constructors
6177 OO
.ui
.mixin
.ItemWidget
.call( this );
6178 OO
.ui
.mixin
.LabelElement
.call( this, config
);
6179 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
6180 OO
.ui
.mixin
.AccessKeyedElement
.call( this, config
);
6181 OO
.ui
.mixin
.TitledElement
.call( this, config
);
6184 this.highlighted
= false;
6185 this.pressed
= false;
6186 this.setSelected( !!config
.selected
);
6190 .data( 'oo-ui-optionWidget', this )
6191 // Allow programmatic focussing (and by access key), but not tabbing
6192 .attr( 'tabindex', '-1' )
6193 .attr( 'role', 'option' )
6194 .addClass( 'oo-ui-optionWidget' )
6195 .append( this.$label
);
6200 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
6201 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
6202 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
6203 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
6204 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
6205 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.TitledElement
);
6207 /* Static Properties */
6210 * Whether this option can be selected. See #setSelected.
6214 * @property {boolean}
6216 OO
.ui
.OptionWidget
.static.selectable
= true;
6219 * Whether this option can be highlighted. See #setHighlighted.
6223 * @property {boolean}
6225 OO
.ui
.OptionWidget
.static.highlightable
= true;
6228 * Whether this option can be pressed. See #setPressed.
6232 * @property {boolean}
6234 OO
.ui
.OptionWidget
.static.pressable
= true;
6237 * Whether this option will be scrolled into view when it is selected.
6241 * @property {boolean}
6243 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
6248 * Check if the option can be selected.
6250 * @return {boolean} Item is selectable
6252 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
6253 return this.constructor.static.selectable
&& !this.disabled
&& this.isVisible();
6257 * Check if the option can be highlighted. A highlight indicates that the option
6258 * may be selected when a user presses Enter key or clicks. Disabled items cannot
6261 * @return {boolean} Item is highlightable
6263 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
6264 return this.constructor.static.highlightable
&& !this.disabled
&& this.isVisible();
6268 * Check if the option can be pressed. The pressed state occurs when a user mouses
6269 * down on an item, but has not yet let go of the mouse.
6271 * @return {boolean} Item is pressable
6273 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
6274 return this.constructor.static.pressable
&& !this.disabled
&& this.isVisible();
6278 * Check if the option is selected.
6280 * @return {boolean} Item is selected
6282 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
6283 return this.selected
;
6287 * Check if the option is highlighted. A highlight indicates that the
6288 * item may be selected when a user presses Enter key or clicks.
6290 * @return {boolean} Item is highlighted
6292 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
6293 return this.highlighted
;
6297 * Check if the option is pressed. The pressed state occurs when a user mouses
6298 * down on an item, but has not yet let go of the mouse. The item may appear
6299 * selected, but it will not be selected until the user releases the mouse.
6301 * @return {boolean} Item is pressed
6303 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
6304 return this.pressed
;
6308 * Set the option’s selected state. In general, all modifications to the selection
6309 * should be handled by the SelectWidget’s
6310 * {@link OO.ui.SelectWidget#selectItem selectItem( [item] )} method instead of this method.
6312 * @param {boolean} [state=false] Select option
6314 * @return {OO.ui.Widget} The widget, for chaining
6316 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
6317 if ( this.constructor.static.selectable
) {
6318 this.selected
= !!state
;
6320 .toggleClass( 'oo-ui-optionWidget-selected', state
)
6321 .attr( 'aria-selected', state
.toString() );
6322 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
6323 this.scrollElementIntoView();
6325 this.updateThemeClasses();
6331 * Set the option’s highlighted state. In general, all programmatic
6332 * modifications to the highlight should be handled by the
6333 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
6334 * method instead of this method.
6336 * @param {boolean} [state=false] Highlight option
6338 * @return {OO.ui.Widget} The widget, for chaining
6340 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
6341 if ( this.constructor.static.highlightable
) {
6342 this.highlighted
= !!state
;
6343 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
6344 this.updateThemeClasses();
6350 * Set the option’s pressed state. In general, all
6351 * programmatic modifications to the pressed state should be handled by the
6352 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
6353 * method instead of this method.
6355 * @param {boolean} [state=false] Press option
6357 * @return {OO.ui.Widget} The widget, for chaining
6359 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
6360 if ( this.constructor.static.pressable
) {
6361 this.pressed
= !!state
;
6362 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
6363 this.updateThemeClasses();
6369 * Get text to match search strings against.
6371 * The default implementation returns the label text, but subclasses
6372 * can override this to provide more complex behavior.
6374 * @return {string|boolean} String to match search string against
6376 OO
.ui
.OptionWidget
.prototype.getMatchText = function () {
6377 var label
= this.getLabel();
6378 return typeof label
=== 'string' ? label
: this.$label
.text();
6382 * A SelectWidget is of a generic selection of options. The OOUI library contains several types of
6383 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
6384 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
6387 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For
6388 * more information, please see the [OOUI documentation on MediaWiki][1].
6391 * // A select widget with three options.
6392 * var select = new OO.ui.SelectWidget( {
6394 * new OO.ui.OptionWidget( {
6396 * label: 'Option One',
6398 * new OO.ui.OptionWidget( {
6400 * label: 'Option Two',
6402 * new OO.ui.OptionWidget( {
6404 * label: 'Option Three',
6408 * $( document.body ).append( select.$element );
6410 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6414 * @extends OO.ui.Widget
6415 * @mixins OO.ui.mixin.GroupWidget
6418 * @param {Object} [config] Configuration options
6419 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
6420 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
6421 * the [OOUI documentation on MediaWiki] [2] for examples.
6422 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6424 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
6425 // Configuration initialization
6426 config
= config
|| {};
6428 // Parent constructor
6429 OO
.ui
.SelectWidget
.parent
.call( this, config
);
6431 // Mixin constructors
6432 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {
6433 $group
: this.$element
6437 this.pressed
= false;
6438 this.selecting
= null;
6439 this.onDocumentMouseUpHandler
= this.onDocumentMouseUp
.bind( this );
6440 this.onDocumentMouseMoveHandler
= this.onDocumentMouseMove
.bind( this );
6441 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
6442 this.onDocumentKeyPressHandler
= this.onDocumentKeyPress
.bind( this );
6443 this.keyPressBuffer
= '';
6444 this.keyPressBufferTimer
= null;
6445 this.blockMouseOverEvents
= 0;
6448 this.connect( this, {
6452 focusin
: this.onFocus
.bind( this ),
6453 mousedown
: this.onMouseDown
.bind( this ),
6454 mouseover
: this.onMouseOver
.bind( this ),
6455 mouseleave
: this.onMouseLeave
.bind( this )
6460 // -depressed is a deprecated alias of -unpressed
6461 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-unpressed oo-ui-selectWidget-depressed' )
6462 .attr( 'role', 'listbox' );
6463 this.setFocusOwner( this.$element
);
6464 if ( Array
.isArray( config
.items
) ) {
6465 this.addItems( config
.items
);
6471 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
6472 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
6479 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
6481 * @param {OO.ui.OptionWidget|null} item Highlighted item
6487 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
6488 * pressed state of an option.
6490 * @param {OO.ui.OptionWidget|null} item Pressed item
6496 * A `select` event is emitted when the selection is modified programmatically with the #selectItem
6499 * @param {OO.ui.OptionWidget|null} item Selected item
6504 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
6505 * @param {OO.ui.OptionWidget} item Chosen item
6511 * An `add` event is emitted when options are added to the select with the #addItems method.
6513 * @param {OO.ui.OptionWidget[]} items Added items
6514 * @param {number} index Index of insertion point
6520 * A `remove` event is emitted when options are removed from the select with the #clearItems
6521 * or #removeItems methods.
6523 * @param {OO.ui.OptionWidget[]} items Removed items
6526 /* Static methods */
6529 * Normalize text for filter matching
6531 * @param {string} text Text
6532 * @return {string} Normalized text
6534 OO
.ui
.SelectWidget
.static.normalizeForMatching = function ( text
) {
6535 // Replace trailing whitespace, normalize multiple spaces and make case insensitive
6536 var normalized
= text
.trim().replace( /\s+/, ' ' ).toLowerCase();
6538 // Normalize Unicode
6539 // eslint-disable-next-line no-restricted-properties
6540 if ( normalized
.normalize
) {
6541 // eslint-disable-next-line no-restricted-properties
6542 normalized
= normalized
.normalize();
6550 * Handle focus events
6553 * @param {jQuery.Event} event
6555 OO
.ui
.SelectWidget
.prototype.onFocus = function ( event
) {
6557 if ( event
.target
=== this.$element
[ 0 ] ) {
6558 // This widget was focussed, e.g. by the user tabbing to it.
6559 // The styles for focus state depend on one of the items being selected.
6560 if ( !this.findSelectedItem() ) {
6561 item
= this.findFirstSelectableItem();
6564 if ( event
.target
.tabIndex
=== -1 ) {
6565 // One of the options got focussed (and the event bubbled up here).
6566 // They can't be tabbed to, but they can be activated using access keys.
6567 // OptionWidgets and focusable UI elements inside them have tabindex="-1" set.
6568 item
= this.findTargetItem( event
);
6570 // There is something actually user-focusable in one of the labels of the options, and
6571 // the user focussed it (e.g. by tabbing to it). Do nothing (especially, don't change
6578 if ( item
.constructor.static.highlightable
) {
6579 this.highlightItem( item
);
6581 this.selectItem( item
);
6585 if ( event
.target
!== this.$element
[ 0 ] ) {
6586 this.$focusOwner
.trigger( 'focus' );
6591 * Handle mouse down events.
6594 * @param {jQuery.Event} e Mouse down event
6595 * @return {undefined/boolean} False to prevent default if event is handled
6597 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
6600 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
6601 this.togglePressed( true );
6602 item
= this.findTargetItem( e
);
6603 if ( item
&& item
.isSelectable() ) {
6604 this.pressItem( item
);
6605 this.selecting
= item
;
6606 this.getElementDocument().addEventListener( 'mouseup', this.onDocumentMouseUpHandler
, true );
6607 this.getElementDocument().addEventListener( 'mousemove', this.onDocumentMouseMoveHandler
, true );
6614 * Handle document mouse up events.
6617 * @param {MouseEvent} e Mouse up event
6618 * @return {undefined/boolean} False to prevent default if event is handled
6620 OO
.ui
.SelectWidget
.prototype.onDocumentMouseUp = function ( e
) {
6623 this.togglePressed( false );
6624 if ( !this.selecting
) {
6625 item
= this.findTargetItem( e
);
6626 if ( item
&& item
.isSelectable() ) {
6627 this.selecting
= item
;
6630 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
&& this.selecting
) {
6631 this.pressItem( null );
6632 this.chooseItem( this.selecting
);
6633 this.selecting
= null;
6636 this.getElementDocument().removeEventListener( 'mouseup', this.onDocumentMouseUpHandler
, true );
6637 this.getElementDocument().removeEventListener( 'mousemove', this.onDocumentMouseMoveHandler
, true );
6643 * Handle document mouse move events.
6646 * @param {MouseEvent} e Mouse move event
6648 OO
.ui
.SelectWidget
.prototype.onDocumentMouseMove = function ( e
) {
6651 if ( !this.isDisabled() && this.pressed
) {
6652 item
= this.findTargetItem( e
);
6653 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
6654 this.pressItem( item
);
6655 this.selecting
= item
;
6661 * Handle mouse over events.
6664 * @param {jQuery.Event} e Mouse over event
6665 * @return {undefined/boolean} False to prevent default if event is handled
6667 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
6669 if ( this.blockMouseOverEvents
) {
6672 if ( !this.isDisabled() ) {
6673 item
= this.findTargetItem( e
);
6674 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
6680 * Handle mouse leave events.
6683 * @param {jQuery.Event} e Mouse over event
6684 * @return {undefined/boolean} False to prevent default if event is handled
6686 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
6687 if ( !this.isDisabled() ) {
6688 this.highlightItem( null );
6694 * Handle document key down events.
6697 * @param {KeyboardEvent} e Key down event
6699 OO
.ui
.SelectWidget
.prototype.onDocumentKeyDown = function ( e
) {
6702 currentItem
= this.findHighlightedItem() || this.findSelectedItem();
6704 if ( !this.isDisabled() && this.isVisible() ) {
6705 switch ( e
.keyCode
) {
6706 case OO
.ui
.Keys
.ENTER
:
6707 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
6708 // Was only highlighted, now let's select it. No-op if already selected.
6709 this.chooseItem( currentItem
);
6714 case OO
.ui
.Keys
.LEFT
:
6715 this.clearKeyPressBuffer();
6716 nextItem
= this.findRelativeSelectableItem( currentItem
, -1 );
6719 case OO
.ui
.Keys
.DOWN
:
6720 case OO
.ui
.Keys
.RIGHT
:
6721 this.clearKeyPressBuffer();
6722 nextItem
= this.findRelativeSelectableItem( currentItem
, 1 );
6725 case OO
.ui
.Keys
.ESCAPE
:
6726 case OO
.ui
.Keys
.TAB
:
6727 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
6728 currentItem
.setHighlighted( false );
6730 this.unbindDocumentKeyDownListener();
6731 this.unbindDocumentKeyPressListener();
6732 // Don't prevent tabbing away / defocusing
6738 if ( nextItem
.constructor.static.highlightable
) {
6739 this.highlightItem( nextItem
);
6741 this.chooseItem( nextItem
);
6743 this.scrollItemIntoView( nextItem
);
6748 e
.stopPropagation();
6754 * Bind document key down listener.
6758 OO
.ui
.SelectWidget
.prototype.bindDocumentKeyDownListener = function () {
6759 this.getElementDocument().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
6763 * Unbind document key down listener.
6767 OO
.ui
.SelectWidget
.prototype.unbindDocumentKeyDownListener = function () {
6768 this.getElementDocument().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
6772 * Scroll item into view, preventing spurious mouse highlight actions from happening.
6774 * @param {OO.ui.OptionWidget} item Item to scroll into view
6776 OO
.ui
.SelectWidget
.prototype.scrollItemIntoView = function ( item
) {
6778 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic
6779 // scrolling and around 100-150 ms after it is finished.
6780 this.blockMouseOverEvents
++;
6781 item
.scrollElementIntoView().done( function () {
6782 setTimeout( function () {
6783 widget
.blockMouseOverEvents
--;
6789 * Clear the key-press buffer
6793 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
6794 if ( this.keyPressBufferTimer
) {
6795 clearTimeout( this.keyPressBufferTimer
);
6796 this.keyPressBufferTimer
= null;
6798 this.keyPressBuffer
= '';
6802 * Handle key press events.
6805 * @param {KeyboardEvent} e Key press event
6806 * @return {undefined/boolean} False to prevent default if event is handled
6808 OO
.ui
.SelectWidget
.prototype.onDocumentKeyPress = function ( e
) {
6809 var c
, filter
, item
;
6811 if ( !e
.charCode
) {
6812 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
6813 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
6818 // eslint-disable-next-line no-restricted-properties
6819 if ( String
.fromCodePoint
) {
6820 // eslint-disable-next-line no-restricted-properties
6821 c
= String
.fromCodePoint( e
.charCode
);
6823 c
= String
.fromCharCode( e
.charCode
);
6826 if ( this.keyPressBufferTimer
) {
6827 clearTimeout( this.keyPressBufferTimer
);
6829 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
6831 item
= this.findHighlightedItem() || this.findSelectedItem();
6833 if ( this.keyPressBuffer
=== c
) {
6834 // Common (if weird) special case: typing "xxxx" will cycle through all
6835 // the items beginning with "x".
6837 item
= this.findRelativeSelectableItem( item
, 1 );
6840 this.keyPressBuffer
+= c
;
6843 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
6844 if ( !item
|| !filter( item
) ) {
6845 item
= this.findRelativeSelectableItem( item
, 1, filter
);
6848 if ( this.isVisible() && item
.constructor.static.highlightable
) {
6849 this.highlightItem( item
);
6851 this.chooseItem( item
);
6853 this.scrollItemIntoView( item
);
6857 e
.stopPropagation();
6861 * Get a matcher for the specific string
6864 * @param {string} query String to match against items
6865 * @param {string} [mode='prefix'] Matching mode: 'substring', 'prefix', or 'exact'
6866 * @return {Function} function ( OO.ui.OptionWidget ) => boolean
6868 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( query
, mode
) {
6869 var normalizeForMatching
= this.constructor.static.normalizeForMatching
,
6870 normalizedQuery
= normalizeForMatching( query
);
6872 // Support deprecated exact=true argument
6873 if ( mode
=== true ) {
6877 return function ( item
) {
6878 var matchText
= normalizeForMatching( item
.getMatchText() );
6880 if ( normalizedQuery
=== '' ) {
6881 // Empty string matches all, except if we are in 'exact'
6882 // mode, where it doesn't match at all
6883 return mode
!== 'exact';
6888 return matchText
=== normalizedQuery
;
6890 return matchText
.indexOf( normalizedQuery
) !== -1;
6893 return matchText
.indexOf( normalizedQuery
) === 0;
6899 * Bind document key press listener.
6903 OO
.ui
.SelectWidget
.prototype.bindDocumentKeyPressListener = function () {
6904 this.getElementDocument().addEventListener( 'keypress', this.onDocumentKeyPressHandler
, true );
6908 * Unbind document key down listener.
6910 * If you override this, be sure to call this.clearKeyPressBuffer() from your
6915 OO
.ui
.SelectWidget
.prototype.unbindDocumentKeyPressListener = function () {
6916 this.getElementDocument().removeEventListener( 'keypress', this.onDocumentKeyPressHandler
, true );
6917 this.clearKeyPressBuffer();
6921 * Visibility change handler
6924 * @param {boolean} visible
6926 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
6928 this.clearKeyPressBuffer();
6933 * Get the closest item to a jQuery.Event.
6936 * @param {jQuery.Event} e
6937 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
6939 OO
.ui
.SelectWidget
.prototype.findTargetItem = function ( e
) {
6940 var $option
= $( e
.target
).closest( '.oo-ui-optionWidget' );
6941 if ( !$option
.closest( '.oo-ui-selectWidget' ).is( this.$element
) ) {
6944 return $option
.data( 'oo-ui-optionWidget' ) || null;
6948 * Find selected item.
6950 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
6952 OO
.ui
.SelectWidget
.prototype.findSelectedItem = function () {
6955 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6956 if ( this.items
[ i
].isSelected() ) {
6957 return this.items
[ i
];
6964 * Find highlighted item.
6966 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
6968 OO
.ui
.SelectWidget
.prototype.findHighlightedItem = function () {
6971 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6972 if ( this.items
[ i
].isHighlighted() ) {
6973 return this.items
[ i
];
6980 * Toggle pressed state.
6982 * Press is a state that occurs when a user mouses down on an item, but
6983 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
6984 * until the user releases the mouse.
6986 * @param {boolean} pressed An option is being pressed
6988 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
6989 if ( pressed
=== undefined ) {
6990 pressed
= !this.pressed
;
6992 if ( pressed
!== this.pressed
) {
6994 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
6995 // -depressed is a deprecated alias of -unpressed
6996 .toggleClass( 'oo-ui-selectWidget-unpressed oo-ui-selectWidget-depressed', !pressed
);
6997 this.pressed
= pressed
;
7002 * Highlight an option. If the `item` param is omitted, no options will be highlighted
7003 * and any existing highlight will be removed. The highlight is mutually exclusive.
7005 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
7008 * @return {OO.ui.Widget} The widget, for chaining
7010 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
7011 var i
, len
, highlighted
,
7014 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
7015 highlighted
= this.items
[ i
] === item
;
7016 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
7017 this.items
[ i
].setHighlighted( highlighted
);
7023 this.$focusOwner
.attr( 'aria-activedescendant', item
.getElementId() );
7025 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
7027 this.emit( 'highlight', item
);
7034 * Fetch an item by its label.
7036 * @param {string} label Label of the item to select.
7037 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
7038 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
7040 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
7042 len
= this.items
.length
,
7043 filter
= this.getItemMatcher( label
, 'exact' );
7045 for ( i
= 0; i
< len
; i
++ ) {
7046 item
= this.items
[ i
];
7047 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
7054 filter
= this.getItemMatcher( label
, 'prefix' );
7055 for ( i
= 0; i
< len
; i
++ ) {
7056 item
= this.items
[ i
];
7057 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
7073 * Programmatically select an option by its label. If the item does not exist,
7074 * all options will be deselected.
7076 * @param {string} [label] Label of the item to select.
7077 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
7080 * @return {OO.ui.Widget} The widget, for chaining
7082 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
7083 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
7084 if ( label
=== undefined || !itemFromLabel
) {
7085 return this.selectItem();
7087 return this.selectItem( itemFromLabel
);
7091 * Programmatically select an option by its data. If the `data` parameter is omitted,
7092 * or if the item does not exist, all options will be deselected.
7094 * @param {Object|string} [data] Value of the item to select, omit to deselect all
7097 * @return {OO.ui.Widget} The widget, for chaining
7099 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
7100 var itemFromData
= this.findItemFromData( data
);
7101 if ( data
=== undefined || !itemFromData
) {
7102 return this.selectItem();
7104 return this.selectItem( itemFromData
);
7108 * Programmatically select an option by its reference. If the `item` parameter is omitted,
7109 * all options will be deselected.
7111 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
7114 * @return {OO.ui.Widget} The widget, for chaining
7116 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
7117 var i
, len
, selected
,
7120 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
7121 selected
= this.items
[ i
] === item
;
7122 if ( this.items
[ i
].isSelected() !== selected
) {
7123 this.items
[ i
].setSelected( selected
);
7128 if ( item
&& !item
.constructor.static.highlightable
) {
7130 this.$focusOwner
.attr( 'aria-activedescendant', item
.getElementId() );
7132 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
7135 this.emit( 'select', item
);
7144 * Press is a state that occurs when a user mouses down on an item, but has not
7145 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
7146 * releases the mouse.
7148 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
7151 * @return {OO.ui.Widget} The widget, for chaining
7153 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
7154 var i
, len
, pressed
,
7157 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
7158 pressed
= this.items
[ i
] === item
;
7159 if ( this.items
[ i
].isPressed() !== pressed
) {
7160 this.items
[ i
].setPressed( pressed
);
7165 this.emit( 'press', item
);
7174 * Note that ‘choose’ should never be modified programmatically. A user can choose
7175 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
7176 * use the #selectItem method.
7178 * This method is identical to #selectItem, but may vary in subclasses that take additional action
7179 * when users choose an item with the keyboard or mouse.
7181 * @param {OO.ui.OptionWidget} item Item to choose
7184 * @return {OO.ui.Widget} The widget, for chaining
7186 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
7188 this.selectItem( item
);
7189 this.emit( 'choose', item
);
7196 * Find an option by its position relative to the specified item (or to the start of the option
7197 * array, if item is `null`). The direction in which to search through the option array is specified
7198 * with a number: -1 for reverse (the default) or 1 for forward. The method will return an option,
7199 * or `null` if there are no options in the array.
7201 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at
7202 * the beginning of the array.
7203 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
7204 * @param {Function} [filter] Only consider items for which this function returns
7205 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
7206 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
7208 OO
.ui
.SelectWidget
.prototype.findRelativeSelectableItem = function ( item
, direction
, filter
) {
7209 var currentIndex
, nextIndex
, i
,
7210 increase
= direction
> 0 ? 1 : -1,
7211 len
= this.items
.length
;
7213 if ( item
instanceof OO
.ui
.OptionWidget
) {
7214 currentIndex
= this.items
.indexOf( item
);
7215 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
7217 // If no item is selected and moving forward, start at the beginning.
7218 // If moving backward, start at the end.
7219 nextIndex
= direction
> 0 ? 0 : len
- 1;
7222 for ( i
= 0; i
< len
; i
++ ) {
7223 item
= this.items
[ nextIndex
];
7225 item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() &&
7226 ( !filter
|| filter( item
) )
7230 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
7236 * Find the next selectable item or `null` if there are no selectable items.
7237 * Disabled options and menu-section markers and breaks are not selectable.
7239 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
7241 OO
.ui
.SelectWidget
.prototype.findFirstSelectableItem = function () {
7242 return this.findRelativeSelectableItem( null, 1 );
7246 * Add an array of options to the select. Optionally, an index number can be used to
7247 * specify an insertion point.
7249 * @param {OO.ui.OptionWidget[]} items Items to add
7250 * @param {number} [index] Index to insert items after
7253 * @return {OO.ui.Widget} The widget, for chaining
7255 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
7257 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
7259 // Always provide an index, even if it was omitted
7260 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
7266 * Remove the specified array of options from the select. Options will be detached
7267 * from the DOM, not removed, so they can be reused later. To remove all options from
7268 * the select, you may wish to use the #clearItems method instead.
7270 * @param {OO.ui.OptionWidget[]} items Items to remove
7273 * @return {OO.ui.Widget} The widget, for chaining
7275 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
7278 // Deselect items being removed
7279 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
7281 if ( item
.isSelected() ) {
7282 this.selectItem( null );
7287 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
7289 this.emit( 'remove', items
);
7295 * Clear all options from the select. Options will be detached from the DOM, not removed,
7296 * so that they can be reused later. To remove a subset of options from the select, use
7297 * the #removeItems method.
7301 * @return {OO.ui.Widget} The widget, for chaining
7303 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
7304 var items
= this.items
.slice();
7307 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
7310 this.selectItem( null );
7312 this.emit( 'remove', items
);
7318 * Set the DOM element which has focus while the user is interacting with this SelectWidget.
7320 * This is used to set `aria-activedescendant` and `aria-expanded` on it.
7323 * @param {jQuery} $focusOwner
7325 OO
.ui
.SelectWidget
.prototype.setFocusOwner = function ( $focusOwner
) {
7326 this.$focusOwner
= $focusOwner
;
7330 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
7331 * with an {@link OO.ui.mixin.IconElement icon} and/or
7332 * {@link OO.ui.mixin.IndicatorElement indicator}.
7333 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
7334 * options. For more information about options and selects, please see the
7335 * [OOUI documentation on MediaWiki][1].
7338 * // Decorated options in a select widget.
7339 * var select = new OO.ui.SelectWidget( {
7341 * new OO.ui.DecoratedOptionWidget( {
7343 * label: 'Option with icon',
7346 * new OO.ui.DecoratedOptionWidget( {
7348 * label: 'Option with indicator',
7353 * $( document.body ).append( select.$element );
7355 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7358 * @extends OO.ui.OptionWidget
7359 * @mixins OO.ui.mixin.IconElement
7360 * @mixins OO.ui.mixin.IndicatorElement
7363 * @param {Object} [config] Configuration options
7365 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
7366 // Parent constructor
7367 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
7369 // Mixin constructors
7370 OO
.ui
.mixin
.IconElement
.call( this, config
);
7371 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
7375 .addClass( 'oo-ui-decoratedOptionWidget' )
7376 .prepend( this.$icon
)
7377 .append( this.$indicator
);
7382 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
7383 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
7384 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
7387 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
7388 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
7389 * the [OOUI documentation on MediaWiki] [1] for more information.
7391 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
7394 * @extends OO.ui.DecoratedOptionWidget
7397 * @param {Object} [config] Configuration options
7399 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
7400 // Parent constructor
7401 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
7404 this.checkIcon
= new OO
.ui
.IconWidget( {
7406 classes
: [ 'oo-ui-menuOptionWidget-checkIcon' ]
7411 .prepend( this.checkIcon
.$element
)
7412 .addClass( 'oo-ui-menuOptionWidget' );
7417 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
7419 /* Static Properties */
7425 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
7428 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to
7429 * group one or more related {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets
7430 * cannot be highlighted or selected.
7433 * var dropdown = new OO.ui.DropdownWidget( {
7436 * new OO.ui.MenuSectionOptionWidget( {
7439 * new OO.ui.MenuOptionWidget( {
7441 * label: 'Welsh Corgi'
7443 * new OO.ui.MenuOptionWidget( {
7445 * label: 'Standard Poodle'
7447 * new OO.ui.MenuSectionOptionWidget( {
7450 * new OO.ui.MenuOptionWidget( {
7457 * $( document.body ).append( dropdown.$element );
7460 * @extends OO.ui.DecoratedOptionWidget
7463 * @param {Object} [config] Configuration options
7465 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
7466 // Parent constructor
7467 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
7471 .addClass( 'oo-ui-menuSectionOptionWidget' )
7472 .removeAttr( 'role aria-selected' );
7473 this.selected
= false;
7478 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
7480 /* Static Properties */
7486 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
7492 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
7495 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
7496 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
7497 * See {@link OO.ui.DropdownWidget DropdownWidget},
7498 * {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}, and
7499 * {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
7500 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
7501 * and customized to be opened, closed, and displayed as needed.
7503 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
7504 * mouse outside the menu.
7506 * Menus also have support for keyboard interaction:
7508 * - Enter/Return key: choose and select a menu option
7509 * - Up-arrow key: highlight the previous menu option
7510 * - Down-arrow key: highlight the next menu option
7511 * - Escape key: hide the menu
7513 * Unlike most widgets, MenuSelectWidget is initially hidden and must be shown by calling #toggle.
7515 * Please see the [OOUI documentation on MediaWiki][1] for more information.
7516 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7519 * @extends OO.ui.SelectWidget
7520 * @mixins OO.ui.mixin.ClippableElement
7521 * @mixins OO.ui.mixin.FloatableElement
7524 * @param {Object} [config] Configuration options
7525 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu
7526 * items that match the text the user types. This config is used by
7527 * {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget} and
7528 * {@link OO.ui.mixin.LookupElement LookupElement}
7529 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
7530 * the text the user types. This config is used by
7531 * {@link OO.ui.TagMultiselectWidget TagMultiselectWidget}
7532 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks
7533 * the mouse anywhere on the page outside of this widget, the menu is hidden. For example, if
7534 * there is a button that toggles the menu's visibility on click, the menu will be hidden then
7535 * re-shown when the user clicks that button, unless the button (or its parent widget) is passed
7537 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
7538 * @cfg {jQuery} [$autoCloseIgnore] If these elements are clicked, don't auto-hide the menu.
7539 * @cfg {boolean} [hideOnChoose=true] Hide the menu when the user chooses an option.
7540 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
7541 * @cfg {boolean} [highlightOnFilter] Highlight the first result when filtering
7542 * @cfg {string} [filterMode='prefix'] The mode by which the menu filters the results.
7543 * Options are 'exact', 'prefix' or 'substring'. See `OO.ui.SelectWidget#getItemMatcher`
7544 * @param {number|string} [width] Width of the menu as a number of pixels or CSS string with unit
7545 * suffix, used by {@link OO.ui.mixin.ClippableElement ClippableElement}
7547 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
7548 // Configuration initialization
7549 config
= config
|| {};
7551 // Parent constructor
7552 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
7554 // Mixin constructors
7555 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( { $clippable
: this.$group
}, config
) );
7556 OO
.ui
.mixin
.FloatableElement
.call( this, config
);
7558 // Initial vertical positions other than 'center' will result in
7559 // the menu being flipped if there is not enough space in the container.
7560 // Store the original position so we know what to reset to.
7561 this.originalVerticalPosition
= this.verticalPosition
;
7564 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
7565 this.hideOnChoose
= config
.hideOnChoose
=== undefined || !!config
.hideOnChoose
;
7566 this.filterFromInput
= !!config
.filterFromInput
;
7567 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
7568 this.$widget
= config
.widget
? config
.widget
.$element
: null;
7569 this.$autoCloseIgnore
= config
.$autoCloseIgnore
|| $( [] );
7570 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
7571 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
7572 this.highlightOnFilter
= !!config
.highlightOnFilter
;
7573 this.lastHighlightedItem
= null;
7574 this.width
= config
.width
;
7575 this.filterMode
= config
.filterMode
;
7578 this.$element
.addClass( 'oo-ui-menuSelectWidget' );
7579 if ( config
.widget
) {
7580 this.setFocusOwner( config
.widget
.$tabIndexed
);
7583 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
7584 // that reference properties not initialized at that time of parent class construction
7585 // TODO: Find a better way to handle post-constructor setup
7586 this.visible
= false;
7587 this.$element
.addClass( 'oo-ui-element-hidden' );
7588 this.$focusOwner
.attr( 'aria-expanded', 'false' );
7593 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
7594 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
7595 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.FloatableElement
);
7602 * The menu is ready: it is visible and has been positioned and clipped.
7605 /* Static properties */
7608 * Positions to flip to if there isn't room in the container for the
7609 * menu in a specific direction.
7611 * @property {Object.<string,string>}
7613 OO
.ui
.MenuSelectWidget
.static.flippedPositions
= {
7623 * Handles document mouse down events.
7626 * @param {MouseEvent} e Mouse down event
7628 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
7632 this.$element
.add( this.$widget
).add( this.$autoCloseIgnore
).get(),
7637 this.toggle( false );
7644 OO
.ui
.MenuSelectWidget
.prototype.onDocumentKeyDown = function ( e
) {
7645 var currentItem
= this.findHighlightedItem() || this.findSelectedItem();
7647 if ( !this.isDisabled() && this.isVisible() ) {
7648 switch ( e
.keyCode
) {
7649 case OO
.ui
.Keys
.LEFT
:
7650 case OO
.ui
.Keys
.RIGHT
:
7651 // Do nothing if a text field is associated, arrow keys will be handled natively
7652 if ( !this.$input
) {
7653 OO
.ui
.MenuSelectWidget
.parent
.prototype.onDocumentKeyDown
.call( this, e
);
7656 case OO
.ui
.Keys
.ESCAPE
:
7657 case OO
.ui
.Keys
.TAB
:
7658 if ( currentItem
) {
7659 currentItem
.setHighlighted( false );
7661 this.toggle( false );
7662 // Don't prevent tabbing away, prevent defocusing
7663 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
7665 e
.stopPropagation();
7669 OO
.ui
.MenuSelectWidget
.parent
.prototype.onDocumentKeyDown
.call( this, e
);
7676 * Update menu item visibility and clipping after input changes (if filterFromInput is enabled)
7677 * or after items were added/removed (always).
7681 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
7682 var i
, item
, items
, visible
, section
, sectionEmpty
, filter
, exactFilter
,
7684 len
= this.items
.length
,
7685 showAll
= !this.isVisible(),
7688 if ( this.$input
&& this.filterFromInput
) {
7689 filter
= showAll
? null : this.getItemMatcher( this.$input
.val(), this.filterMode
);
7690 exactFilter
= this.getItemMatcher( this.$input
.val(), 'exact' );
7691 // Hide non-matching options, and also hide section headers if all options
7692 // in their section are hidden.
7693 for ( i
= 0; i
< len
; i
++ ) {
7694 item
= this.items
[ i
];
7695 if ( item
instanceof OO
.ui
.MenuSectionOptionWidget
) {
7697 // If the previous section was empty, hide its header
7698 section
.toggle( showAll
|| !sectionEmpty
);
7701 sectionEmpty
= true;
7702 } else if ( item
instanceof OO
.ui
.OptionWidget
) {
7703 visible
= showAll
|| filter( item
);
7704 exactMatch
= exactMatch
|| exactFilter( item
);
7705 anyVisible
= anyVisible
|| visible
;
7706 sectionEmpty
= sectionEmpty
&& !visible
;
7707 item
.toggle( visible
);
7710 // Process the final section
7712 section
.toggle( showAll
|| !sectionEmpty
);
7715 if ( anyVisible
&& this.items
.length
&& !exactMatch
) {
7716 this.scrollItemIntoView( this.items
[ 0 ] );
7719 if ( !anyVisible
) {
7720 this.highlightItem( null );
7723 this.$element
.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible
);
7726 this.highlightOnFilter
&&
7727 !( this.lastHighlightedItem
&& this.lastHighlightedItem
.isVisible() )
7729 // Highlight the first item on the list
7731 items
= this.getItems();
7732 for ( i
= 0; i
< items
.length
; i
++ ) {
7733 if ( items
[ i
].isVisible() ) {
7738 this.highlightItem( item
);
7739 this.lastHighlightedItem
= item
;
7744 // Reevaluate clipping
7751 OO
.ui
.MenuSelectWidget
.prototype.bindDocumentKeyDownListener = function () {
7752 if ( this.$input
) {
7753 this.$input
.on( 'keydown', this.onDocumentKeyDownHandler
);
7755 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindDocumentKeyDownListener
.call( this );
7762 OO
.ui
.MenuSelectWidget
.prototype.unbindDocumentKeyDownListener = function () {
7763 if ( this.$input
) {
7764 this.$input
.off( 'keydown', this.onDocumentKeyDownHandler
);
7766 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindDocumentKeyDownListener
.call( this );
7773 OO
.ui
.MenuSelectWidget
.prototype.bindDocumentKeyPressListener = function () {
7774 if ( this.$input
) {
7775 if ( this.filterFromInput
) {
7777 'keydown mouseup cut paste change input select',
7778 this.onInputEditHandler
7780 this.updateItemVisibility();
7783 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindDocumentKeyPressListener
.call( this );
7790 OO
.ui
.MenuSelectWidget
.prototype.unbindDocumentKeyPressListener = function () {
7791 if ( this.$input
) {
7792 if ( this.filterFromInput
) {
7794 'keydown mouseup cut paste change input select',
7795 this.onInputEditHandler
7797 this.updateItemVisibility();
7800 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindDocumentKeyPressListener
.call( this );
7807 * When a user chooses an item, the menu is closed, unless the hideOnChoose config option is
7810 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with
7811 * the keyboard or mouse and it becomes selected. To select an item programmatically,
7812 * use the #selectItem method.
7814 * @param {OO.ui.OptionWidget} item Item to choose
7816 * @return {OO.ui.Widget} The widget, for chaining
7818 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
7819 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
7820 if ( this.hideOnChoose
) {
7821 this.toggle( false );
7829 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
7831 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
7833 this.updateItemVisibility();
7841 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
7843 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
7845 this.updateItemVisibility();
7853 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
7855 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
7857 this.updateItemVisibility();
7863 * Toggle visibility of the menu. The menu is initially hidden and must be shown by calling
7864 * `.toggle( true )` after its #$element is attached to the DOM.
7866 * Do not show the menu while it is not attached to the DOM. The calculations required to display
7867 * it in the right place and with the right dimensions only work correctly while it is attached.
7868 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
7869 * strictly enforced, so currently it only generates a warning in the browser console.
7874 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
7875 var change
, originalHeight
, flippedHeight
;
7877 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
7878 change
= visible
!== this.isVisible();
7880 if ( visible
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
7881 OO
.ui
.warnDeprecation( 'MenuSelectWidget#toggle: Before calling this method, the menu must be attached to the DOM.' );
7882 this.warnedUnattached
= true;
7885 if ( change
&& visible
) {
7886 // Reset position before showing the popup again. It's possible we no longer need to flip
7887 // (e.g. if the user scrolled).
7888 this.setVerticalPosition( this.originalVerticalPosition
);
7892 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
7898 this.setIdealSize( this.width
);
7899 } else if ( this.$floatableContainer
) {
7900 this.$clippable
.css( 'width', 'auto' );
7902 this.$floatableContainer
[ 0 ].offsetWidth
> this.$clippable
[ 0 ].offsetWidth
?
7903 // Dropdown is smaller than handle so expand to width
7904 this.$floatableContainer
[ 0 ].offsetWidth
:
7905 // Dropdown is larger than handle so auto size
7908 this.$clippable
.css( 'width', '' );
7911 this.togglePositioning( !!this.$floatableContainer
);
7912 this.toggleClipping( true );
7914 this.bindDocumentKeyDownListener();
7915 this.bindDocumentKeyPressListener();
7918 ( this.isClippedVertically() || this.isFloatableOutOfView() ) &&
7919 this.originalVerticalPosition
!== 'center'
7921 // If opening the menu in one direction causes it to be clipped, flip it
7922 originalHeight
= this.$element
.height();
7923 this.setVerticalPosition(
7924 this.constructor.static.flippedPositions
[ this.originalVerticalPosition
]
7926 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
7927 // If flipping also causes it to be clipped, open in whichever direction
7928 // we have more space
7929 flippedHeight
= this.$element
.height();
7930 if ( originalHeight
> flippedHeight
) {
7931 this.setVerticalPosition( this.originalVerticalPosition
);
7935 // Note that we do not flip the menu's opening direction if the clipping changes
7936 // later (e.g. after the user scrolls), that seems like it would be annoying
7938 this.$focusOwner
.attr( 'aria-expanded', 'true' );
7940 if ( this.findSelectedItem() ) {
7941 this.$focusOwner
.attr( 'aria-activedescendant', this.findSelectedItem().getElementId() );
7942 this.findSelectedItem().scrollElementIntoView( { duration
: 0 } );
7946 if ( this.autoHide
) {
7947 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
7950 this.emit( 'ready' );
7952 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
7953 this.unbindDocumentKeyDownListener();
7954 this.unbindDocumentKeyPressListener();
7955 this.$focusOwner
.attr( 'aria-expanded', 'false' );
7956 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
7957 this.togglePositioning( false );
7958 this.toggleClipping( false );
7966 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
7967 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
7968 * users can interact with it.
7970 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7971 * OO.ui.DropdownInputWidget instead.
7974 * // A DropdownWidget with a menu that contains three options.
7975 * var dropDown = new OO.ui.DropdownWidget( {
7976 * label: 'Dropdown menu: Select a menu option',
7979 * new OO.ui.MenuOptionWidget( {
7983 * new OO.ui.MenuOptionWidget( {
7987 * new OO.ui.MenuOptionWidget( {
7995 * $( document.body ).append( dropDown.$element );
7997 * dropDown.getMenu().selectItemByData( 'b' );
7999 * dropDown.getMenu().findSelectedItem().getData(); // Returns 'b'.
8001 * For more information, please see the [OOUI documentation on MediaWiki] [1].
8003 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
8006 * @extends OO.ui.Widget
8007 * @mixins OO.ui.mixin.IconElement
8008 * @mixins OO.ui.mixin.IndicatorElement
8009 * @mixins OO.ui.mixin.LabelElement
8010 * @mixins OO.ui.mixin.TitledElement
8011 * @mixins OO.ui.mixin.TabIndexedElement
8014 * @param {Object} [config] Configuration options
8015 * @cfg {Object} [menu] Configuration options to pass to
8016 * {@link OO.ui.MenuSelectWidget menu select widget}.
8017 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful
8018 * in cases where the expanded menu is larger than its containing `<div>`. The specified overlay
8019 * layer is usually on top of the containing `<div>` and has a larger area. By default, the menu
8020 * uses relative positioning.
8021 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
8023 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
8024 // Configuration initialization
8025 config
= $.extend( { indicator
: 'down' }, config
);
8027 // Parent constructor
8028 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
8030 // Properties (must be set before TabIndexedElement constructor call)
8031 this.$handle
= $( '<button>' );
8032 this.$overlay
= ( config
.$overlay
=== true ?
8033 OO
.ui
.getDefaultOverlay() : config
.$overlay
) || this.$element
;
8035 // Mixin constructors
8036 OO
.ui
.mixin
.IconElement
.call( this, config
);
8037 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
8038 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8039 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {
8040 $titled
: this.$label
8042 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {
8043 $tabIndexed
: this.$handle
8047 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend( {
8049 $floatableContainer
: this.$element
8054 click
: this.onClick
.bind( this ),
8055 keydown
: this.onKeyDown
.bind( this ),
8056 // Hack? Handle type-to-search when menu is not expanded and not handling its own events.
8057 keypress
: this.menu
.onDocumentKeyPressHandler
,
8058 blur
: this.menu
.clearKeyPressBuffer
.bind( this.menu
)
8060 this.menu
.connect( this, {
8061 select
: 'onMenuSelect',
8062 toggle
: 'onMenuToggle'
8067 .addClass( 'oo-ui-dropdownWidget-handle' )
8070 'aria-owns': this.menu
.getElementId(),
8071 'aria-haspopup': 'listbox'
8073 .append( this.$icon
, this.$label
, this.$indicator
);
8075 .addClass( 'oo-ui-dropdownWidget' )
8076 .append( this.$handle
);
8077 this.$overlay
.append( this.menu
.$element
);
8082 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
8083 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
8084 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
8085 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
8086 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
8087 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
8094 * @return {OO.ui.MenuSelectWidget} Menu of widget
8096 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
8101 * Handles menu select events.
8104 * @param {OO.ui.MenuOptionWidget} item Selected menu item
8106 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
8110 this.setLabel( null );
8114 selectedLabel
= item
.getLabel();
8116 // If the label is a DOM element, clone it, because setLabel will append() it
8117 if ( selectedLabel
instanceof $ ) {
8118 selectedLabel
= selectedLabel
.clone();
8121 this.setLabel( selectedLabel
);
8125 * Handle menu toggle events.
8128 * @param {boolean} isVisible Open state of the menu
8130 OO
.ui
.DropdownWidget
.prototype.onMenuToggle = function ( isVisible
) {
8131 this.$element
.toggleClass( 'oo-ui-dropdownWidget-open', isVisible
);
8135 * Handle mouse click events.
8138 * @param {jQuery.Event} e Mouse click event
8139 * @return {undefined/boolean} False to prevent default if event is handled
8141 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
8142 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
8149 * Handle key down events.
8152 * @param {jQuery.Event} e Key down event
8153 * @return {undefined/boolean} False to prevent default if event is handled
8155 OO
.ui
.DropdownWidget
.prototype.onKeyDown = function ( e
) {
8157 !this.isDisabled() &&
8159 e
.which
=== OO
.ui
.Keys
.ENTER
||
8161 e
.which
=== OO
.ui
.Keys
.SPACE
&&
8162 // Avoid conflicts with type-to-search, see SelectWidget#onKeyPress.
8163 // Space only closes the menu is the user is not typing to search.
8164 this.menu
.keyPressBuffer
=== ''
8167 !this.menu
.isVisible() &&
8169 e
.which
=== OO
.ui
.Keys
.UP
||
8170 e
.which
=== OO
.ui
.Keys
.DOWN
8181 * RadioOptionWidget is an option widget that looks like a radio button.
8182 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
8183 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8185 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8188 * @extends OO.ui.OptionWidget
8191 * @param {Object} [config] Configuration options
8193 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
8194 // Configuration initialization
8195 config
= config
|| {};
8197 // Properties (must be done before parent constructor which calls #setDisabled)
8198 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
8200 // Parent constructor
8201 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
8204 // Remove implicit role, we're handling it ourselves
8205 this.radio
.$input
.attr( 'role', 'presentation' );
8207 .addClass( 'oo-ui-radioOptionWidget' )
8208 .attr( 'role', 'radio' )
8209 .attr( 'aria-checked', 'false' )
8210 .removeAttr( 'aria-selected' )
8211 .prepend( this.radio
.$element
);
8216 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
8218 /* Static Properties */
8224 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
8230 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
8236 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
8242 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
8249 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
8250 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
8252 this.radio
.setSelected( state
);
8254 .attr( 'aria-checked', state
.toString() )
8255 .removeAttr( 'aria-selected' );
8263 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
8264 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
8266 this.radio
.setDisabled( this.isDisabled() );
8272 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
8273 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
8274 * an interface for adding, removing and selecting options.
8275 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8277 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8278 * OO.ui.RadioSelectInputWidget instead.
8281 * // A RadioSelectWidget with RadioOptions.
8282 * var option1 = new OO.ui.RadioOptionWidget( {
8284 * label: 'Selected radio option'
8286 * option2 = new OO.ui.RadioOptionWidget( {
8288 * label: 'Unselected radio option'
8290 * radioSelect = new OO.ui.RadioSelectWidget( {
8291 * items: [ option1, option2 ]
8294 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
8295 * radioSelect.selectItem( option1 );
8297 * $( document.body ).append( radioSelect.$element );
8299 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8303 * @extends OO.ui.SelectWidget
8304 * @mixins OO.ui.mixin.TabIndexedElement
8307 * @param {Object} [config] Configuration options
8309 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
8310 // Parent constructor
8311 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
8313 // Mixin constructors
8314 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
8318 focus
: this.bindDocumentKeyDownListener
.bind( this ),
8319 blur
: this.unbindDocumentKeyDownListener
.bind( this )
8324 .addClass( 'oo-ui-radioSelectWidget' )
8325 .attr( 'role', 'radiogroup' );
8330 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
8331 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
8334 * MultioptionWidgets are special elements that can be selected and configured with data. The
8335 * data is often unique for each option, but it does not have to be. MultioptionWidgets are used
8336 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
8337 * and examples, please see the [OOUI documentation on MediaWiki][1].
8339 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8342 * @extends OO.ui.Widget
8343 * @mixins OO.ui.mixin.ItemWidget
8344 * @mixins OO.ui.mixin.LabelElement
8345 * @mixins OO.ui.mixin.TitledElement
8348 * @param {Object} [config] Configuration options
8349 * @cfg {boolean} [selected=false] Whether the option is initially selected
8351 OO
.ui
.MultioptionWidget
= function OoUiMultioptionWidget( config
) {
8352 // Configuration initialization
8353 config
= config
|| {};
8355 // Parent constructor
8356 OO
.ui
.MultioptionWidget
.parent
.call( this, config
);
8358 // Mixin constructors
8359 OO
.ui
.mixin
.ItemWidget
.call( this );
8360 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8361 OO
.ui
.mixin
.TitledElement
.call( this, config
);
8364 this.selected
= null;
8368 .addClass( 'oo-ui-multioptionWidget' )
8369 .append( this.$label
);
8370 this.setSelected( config
.selected
);
8375 OO
.inheritClass( OO
.ui
.MultioptionWidget
, OO
.ui
.Widget
);
8376 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.ItemWidget
);
8377 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.LabelElement
);
8378 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.TitledElement
);
8385 * A change event is emitted when the selected state of the option changes.
8387 * @param {boolean} selected Whether the option is now selected
8393 * Check if the option is selected.
8395 * @return {boolean} Item is selected
8397 OO
.ui
.MultioptionWidget
.prototype.isSelected = function () {
8398 return this.selected
;
8402 * Set the option’s selected state. In general, all modifications to the selection
8403 * should be handled by the SelectWidget’s
8404 * {@link OO.ui.SelectWidget#selectItem selectItem( [item] )} method instead of this method.
8406 * @param {boolean} [state=false] Select option
8408 * @return {OO.ui.Widget} The widget, for chaining
8410 OO
.ui
.MultioptionWidget
.prototype.setSelected = function ( state
) {
8412 if ( this.selected
!== state
) {
8413 this.selected
= state
;
8414 this.emit( 'change', state
);
8415 this.$element
.toggleClass( 'oo-ui-multioptionWidget-selected', state
);
8421 * MultiselectWidget allows selecting multiple options from a list.
8423 * For more information about menus and options, please see the [OOUI documentation
8426 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
8430 * @extends OO.ui.Widget
8431 * @mixins OO.ui.mixin.GroupWidget
8432 * @mixins OO.ui.mixin.TitledElement
8435 * @param {Object} [config] Configuration options
8436 * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
8438 OO
.ui
.MultiselectWidget
= function OoUiMultiselectWidget( config
) {
8439 // Parent constructor
8440 OO
.ui
.MultiselectWidget
.parent
.call( this, config
);
8442 // Configuration initialization
8443 config
= config
|| {};
8445 // Mixin constructors
8446 OO
.ui
.mixin
.GroupWidget
.call( this, config
);
8447 OO
.ui
.mixin
.TitledElement
.call( this, config
);
8453 // This is mostly for compatibility with TagMultiselectWidget... normally, 'change' is emitted
8454 // by GroupElement only when items are added/removed
8455 this.connect( this, {
8456 select
: [ 'emit', 'change' ]
8460 if ( config
.items
) {
8461 this.addItems( config
.items
);
8463 this.$group
.addClass( 'oo-ui-multiselectWidget-group' );
8464 this.$element
.addClass( 'oo-ui-multiselectWidget' )
8465 .append( this.$group
);
8470 OO
.inheritClass( OO
.ui
.MultiselectWidget
, OO
.ui
.Widget
);
8471 OO
.mixinClass( OO
.ui
.MultiselectWidget
, OO
.ui
.mixin
.GroupWidget
);
8472 OO
.mixinClass( OO
.ui
.MultiselectWidget
, OO
.ui
.mixin
.TitledElement
);
8479 * A change event is emitted when the set of items changes, or an item is selected or deselected.
8485 * A select event is emitted when an item is selected or deselected.
8491 * Find options that are selected.
8493 * @return {OO.ui.MultioptionWidget[]} Selected options
8495 OO
.ui
.MultiselectWidget
.prototype.findSelectedItems = function () {
8496 return this.items
.filter( function ( item
) {
8497 return item
.isSelected();
8502 * Find the data of options that are selected.
8504 * @return {Object[]|string[]} Values of selected options
8506 OO
.ui
.MultiselectWidget
.prototype.findSelectedItemsData = function () {
8507 return this.findSelectedItems().map( function ( item
) {
8513 * Select options by reference. Options not mentioned in the `items` array will be deselected.
8515 * @param {OO.ui.MultioptionWidget[]} items Items to select
8517 * @return {OO.ui.Widget} The widget, for chaining
8519 OO
.ui
.MultiselectWidget
.prototype.selectItems = function ( items
) {
8520 this.items
.forEach( function ( item
) {
8521 var selected
= items
.indexOf( item
) !== -1;
8522 item
.setSelected( selected
);
8528 * Select items by their data. Options not mentioned in the `datas` array will be deselected.
8530 * @param {Object[]|string[]} datas Values of items to select
8532 * @return {OO.ui.Widget} The widget, for chaining
8534 OO
.ui
.MultiselectWidget
.prototype.selectItemsByData = function ( datas
) {
8537 items
= datas
.map( function ( data
) {
8538 return widget
.findItemFromData( data
);
8540 this.selectItems( items
);
8545 * CheckboxMultioptionWidget is an option widget that looks like a checkbox.
8546 * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
8547 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8549 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8552 * @extends OO.ui.MultioptionWidget
8555 * @param {Object} [config] Configuration options
8557 OO
.ui
.CheckboxMultioptionWidget
= function OoUiCheckboxMultioptionWidget( config
) {
8558 // Configuration initialization
8559 config
= config
|| {};
8561 // Properties (must be done before parent constructor which calls #setDisabled)
8562 this.checkbox
= new OO
.ui
.CheckboxInputWidget();
8564 // Parent constructor
8565 OO
.ui
.CheckboxMultioptionWidget
.parent
.call( this, config
);
8568 this.checkbox
.on( 'change', this.onCheckboxChange
.bind( this ) );
8569 this.$element
.on( 'keydown', this.onKeyDown
.bind( this ) );
8573 .addClass( 'oo-ui-checkboxMultioptionWidget' )
8574 .prepend( this.checkbox
.$element
);
8579 OO
.inheritClass( OO
.ui
.CheckboxMultioptionWidget
, OO
.ui
.MultioptionWidget
);
8581 /* Static Properties */
8587 OO
.ui
.CheckboxMultioptionWidget
.static.tagName
= 'label';
8592 * Handle checkbox selected state change.
8596 OO
.ui
.CheckboxMultioptionWidget
.prototype.onCheckboxChange = function () {
8597 this.setSelected( this.checkbox
.isSelected() );
8603 OO
.ui
.CheckboxMultioptionWidget
.prototype.setSelected = function ( state
) {
8604 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setSelected
.call( this, state
);
8605 this.checkbox
.setSelected( state
);
8612 OO
.ui
.CheckboxMultioptionWidget
.prototype.setDisabled = function ( disabled
) {
8613 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
8614 this.checkbox
.setDisabled( this.isDisabled() );
8621 OO
.ui
.CheckboxMultioptionWidget
.prototype.focus = function () {
8622 this.checkbox
.focus();
8626 * Handle key down events.
8629 * @param {jQuery.Event} e
8631 OO
.ui
.CheckboxMultioptionWidget
.prototype.onKeyDown = function ( e
) {
8633 element
= this.getElementGroup(),
8636 if ( e
.keyCode
=== OO
.ui
.Keys
.LEFT
|| e
.keyCode
=== OO
.ui
.Keys
.UP
) {
8637 nextItem
= element
.getRelativeFocusableItem( this, -1 );
8638 } else if ( e
.keyCode
=== OO
.ui
.Keys
.RIGHT
|| e
.keyCode
=== OO
.ui
.Keys
.DOWN
) {
8639 nextItem
= element
.getRelativeFocusableItem( this, 1 );
8649 * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
8650 * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
8651 * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
8652 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8654 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8655 * OO.ui.CheckboxMultiselectInputWidget instead.
8658 * // A CheckboxMultiselectWidget with CheckboxMultioptions.
8659 * var option1 = new OO.ui.CheckboxMultioptionWidget( {
8662 * label: 'Selected checkbox'
8664 * option2 = new OO.ui.CheckboxMultioptionWidget( {
8666 * label: 'Unselected checkbox'
8668 * multiselect = new OO.ui.CheckboxMultiselectWidget( {
8669 * items: [ option1, option2 ]
8671 * $( document.body ).append( multiselect.$element );
8673 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8676 * @extends OO.ui.MultiselectWidget
8679 * @param {Object} [config] Configuration options
8681 OO
.ui
.CheckboxMultiselectWidget
= function OoUiCheckboxMultiselectWidget( config
) {
8682 // Parent constructor
8683 OO
.ui
.CheckboxMultiselectWidget
.parent
.call( this, config
);
8686 this.$lastClicked
= null;
8689 this.$group
.on( 'click', this.onClick
.bind( this ) );
8692 this.$element
.addClass( 'oo-ui-checkboxMultiselectWidget' );
8697 OO
.inheritClass( OO
.ui
.CheckboxMultiselectWidget
, OO
.ui
.MultiselectWidget
);
8702 * Get an option by its position relative to the specified item (or to the start of the
8703 * option array, if item is `null`). The direction in which to search through the option array
8704 * is specified with a number: -1 for reverse (the default) or 1 for forward. The method will
8705 * return an option, or `null` if there are no options in the array.
8707 * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or
8708 * `null` to start at the beginning of the array.
8709 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
8710 * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items
8713 OO
.ui
.CheckboxMultiselectWidget
.prototype.getRelativeFocusableItem = function ( item
, direction
) {
8714 var currentIndex
, nextIndex
, i
,
8715 increase
= direction
> 0 ? 1 : -1,
8716 len
= this.items
.length
;
8719 currentIndex
= this.items
.indexOf( item
);
8720 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
8722 // If no item is selected and moving forward, start at the beginning.
8723 // If moving backward, start at the end.
8724 nextIndex
= direction
> 0 ? 0 : len
- 1;
8727 for ( i
= 0; i
< len
; i
++ ) {
8728 item
= this.items
[ nextIndex
];
8729 if ( item
&& !item
.isDisabled() ) {
8732 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
8738 * Handle click events on checkboxes.
8740 * @param {jQuery.Event} e
8742 OO
.ui
.CheckboxMultiselectWidget
.prototype.onClick = function ( e
) {
8743 var $options
, lastClickedIndex
, nowClickedIndex
, i
, direction
, wasSelected
, items
,
8744 $lastClicked
= this.$lastClicked
,
8745 $nowClicked
= $( e
.target
).closest( '.oo-ui-checkboxMultioptionWidget' )
8746 .not( '.oo-ui-widget-disabled' );
8748 // Allow selecting multiple options at once by Shift-clicking them
8749 if ( $lastClicked
&& $nowClicked
.length
&& e
.shiftKey
) {
8750 $options
= this.$group
.find( '.oo-ui-checkboxMultioptionWidget' );
8751 lastClickedIndex
= $options
.index( $lastClicked
);
8752 nowClickedIndex
= $options
.index( $nowClicked
);
8753 // If it's the same item, either the user is being silly, or it's a fake event generated
8754 // by the browser. In either case we don't need custom handling.
8755 if ( nowClickedIndex
!== lastClickedIndex
) {
8757 wasSelected
= items
[ nowClickedIndex
].isSelected();
8758 direction
= nowClickedIndex
> lastClickedIndex
? 1 : -1;
8760 // This depends on the DOM order of the items and the order of the .items array being
8762 for ( i
= lastClickedIndex
; i
!== nowClickedIndex
; i
+= direction
) {
8763 if ( !items
[ i
].isDisabled() ) {
8764 items
[ i
].setSelected( !wasSelected
);
8767 // For the now-clicked element, use immediate timeout to allow the browser to do its own
8768 // handling first, then set our value. The order in which events happen is different for
8769 // clicks on the <input> and on the <label> and there are additional fake clicks fired
8770 // for non-click actions that change the checkboxes.
8772 setTimeout( function () {
8773 if ( !items
[ nowClickedIndex
].isDisabled() ) {
8774 items
[ nowClickedIndex
].setSelected( !wasSelected
);
8780 if ( $nowClicked
.length
) {
8781 this.$lastClicked
= $nowClicked
;
8789 * @return {OO.ui.Widget} The widget, for chaining
8791 OO
.ui
.CheckboxMultiselectWidget
.prototype.focus = function () {
8793 if ( !this.isDisabled() ) {
8794 item
= this.getRelativeFocusableItem( null, 1 );
8805 OO
.ui
.CheckboxMultiselectWidget
.prototype.simulateLabelClick = function () {
8810 * Progress bars visually display the status of an operation, such as a download,
8811 * and can be either determinate or indeterminate:
8813 * - **determinate** process bars show the percent of an operation that is complete.
8815 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
8816 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
8817 * not use percentages.
8819 * The value of the `progress` configuration determines whether the bar is determinate
8823 * // Examples of determinate and indeterminate progress bars.
8824 * var progressBar1 = new OO.ui.ProgressBarWidget( {
8827 * var progressBar2 = new OO.ui.ProgressBarWidget();
8829 * // Create a FieldsetLayout to layout progress bars.
8830 * var fieldset = new OO.ui.FieldsetLayout;
8831 * fieldset.addItems( [
8832 * new OO.ui.FieldLayout( progressBar1, {
8833 * label: 'Determinate',
8836 * new OO.ui.FieldLayout( progressBar2, {
8837 * label: 'Indeterminate',
8841 * $( document.body ).append( fieldset.$element );
8844 * @extends OO.ui.Widget
8847 * @param {Object} [config] Configuration options
8848 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
8849 * To create a determinate progress bar, specify a number that reflects the initial
8851 * By default, the progress bar is indeterminate.
8853 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
8854 // Configuration initialization
8855 config
= config
|| {};
8857 // Parent constructor
8858 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
8861 this.$bar
= $( '<div>' );
8862 this.progress
= null;
8865 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
8866 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
8869 role
: 'progressbar',
8871 'aria-valuemax': 100
8873 .addClass( 'oo-ui-progressBarWidget' )
8874 .append( this.$bar
);
8879 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
8881 /* Static Properties */
8887 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
8892 * Get the percent of the progress that has been completed. Indeterminate progresses will
8895 * @return {number|boolean} Progress percent
8897 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
8898 return this.progress
;
8902 * Set the percent of the process completed or `false` for an indeterminate process.
8904 * @param {number|boolean} progress Progress percent or `false` for indeterminate
8906 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
8907 this.progress
= progress
;
8909 if ( progress
!== false ) {
8910 this.$bar
.css( 'width', this.progress
+ '%' );
8911 this.$element
.attr( 'aria-valuenow', this.progress
);
8913 this.$bar
.css( 'width', '' );
8914 this.$element
.removeAttr( 'aria-valuenow' );
8916 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress
=== false );
8920 * InputWidget is the base class for all input widgets, which
8921 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox
8922 * inputs}, {@link OO.ui.RadioInputWidget radio inputs}, and
8923 * {@link OO.ui.ButtonInputWidget button inputs}.
8924 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
8926 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
8930 * @extends OO.ui.Widget
8931 * @mixins OO.ui.mixin.TabIndexedElement
8932 * @mixins OO.ui.mixin.TitledElement
8933 * @mixins OO.ui.mixin.AccessKeyedElement
8936 * @param {Object} [config] Configuration options
8937 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
8938 * @cfg {string} [value=''] The value of the input.
8939 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
8940 * @cfg {string} [inputId] The value of the input’s HTML `id` attribute.
8941 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the
8942 * value of an input before it is accepted.
8944 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
8945 // Configuration initialization
8946 config
= config
|| {};
8948 // Parent constructor
8949 OO
.ui
.InputWidget
.parent
.call( this, config
);
8952 // See #reusePreInfuseDOM about config.$input
8953 this.$input
= config
.$input
|| this.getInputElement( config
);
8955 this.inputFilter
= config
.inputFilter
;
8957 // Mixin constructors
8958 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {
8959 $tabIndexed
: this.$input
8961 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {
8962 $titled
: this.$input
8964 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {
8965 $accessKeyed
: this.$input
8969 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
8973 .addClass( 'oo-ui-inputWidget-input' )
8974 .attr( 'name', config
.name
)
8975 .prop( 'disabled', this.isDisabled() );
8977 .addClass( 'oo-ui-inputWidget' )
8978 .append( this.$input
);
8979 this.setValue( config
.value
);
8981 this.setDir( config
.dir
);
8983 if ( config
.inputId
!== undefined ) {
8984 this.setInputId( config
.inputId
);
8990 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
8991 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
8992 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
8993 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
8995 /* Static Methods */
9000 OO
.ui
.InputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
9001 config
= OO
.ui
.InputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
9002 // Reusing `$input` lets browsers preserve inputted values across page reloads, see T114134.
9003 config
.$input
= $( node
).find( '.oo-ui-inputWidget-input' );
9010 OO
.ui
.InputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9011 var state
= OO
.ui
.InputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9012 if ( config
.$input
&& config
.$input
.length
) {
9013 state
.value
= config
.$input
.val();
9014 // Might be better in TabIndexedElement, but it's awkward to do there because
9015 // mixins are awkward
9016 state
.focus
= config
.$input
.is( ':focus' );
9026 * A change event is emitted when the value of the input changes.
9028 * @param {string} value
9034 * Get input element.
9036 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
9037 * different circumstances. The element must have a `value` property (like form elements).
9040 * @param {Object} config Configuration options
9041 * @return {jQuery} Input element
9043 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
9044 return $( '<input>' );
9048 * Handle potentially value-changing events.
9051 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
9053 OO
.ui
.InputWidget
.prototype.onEdit = function () {
9055 if ( !this.isDisabled() ) {
9056 // Allow the stack to clear so the value will be updated
9057 setTimeout( function () {
9058 widget
.setValue( widget
.$input
.val() );
9064 * Get the value of the input.
9066 * @return {string} Input value
9068 OO
.ui
.InputWidget
.prototype.getValue = function () {
9069 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
9070 // it, and we won't know unless they're kind enough to trigger a 'change' event.
9071 var value
= this.$input
.val();
9072 if ( this.value
!== value
) {
9073 this.setValue( value
);
9079 * Set the directionality of the input.
9081 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
9083 * @return {OO.ui.Widget} The widget, for chaining
9085 OO
.ui
.InputWidget
.prototype.setDir = function ( dir
) {
9086 this.$input
.prop( 'dir', dir
);
9091 * Set the value of the input.
9093 * @param {string} value New value
9096 * @return {OO.ui.Widget} The widget, for chaining
9098 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
9099 value
= this.cleanUpValue( value
);
9100 // Update the DOM if it has changed. Note that with cleanUpValue, it
9101 // is possible for the DOM value to change without this.value changing.
9102 if ( this.$input
.val() !== value
) {
9103 this.$input
.val( value
);
9105 if ( this.value
!== value
) {
9107 this.emit( 'change', this.value
);
9109 // The first time that the value is set (probably while constructing the widget),
9110 // remember it in defaultValue. This property can be later used to check whether
9111 // the value of the input has been changed since it was created.
9112 if ( this.defaultValue
=== undefined ) {
9113 this.defaultValue
= this.value
;
9114 this.$input
[ 0 ].defaultValue
= this.defaultValue
;
9120 * Clean up incoming value.
9122 * Ensures value is a string, and converts undefined and null to empty string.
9125 * @param {string} value Original value
9126 * @return {string} Cleaned up value
9128 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
9129 if ( value
=== undefined || value
=== null ) {
9131 } else if ( this.inputFilter
) {
9132 return this.inputFilter( String( value
) );
9134 return String( value
);
9141 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
9142 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9143 if ( this.$input
) {
9144 this.$input
.prop( 'disabled', this.isDisabled() );
9150 * Set the 'id' attribute of the `<input>` element.
9152 * @param {string} id
9154 * @return {OO.ui.Widget} The widget, for chaining
9156 OO
.ui
.InputWidget
.prototype.setInputId = function ( id
) {
9157 this.$input
.attr( 'id', id
);
9164 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
9165 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
9166 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
9167 this.setValue( state
.value
);
9169 if ( state
.focus
) {
9175 * Data widget intended for creating `<input type="hidden">` inputs.
9178 * @extends OO.ui.Widget
9181 * @param {Object} [config] Configuration options
9182 * @cfg {string} [value=''] The value of the input.
9183 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
9185 OO
.ui
.HiddenInputWidget
= function OoUiHiddenInputWidget( config
) {
9186 // Configuration initialization
9187 config
= $.extend( { value
: '', name
: '' }, config
);
9189 // Parent constructor
9190 OO
.ui
.HiddenInputWidget
.parent
.call( this, config
);
9193 this.$element
.attr( {
9195 value
: config
.value
,
9198 this.$element
.removeAttr( 'aria-disabled' );
9203 OO
.inheritClass( OO
.ui
.HiddenInputWidget
, OO
.ui
.Widget
);
9205 /* Static Properties */
9211 OO
.ui
.HiddenInputWidget
.static.tagName
= 'input';
9214 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
9215 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
9216 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
9217 * HTML `<button>` (the default) or an HTML `<input>` tags. See the
9218 * [OOUI documentation on MediaWiki] [1] for more information.
9221 * // A ButtonInputWidget rendered as an HTML button, the default.
9222 * var button = new OO.ui.ButtonInputWidget( {
9223 * label: 'Input button',
9227 * $( document.body ).append( button.$element );
9229 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#Button_inputs
9232 * @extends OO.ui.InputWidget
9233 * @mixins OO.ui.mixin.ButtonElement
9234 * @mixins OO.ui.mixin.IconElement
9235 * @mixins OO.ui.mixin.IndicatorElement
9236 * @mixins OO.ui.mixin.LabelElement
9237 * @mixins OO.ui.mixin.FlaggedElement
9240 * @param {Object} [config] Configuration options
9241 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute:
9242 * 'button', 'submit' or 'reset'.
9243 * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
9244 * Widgets configured to be an `<input>` do not support {@link #icon icons} and
9245 * {@link #indicator indicators},
9246 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should
9247 * only be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
9249 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
9250 // Configuration initialization
9251 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
9253 // See InputWidget#reusePreInfuseDOM about config.$input
9254 if ( config
.$input
) {
9255 config
.$input
.empty();
9258 // Properties (must be set before parent constructor, which calls #setValue)
9259 this.useInputTag
= config
.useInputTag
;
9261 // Parent constructor
9262 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
9264 // Mixin constructors
9265 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {
9266 $button
: this.$input
9268 OO
.ui
.mixin
.IconElement
.call( this, config
);
9269 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
9270 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9271 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
9274 if ( !config
.useInputTag
) {
9275 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
9277 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
9282 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
9283 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
9284 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
9285 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
9286 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
9287 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.FlaggedElement
);
9289 /* Static Properties */
9295 OO
.ui
.ButtonInputWidget
.static.tagName
= 'span';
9303 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
9305 type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ? config
.type
: 'button';
9306 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
9312 * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
9314 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
9315 * text, or `null` for no label
9317 * @return {OO.ui.Widget} The widget, for chaining
9319 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
9320 if ( typeof label
=== 'function' ) {
9321 label
= OO
.ui
.resolveMsg( label
);
9324 if ( this.useInputTag
) {
9325 // Discard non-plaintext labels
9326 if ( typeof label
!== 'string' ) {
9330 this.$input
.val( label
);
9333 return OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
9337 * Set the value of the input.
9339 * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
9340 * they do not support {@link #value values}.
9342 * @param {string} value New value
9344 * @return {OO.ui.Widget} The widget, for chaining
9346 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
9347 if ( !this.useInputTag
) {
9348 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
9356 OO
.ui
.ButtonInputWidget
.prototype.getInputId = function () {
9357 // Disable generating `<label>` elements for buttons. One would very rarely need additional
9358 // label for a button, and it's already a big clickable target, and it causes
9359 // unexpected rendering.
9364 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
9365 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
9366 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
9367 * alignment. For more information, please see the [OOUI documentation on MediaWiki][1].
9369 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9372 * // An example of selected, unselected, and disabled checkbox inputs.
9373 * var checkbox1 = new OO.ui.CheckboxInputWidget( {
9377 * checkbox2 = new OO.ui.CheckboxInputWidget( {
9380 * checkbox3 = new OO.ui.CheckboxInputWidget( {
9384 * // Create a fieldset layout with fields for each checkbox.
9385 * fieldset = new OO.ui.FieldsetLayout( {
9386 * label: 'Checkboxes'
9388 * fieldset.addItems( [
9389 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
9390 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
9391 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
9393 * $( document.body ).append( fieldset.$element );
9395 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9398 * @extends OO.ui.InputWidget
9401 * @param {Object} [config] Configuration options
9402 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is
9405 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
9406 // Configuration initialization
9407 config
= config
|| {};
9409 // Parent constructor
9410 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
9413 this.checkIcon
= new OO
.ui
.IconWidget( {
9415 classes
: [ 'oo-ui-checkboxInputWidget-checkIcon' ]
9420 .addClass( 'oo-ui-checkboxInputWidget' )
9421 // Required for pretty styling in WikimediaUI theme
9422 .append( this.checkIcon
.$element
);
9423 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
9428 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
9430 /* Static Properties */
9436 OO
.ui
.CheckboxInputWidget
.static.tagName
= 'span';
9438 /* Static Methods */
9443 OO
.ui
.CheckboxInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9444 var state
= OO
.ui
.CheckboxInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9445 state
.checked
= config
.$input
.prop( 'checked' );
9455 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
9456 return $( '<input>' ).attr( 'type', 'checkbox' );
9462 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
9464 if ( !this.isDisabled() ) {
9465 // Allow the stack to clear so the value will be updated
9466 setTimeout( function () {
9467 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
9473 * Set selection state of this checkbox.
9475 * @param {boolean} state `true` for selected
9477 * @return {OO.ui.Widget} The widget, for chaining
9479 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
9481 if ( this.selected
!== state
) {
9482 this.selected
= state
;
9483 this.$input
.prop( 'checked', this.selected
);
9484 this.emit( 'change', this.selected
);
9486 // The first time that the selection state is set (probably while constructing the widget),
9487 // remember it in defaultSelected. This property can be later used to check whether
9488 // the selection state of the input has been changed since it was created.
9489 if ( this.defaultSelected
=== undefined ) {
9490 this.defaultSelected
= this.selected
;
9491 this.$input
[ 0 ].defaultChecked
= this.defaultSelected
;
9497 * Check if this checkbox is selected.
9499 * @return {boolean} Checkbox is selected
9501 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
9502 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
9503 // it, and we won't know unless they're kind enough to trigger a 'change' event.
9504 var selected
= this.$input
.prop( 'checked' );
9505 if ( this.selected
!== selected
) {
9506 this.setSelected( selected
);
9508 return this.selected
;
9514 OO
.ui
.CheckboxInputWidget
.prototype.simulateLabelClick = function () {
9515 if ( !this.isDisabled() ) {
9516 this.$handle
.trigger( 'click' );
9524 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
9525 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
9526 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
9527 this.setSelected( state
.checked
);
9532 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
9533 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the
9534 * value of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9535 * more information about input widgets.
9537 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
9538 * are no options. If no `value` configuration option is provided, the first option is selected.
9539 * If you need a state representing no value (no option being selected), use a DropdownWidget.
9541 * This and OO.ui.RadioSelectInputWidget support similar configuration options.
9544 * // A DropdownInputWidget with three options.
9545 * var dropdownInput = new OO.ui.DropdownInputWidget( {
9547 * { data: 'a', label: 'First' },
9548 * { data: 'b', label: 'Second', disabled: true },
9549 * { optgroup: 'Group label' },
9550 * { data: 'c', label: 'First sub-item)' }
9553 * $( document.body ).append( dropdownInput.$element );
9555 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9558 * @extends OO.ui.InputWidget
9561 * @param {Object} [config] Configuration options
9562 * @cfg {Object[]} [options=[]] Array of menu options in the format described above.
9563 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
9564 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful
9565 * in cases where the expanded menu is larger than its containing `<div>`. The specified overlay
9566 * layer is usually on top of the containing `<div>` and has a larger area. By default, the menu
9567 * uses relative positioning.
9568 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
9570 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
9571 // Configuration initialization
9572 config
= config
|| {};
9574 // Properties (must be done before parent constructor which calls #setDisabled)
9575 this.dropdownWidget
= new OO
.ui
.DropdownWidget( $.extend(
9577 $overlay
: config
.$overlay
9581 // Set up the options before parent constructor, which uses them to validate config.value.
9582 // Use this instead of setOptions() because this.$input is not set up yet.
9583 this.setOptionsData( config
.options
|| [] );
9585 // Parent constructor
9586 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
9589 this.dropdownWidget
.getMenu().connect( this, {
9590 select
: 'onMenuSelect'
9595 .addClass( 'oo-ui-dropdownInputWidget' )
9596 .append( this.dropdownWidget
.$element
);
9597 this.setTabIndexedElement( this.dropdownWidget
.$tabIndexed
);
9598 this.setTitledElement( this.dropdownWidget
.$handle
);
9603 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
9611 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
9612 return $( '<select>' );
9616 * Handles menu select events.
9619 * @param {OO.ui.MenuOptionWidget|null} item Selected menu item
9621 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
9622 this.setValue( item
? item
.getData() : '' );
9628 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
9630 value
= this.cleanUpValue( value
);
9631 // Only allow setting values that are actually present in the dropdown
9632 selected
= this.dropdownWidget
.getMenu().findItemFromData( value
) ||
9633 this.dropdownWidget
.getMenu().findFirstSelectableItem();
9634 this.dropdownWidget
.getMenu().selectItem( selected
);
9635 value
= selected
? selected
.getData() : '';
9636 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
9637 if ( this.optionsDirty
) {
9638 // We reached this from the constructor or from #setOptions.
9639 // We have to update the <select> element.
9640 this.updateOptionsInterface();
9648 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
9649 this.dropdownWidget
.setDisabled( state
);
9650 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9655 * Set the options available for this input.
9657 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9659 * @return {OO.ui.Widget} The widget, for chaining
9661 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
9662 var value
= this.getValue();
9664 this.setOptionsData( options
);
9666 // Re-set the value to update the visible interface (DropdownWidget and <select>).
9667 // In case the previous value is no longer an available option, select the first valid one.
9668 this.setValue( value
);
9674 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
9676 * This method may be called before the parent constructor, so various properties may not be
9679 * @param {Object[]} options Array of menu options (see #constructor for details).
9682 OO
.ui
.DropdownInputWidget
.prototype.setOptionsData = function ( options
) {
9683 var optionWidgets
, optIndex
, opt
, previousOptgroup
, optionWidget
, optValue
,
9686 this.optionsDirty
= true;
9688 // Go through all the supplied option configs and create either
9689 // MenuSectionOption or MenuOption widgets from each.
9691 for ( optIndex
= 0; optIndex
< options
.length
; optIndex
++ ) {
9692 opt
= options
[ optIndex
];
9694 if ( opt
.optgroup
!== undefined ) {
9695 // Create a <optgroup> menu item.
9696 optionWidget
= widget
.createMenuSectionOptionWidget( opt
.optgroup
);
9697 previousOptgroup
= optionWidget
;
9700 // Create a normal <option> menu item.
9701 optValue
= widget
.cleanUpValue( opt
.data
);
9702 optionWidget
= widget
.createMenuOptionWidget(
9704 opt
.label
!== undefined ? opt
.label
: optValue
9708 // Disable the menu option if it is itself disabled or if its parent optgroup is disabled.
9710 opt
.disabled
!== undefined ||
9711 previousOptgroup
instanceof OO
.ui
.MenuSectionOptionWidget
&&
9712 previousOptgroup
.isDisabled()
9714 optionWidget
.setDisabled( true );
9717 optionWidgets
.push( optionWidget
);
9720 this.dropdownWidget
.getMenu().clearItems().addItems( optionWidgets
);
9724 * Create a menu option widget.
9727 * @param {string} data Item data
9728 * @param {string} label Item label
9729 * @return {OO.ui.MenuOptionWidget} Option widget
9731 OO
.ui
.DropdownInputWidget
.prototype.createMenuOptionWidget = function ( data
, label
) {
9732 return new OO
.ui
.MenuOptionWidget( {
9739 * Create a menu section option widget.
9742 * @param {string} label Section item label
9743 * @return {OO.ui.MenuSectionOptionWidget} Menu section option widget
9745 OO
.ui
.DropdownInputWidget
.prototype.createMenuSectionOptionWidget = function ( label
) {
9746 return new OO
.ui
.MenuSectionOptionWidget( {
9752 * Update the user-visible interface to match the internal list of options and value.
9754 * This method must only be called after the parent constructor.
9758 OO
.ui
.DropdownInputWidget
.prototype.updateOptionsInterface = function () {
9760 $optionsContainer
= this.$input
,
9761 defaultValue
= this.defaultValue
,
9764 this.$input
.empty();
9766 this.dropdownWidget
.getMenu().getItems().forEach( function ( optionWidget
) {
9769 if ( !( optionWidget
instanceof OO
.ui
.MenuSectionOptionWidget
) ) {
9770 $optionNode
= $( '<option>' )
9771 .attr( 'value', optionWidget
.getData() )
9772 .text( optionWidget
.getLabel() );
9774 // Remember original selection state. This property can be later used to check whether
9775 // the selection state of the input has been changed since it was created.
9776 $optionNode
[ 0 ].defaultSelected
= ( optionWidget
.getData() === defaultValue
);
9778 $optionsContainer
.append( $optionNode
);
9780 $optionNode
= $( '<optgroup>' )
9781 .attr( 'label', optionWidget
.getLabel() );
9782 widget
.$input
.append( $optionNode
);
9783 $optionsContainer
= $optionNode
;
9786 // Disable the option or optgroup if required.
9787 if ( optionWidget
.isDisabled() ) {
9788 $optionNode
.prop( 'disabled', true );
9792 this.optionsDirty
= false;
9798 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
9799 this.dropdownWidget
.focus();
9806 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
9807 this.dropdownWidget
.blur();
9812 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
9813 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
9814 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
9815 * please see the [OOUI documentation on MediaWiki][1].
9817 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9820 * // An example of selected, unselected, and disabled radio inputs
9821 * var radio1 = new OO.ui.RadioInputWidget( {
9825 * var radio2 = new OO.ui.RadioInputWidget( {
9828 * var radio3 = new OO.ui.RadioInputWidget( {
9832 * // Create a fieldset layout with fields for each radio button.
9833 * var fieldset = new OO.ui.FieldsetLayout( {
9834 * label: 'Radio inputs'
9836 * fieldset.addItems( [
9837 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
9838 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
9839 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
9841 * $( document.body ).append( fieldset.$element );
9843 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9846 * @extends OO.ui.InputWidget
9849 * @param {Object} [config] Configuration options
9850 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button
9853 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
9854 // Configuration initialization
9855 config
= config
|| {};
9857 // Parent constructor
9858 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
9862 .addClass( 'oo-ui-radioInputWidget' )
9863 // Required for pretty styling in WikimediaUI theme
9864 .append( $( '<span>' ) );
9865 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
9870 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
9872 /* Static Properties */
9878 OO
.ui
.RadioInputWidget
.static.tagName
= 'span';
9880 /* Static Methods */
9885 OO
.ui
.RadioInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9886 var state
= OO
.ui
.RadioInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9887 state
.checked
= config
.$input
.prop( 'checked' );
9897 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
9898 return $( '<input>' ).attr( 'type', 'radio' );
9904 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
9905 // RadioInputWidget doesn't track its state.
9909 * Set selection state of this radio button.
9911 * @param {boolean} state `true` for selected
9913 * @return {OO.ui.Widget} The widget, for chaining
9915 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
9916 // RadioInputWidget doesn't track its state.
9917 this.$input
.prop( 'checked', state
);
9918 // The first time that the selection state is set (probably while constructing the widget),
9919 // remember it in defaultSelected. This property can be later used to check whether
9920 // the selection state of the input has been changed since it was created.
9921 if ( this.defaultSelected
=== undefined ) {
9922 this.defaultSelected
= state
;
9923 this.$input
[ 0 ].defaultChecked
= this.defaultSelected
;
9929 * Check if this radio button is selected.
9931 * @return {boolean} Radio is selected
9933 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
9934 return this.$input
.prop( 'checked' );
9940 OO
.ui
.RadioInputWidget
.prototype.simulateLabelClick = function () {
9941 if ( !this.isDisabled() ) {
9942 this.$input
.trigger( 'click' );
9950 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
9951 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
9952 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
9953 this.setSelected( state
.checked
);
9958 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be
9959 * used within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with
9960 * the value of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9961 * more information about input widgets.
9963 * This and OO.ui.DropdownInputWidget support similar configuration options.
9966 * // A RadioSelectInputWidget with three options
9967 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
9969 * { data: 'a', label: 'First' },
9970 * { data: 'b', label: 'Second'},
9971 * { data: 'c', label: 'Third' }
9974 * $( document.body ).append( radioSelectInput.$element );
9976 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9979 * @extends OO.ui.InputWidget
9982 * @param {Object} [config] Configuration options
9983 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9985 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
9986 // Configuration initialization
9987 config
= config
|| {};
9989 // Properties (must be done before parent constructor which calls #setDisabled)
9990 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
9991 // Set up the options before parent constructor, which uses them to validate config.value.
9992 // Use this instead of setOptions() because this.$input is not set up yet
9993 this.setOptionsData( config
.options
|| [] );
9995 // Parent constructor
9996 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
9999 this.radioSelectWidget
.connect( this, {
10000 select
: 'onMenuSelect'
10005 .addClass( 'oo-ui-radioSelectInputWidget' )
10006 .append( this.radioSelectWidget
.$element
);
10007 this.setTabIndexedElement( this.radioSelectWidget
.$tabIndexed
);
10012 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
10014 /* Static Methods */
10019 OO
.ui
.RadioSelectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
10020 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
10021 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
10028 OO
.ui
.RadioSelectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
10029 config
= OO
.ui
.RadioSelectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
10030 // Cannot reuse the `<input type=radio>` set
10031 delete config
.$input
;
10041 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
10042 // Use this instead of <input type="hidden">, because hidden inputs do not have separate
10043 // 'value' and 'defaultValue' properties, and InputWidget wants to handle 'defaultValue'.
10044 return $( '<input>' ).addClass( 'oo-ui-element-hidden' );
10048 * Handles menu select events.
10051 * @param {OO.ui.RadioOptionWidget} item Selected menu item
10053 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
10054 this.setValue( item
.getData() );
10060 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
10062 value
= this.cleanUpValue( value
);
10063 // Only allow setting values that are actually present in the dropdown
10064 selected
= this.radioSelectWidget
.findItemFromData( value
) ||
10065 this.radioSelectWidget
.findFirstSelectableItem();
10066 this.radioSelectWidget
.selectItem( selected
);
10067 value
= selected
? selected
.getData() : '';
10068 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
10075 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
10076 this.radioSelectWidget
.setDisabled( state
);
10077 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
10082 * Set the options available for this input.
10084 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10086 * @return {OO.ui.Widget} The widget, for chaining
10088 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
10089 var value
= this.getValue();
10091 this.setOptionsData( options
);
10093 // Re-set the value to update the visible interface (RadioSelectWidget).
10094 // In case the previous value is no longer an available option, select the first valid one.
10095 this.setValue( value
);
10101 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
10103 * This method may be called before the parent constructor, so various properties may not be
10106 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10109 OO
.ui
.RadioSelectInputWidget
.prototype.setOptionsData = function ( options
) {
10112 this.radioSelectWidget
10114 .addItems( options
.map( function ( opt
) {
10115 var optValue
= widget
.cleanUpValue( opt
.data
);
10116 return new OO
.ui
.RadioOptionWidget( {
10118 label
: opt
.label
!== undefined ? opt
.label
: optValue
10126 OO
.ui
.RadioSelectInputWidget
.prototype.focus = function () {
10127 this.radioSelectWidget
.focus();
10134 OO
.ui
.RadioSelectInputWidget
.prototype.blur = function () {
10135 this.radioSelectWidget
.blur();
10140 * CheckboxMultiselectInputWidget is a
10141 * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
10142 * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
10143 * HTML `<input type=checkbox>` tags. Please see the [OOUI documentation on MediaWiki][1] for
10144 * more information about input widgets.
10147 * // A CheckboxMultiselectInputWidget with three options.
10148 * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
10150 * { data: 'a', label: 'First' },
10151 * { data: 'b', label: 'Second' },
10152 * { data: 'c', label: 'Third' }
10155 * $( document.body ).append( multiselectInput.$element );
10157 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
10160 * @extends OO.ui.InputWidget
10163 * @param {Object} [config] Configuration options
10164 * @cfg {Object[]} [options=[]] Array of menu options in the format
10165 * `{ data: …, label: …, disabled: … }`
10167 OO
.ui
.CheckboxMultiselectInputWidget
= function OoUiCheckboxMultiselectInputWidget( config
) {
10168 // Configuration initialization
10169 config
= config
|| {};
10171 // Properties (must be done before parent constructor which calls #setDisabled)
10172 this.checkboxMultiselectWidget
= new OO
.ui
.CheckboxMultiselectWidget();
10173 // Must be set before the #setOptionsData call below
10174 this.inputName
= config
.name
;
10175 // Set up the options before parent constructor, which uses them to validate config.value.
10176 // Use this instead of setOptions() because this.$input is not set up yet
10177 this.setOptionsData( config
.options
|| [] );
10179 // Parent constructor
10180 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.call( this, config
);
10183 this.checkboxMultiselectWidget
.connect( this, {
10184 select
: 'onCheckboxesSelect'
10189 .addClass( 'oo-ui-checkboxMultiselectInputWidget' )
10190 .append( this.checkboxMultiselectWidget
.$element
);
10191 // We don't use this.$input, but rather the CheckboxInputWidgets inside each option
10192 this.$input
.detach();
10197 OO
.inheritClass( OO
.ui
.CheckboxMultiselectInputWidget
, OO
.ui
.InputWidget
);
10199 /* Static Methods */
10204 OO
.ui
.CheckboxMultiselectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
10205 var state
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.gatherPreInfuseState(
10208 state
.value
= $( node
).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
10209 .toArray().map( function ( el
) { return el
.value
; } );
10216 OO
.ui
.CheckboxMultiselectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
10217 config
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
10218 // Cannot reuse the `<input type=checkbox>` set
10219 delete config
.$input
;
10229 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getInputElement = function () {
10231 return $( '<unused>' );
10235 * Handles CheckboxMultiselectWidget select events.
10239 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.onCheckboxesSelect = function () {
10240 this.setValue( this.checkboxMultiselectWidget
.findSelectedItemsData() );
10246 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getValue = function () {
10247 var value
= this.$element
.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
10248 .toArray().map( function ( el
) { return el
.value
; } );
10249 if ( this.value
!== value
) {
10250 this.setValue( value
);
10258 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setValue = function ( value
) {
10259 value
= this.cleanUpValue( value
);
10260 this.checkboxMultiselectWidget
.selectItemsByData( value
);
10261 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setValue
.call( this, value
);
10262 if ( this.optionsDirty
) {
10263 // We reached this from the constructor or from #setOptions.
10264 // We have to update the <select> element.
10265 this.updateOptionsInterface();
10271 * Clean up incoming value.
10273 * @param {string[]} value Original value
10274 * @return {string[]} Cleaned up value
10276 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.cleanUpValue = function ( value
) {
10277 var i
, singleValue
,
10279 if ( !Array
.isArray( value
) ) {
10282 for ( i
= 0; i
< value
.length
; i
++ ) {
10283 singleValue
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
10284 .call( this, value
[ i
] );
10285 // Remove options that we don't have here
10286 if ( !this.checkboxMultiselectWidget
.findItemFromData( singleValue
) ) {
10289 cleanValue
.push( singleValue
);
10297 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setDisabled = function ( state
) {
10298 this.checkboxMultiselectWidget
.setDisabled( state
);
10299 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
10304 * Set the options available for this input.
10306 * @param {Object[]} options Array of menu options in the format
10307 * `{ data: …, label: …, disabled: … }`
10309 * @return {OO.ui.Widget} The widget, for chaining
10311 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setOptions = function ( options
) {
10312 var value
= this.getValue();
10314 this.setOptionsData( options
);
10316 // Re-set the value to update the visible interface (CheckboxMultiselectWidget).
10317 // This will also get rid of any stale options that we just removed.
10318 this.setValue( value
);
10324 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
10326 * This method may be called before the parent constructor, so various properties may not be
10329 * @param {Object[]} options Array of menu options in the format
10330 * `{ data: …, label: … }`
10333 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setOptionsData = function ( options
) {
10336 this.optionsDirty
= true;
10338 this.checkboxMultiselectWidget
10340 .addItems( options
.map( function ( opt
) {
10341 var optValue
, item
, optDisabled
;
10342 optValue
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
10343 .call( widget
, opt
.data
);
10344 optDisabled
= opt
.disabled
!== undefined ? opt
.disabled
: false;
10345 item
= new OO
.ui
.CheckboxMultioptionWidget( {
10347 label
: opt
.label
!== undefined ? opt
.label
: optValue
,
10348 disabled
: optDisabled
10350 // Set the 'name' and 'value' for form submission
10351 item
.checkbox
.$input
.attr( 'name', widget
.inputName
);
10352 item
.checkbox
.setValue( optValue
);
10358 * Update the user-visible interface to match the internal list of options and value.
10360 * This method must only be called after the parent constructor.
10364 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.updateOptionsInterface = function () {
10365 var defaultValue
= this.defaultValue
;
10367 this.checkboxMultiselectWidget
.getItems().forEach( function ( item
) {
10368 // Remember original selection state. This property can be later used to check whether
10369 // the selection state of the input has been changed since it was created.
10370 var isDefault
= defaultValue
.indexOf( item
.getData() ) !== -1;
10371 item
.checkbox
.defaultSelected
= isDefault
;
10372 item
.checkbox
.$input
[ 0 ].defaultChecked
= isDefault
;
10375 this.optionsDirty
= false;
10381 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.focus = function () {
10382 this.checkboxMultiselectWidget
.focus();
10387 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
10388 * size of the field as well as its presentation. In addition, these widgets can be configured
10389 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an
10390 * optional validation-pattern (used to determine if an input value is valid or not) and an input
10391 * filter, which modifies incoming values rather than validating them.
10392 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
10394 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
10397 * // A TextInputWidget.
10398 * var textInput = new OO.ui.TextInputWidget( {
10399 * value: 'Text input'
10401 * $( document.body ).append( textInput.$element );
10403 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
10406 * @extends OO.ui.InputWidget
10407 * @mixins OO.ui.mixin.IconElement
10408 * @mixins OO.ui.mixin.IndicatorElement
10409 * @mixins OO.ui.mixin.PendingElement
10410 * @mixins OO.ui.mixin.LabelElement
10411 * @mixins OO.ui.mixin.FlaggedElement
10414 * @param {Object} [config] Configuration options
10415 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password'
10416 * 'email', 'url' or 'number'.
10417 * @cfg {string} [placeholder] Placeholder text
10418 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
10419 * instruct the browser to focus this widget.
10420 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
10421 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
10423 * For unfortunate historical reasons, this counts the number of UTF-16 code units rather than
10424 * Unicode codepoints, which means that codepoints outside the Basic Multilingual Plane (e.g.
10425 * many emojis) count as 2 characters each.
10426 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
10427 * the value or placeholder text: `'before'` or `'after'`
10428 * @cfg {boolean} [required=false] Mark the field as required with `true`. Implies `indicator:
10429 * 'required'`. Note that `false` & setting `indicator: 'required' will result in no indicator
10431 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
10432 * @cfg {boolean} [spellcheck] Should the browser support spellcheck for this field (`undefined`
10433 * means leaving it up to the browser).
10434 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
10435 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
10436 * (the value must contain only numbers); when RegExp, a regular expression that must match the
10437 * value for it to be considered valid; when Function, a function receiving the value as parameter
10438 * that must return true, or promise resolving to true, for it to be considered valid.
10440 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
10441 // Configuration initialization
10442 config
= $.extend( {
10444 labelPosition
: 'after'
10447 // Parent constructor
10448 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
10450 // Mixin constructors
10451 OO
.ui
.mixin
.IconElement
.call( this, config
);
10452 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
10453 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( { $pending
: this.$input
}, config
) );
10454 OO
.ui
.mixin
.LabelElement
.call( this, config
);
10455 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
10458 this.type
= this.getSaneType( config
);
10459 this.readOnly
= false;
10460 this.required
= false;
10461 this.validate
= null;
10462 this.scrollWidth
= null;
10464 this.setValidation( config
.validate
);
10465 this.setLabelPosition( config
.labelPosition
);
10469 keypress
: this.onKeyPress
.bind( this ),
10470 blur
: this.onBlur
.bind( this ),
10471 focus
: this.onFocus
.bind( this )
10473 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
10474 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
10475 this.on( 'labelChange', this.updatePosition
.bind( this ) );
10476 this.on( 'change', OO
.ui
.debounce( this.onDebouncedChange
.bind( this ), 250 ) );
10480 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
10481 .append( this.$icon
, this.$indicator
);
10482 this.setReadOnly( !!config
.readOnly
);
10483 this.setRequired( !!config
.required
);
10484 if ( config
.placeholder
!== undefined ) {
10485 this.$input
.attr( 'placeholder', config
.placeholder
);
10487 if ( config
.maxLength
!== undefined ) {
10488 this.$input
.attr( 'maxlength', config
.maxLength
);
10490 if ( config
.autofocus
) {
10491 this.$input
.attr( 'autofocus', 'autofocus' );
10493 if ( config
.autocomplete
=== false ) {
10494 this.$input
.attr( 'autocomplete', 'off' );
10495 // Turning off autocompletion also disables "form caching" when the user navigates to a
10496 // different page and then clicks "Back". Re-enable it when leaving.
10497 // Borrowed from jQuery UI.
10499 beforeunload: function () {
10500 this.$input
.removeAttr( 'autocomplete' );
10502 pageshow: function () {
10503 // Browsers don't seem to actually fire this event on "Back", they instead just
10504 // reload the whole page... it shouldn't hurt, though.
10505 this.$input
.attr( 'autocomplete', 'off' );
10509 if ( config
.spellcheck
!== undefined ) {
10510 this.$input
.attr( 'spellcheck', config
.spellcheck
? 'true' : 'false' );
10512 if ( this.label
) {
10513 this.isWaitingToBeAttached
= true;
10514 this.installParentChangeDetector();
10520 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
10521 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
10522 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
10523 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
10524 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
10525 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.FlaggedElement
);
10527 /* Static Properties */
10529 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
10537 * An `enter` event is emitted when the user presses Enter key inside the text box.
10545 * Handle icon mouse down events.
10548 * @param {jQuery.Event} e Mouse down event
10549 * @return {undefined/boolean} False to prevent default if event is handled
10551 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
10552 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
10559 * Handle indicator mouse down events.
10562 * @param {jQuery.Event} e Mouse down event
10563 * @return {undefined/boolean} False to prevent default if event is handled
10565 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
10566 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
10573 * Handle key press events.
10576 * @param {jQuery.Event} e Key press event
10577 * @fires enter If Enter key is pressed
10579 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
10580 if ( e
.which
=== OO
.ui
.Keys
.ENTER
) {
10581 this.emit( 'enter', e
);
10586 * Handle blur events.
10589 * @param {jQuery.Event} e Blur event
10591 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
10592 this.setValidityFlag();
10596 * Handle focus events.
10599 * @param {jQuery.Event} e Focus event
10601 OO
.ui
.TextInputWidget
.prototype.onFocus = function () {
10602 if ( this.isWaitingToBeAttached
) {
10603 // If we've received focus, then we must be attached to the document, and if
10604 // isWaitingToBeAttached is still true, that means the handler never fired. Fire it now.
10605 this.onElementAttach();
10607 this.setValidityFlag( true );
10611 * Handle element attach events.
10614 * @param {jQuery.Event} e Element attach event
10616 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
10617 this.isWaitingToBeAttached
= false;
10618 // Any previously calculated size is now probably invalid if we reattached elsewhere
10619 this.valCache
= null;
10620 this.positionLabel();
10624 * Handle debounced change events.
10626 * @param {string} value
10629 OO
.ui
.TextInputWidget
.prototype.onDebouncedChange = function () {
10630 this.setValidityFlag();
10634 * Check if the input is {@link #readOnly read-only}.
10636 * @return {boolean}
10638 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
10639 return this.readOnly
;
10643 * Set the {@link #readOnly read-only} state of the input.
10645 * @param {boolean} state Make input read-only
10647 * @return {OO.ui.Widget} The widget, for chaining
10649 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
10650 this.readOnly
= !!state
;
10651 this.$input
.prop( 'readOnly', this.readOnly
);
10656 * Check if the input is {@link #required required}.
10658 * @return {boolean}
10660 OO
.ui
.TextInputWidget
.prototype.isRequired = function () {
10661 return this.required
;
10665 * Set the {@link #required required} state of the input.
10667 * @param {boolean} state Make input required
10669 * @return {OO.ui.Widget} The widget, for chaining
10671 OO
.ui
.TextInputWidget
.prototype.setRequired = function ( state
) {
10672 this.required
= !!state
;
10673 if ( this.required
) {
10675 .prop( 'required', true )
10676 .attr( 'aria-required', 'true' );
10677 if ( this.getIndicator() === null ) {
10678 this.setIndicator( 'required' );
10682 .prop( 'required', false )
10683 .removeAttr( 'aria-required' );
10684 if ( this.getIndicator() === 'required' ) {
10685 this.setIndicator( null );
10692 * Support function for making #onElementAttach work across browsers.
10694 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
10695 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
10697 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
10698 * first time that the element gets attached to the documented.
10700 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
10701 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
10702 MutationObserver
= window
.MutationObserver
||
10703 window
.WebKitMutationObserver
||
10704 window
.MozMutationObserver
,
10707 if ( MutationObserver
) {
10708 // The new way. If only it wasn't so ugly.
10710 if ( this.isElementAttached() ) {
10711 // Widget is attached already, do nothing. This breaks the functionality of this
10712 // function when the widget is detached and reattached. Alas, doing this correctly with
10713 // MutationObserver would require observation of the whole document, which would hurt
10714 // performance of other, more important code.
10718 // Find topmost node in the tree
10719 topmostNode
= this.$element
[ 0 ];
10720 while ( topmostNode
.parentNode
) {
10721 topmostNode
= topmostNode
.parentNode
;
10724 // We have no way to detect the $element being attached somewhere without observing the
10725 // entire DOM with subtree modifications, which would hurt performance. So we cheat: we hook
10726 // to the parent node of $element, and instead detect when $element is removed from it (and
10727 // thus probably attached somewhere else). If there is no parent, we create a "fake" one. If
10728 // it doesn't get attached, we end up back here and create the parent.
10729 mutationObserver
= new MutationObserver( function ( mutations
) {
10730 var i
, j
, removedNodes
;
10731 for ( i
= 0; i
< mutations
.length
; i
++ ) {
10732 removedNodes
= mutations
[ i
].removedNodes
;
10733 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
10734 if ( removedNodes
[ j
] === topmostNode
) {
10735 setTimeout( onRemove
, 0 );
10742 onRemove = function () {
10743 // If the node was attached somewhere else, report it
10744 if ( widget
.isElementAttached() ) {
10745 widget
.onElementAttach();
10747 mutationObserver
.disconnect();
10748 widget
.installParentChangeDetector();
10751 // Create a fake parent and observe it
10752 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
10753 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
10755 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
10756 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
10757 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
10765 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
10766 if ( this.getSaneType( config
) === 'number' ) {
10767 return $( '<input>' )
10768 .attr( 'step', 'any' )
10769 .attr( 'type', 'number' );
10771 return $( '<input>' ).attr( 'type', this.getSaneType( config
) );
10776 * Get sanitized value for 'type' for given config.
10778 * @param {Object} config Configuration options
10779 * @return {string|null}
10782 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
10783 var allowedTypes
= [
10790 return allowedTypes
.indexOf( config
.type
) !== -1 ? config
.type
: 'text';
10794 * Focus the input and select a specified range within the text.
10796 * @param {number} from Select from offset
10797 * @param {number} [to] Select to offset, defaults to from
10799 * @return {OO.ui.Widget} The widget, for chaining
10801 OO
.ui
.TextInputWidget
.prototype.selectRange = function ( from, to
) {
10802 var isBackwards
, start
, end
,
10803 input
= this.$input
[ 0 ];
10807 isBackwards
= to
< from;
10808 start
= isBackwards
? to
: from;
10809 end
= isBackwards
? from : to
;
10814 input
.setSelectionRange( start
, end
, isBackwards
? 'backward' : 'forward' );
10816 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
10817 // Rather than expensively check if the input is attached every time, just check
10818 // if it was the cause of an error being thrown. If not, rethrow the error.
10819 if ( this.getElementDocument().body
.contains( input
) ) {
10827 * Get an object describing the current selection range in a directional manner
10829 * @return {Object} Object containing 'from' and 'to' offsets
10831 OO
.ui
.TextInputWidget
.prototype.getRange = function () {
10832 var input
= this.$input
[ 0 ],
10833 start
= input
.selectionStart
,
10834 end
= input
.selectionEnd
,
10835 isBackwards
= input
.selectionDirection
=== 'backward';
10838 from: isBackwards
? end
: start
,
10839 to
: isBackwards
? start
: end
10844 * Get the length of the text input value.
10846 * This could differ from the length of #getValue if the
10847 * value gets filtered
10849 * @return {number} Input length
10851 OO
.ui
.TextInputWidget
.prototype.getInputLength = function () {
10852 return this.$input
[ 0 ].value
.length
;
10856 * Focus the input and select the entire text.
10859 * @return {OO.ui.Widget} The widget, for chaining
10861 OO
.ui
.TextInputWidget
.prototype.select = function () {
10862 return this.selectRange( 0, this.getInputLength() );
10866 * Focus the input and move the cursor to the start.
10869 * @return {OO.ui.Widget} The widget, for chaining
10871 OO
.ui
.TextInputWidget
.prototype.moveCursorToStart = function () {
10872 return this.selectRange( 0 );
10876 * Focus the input and move the cursor to the end.
10879 * @return {OO.ui.Widget} The widget, for chaining
10881 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
10882 return this.selectRange( this.getInputLength() );
10886 * Insert new content into the input.
10888 * @param {string} content Content to be inserted
10890 * @return {OO.ui.Widget} The widget, for chaining
10892 OO
.ui
.TextInputWidget
.prototype.insertContent = function ( content
) {
10894 range
= this.getRange(),
10895 value
= this.getValue();
10897 start
= Math
.min( range
.from, range
.to
);
10898 end
= Math
.max( range
.from, range
.to
);
10900 this.setValue( value
.slice( 0, start
) + content
+ value
.slice( end
) );
10901 this.selectRange( start
+ content
.length
);
10906 * Insert new content either side of a selection.
10908 * @param {string} pre Content to be inserted before the selection
10909 * @param {string} post Content to be inserted after the selection
10911 * @return {OO.ui.Widget} The widget, for chaining
10913 OO
.ui
.TextInputWidget
.prototype.encapsulateContent = function ( pre
, post
) {
10915 range
= this.getRange(),
10916 offset
= pre
.length
;
10918 start
= Math
.min( range
.from, range
.to
);
10919 end
= Math
.max( range
.from, range
.to
);
10921 this.selectRange( start
).insertContent( pre
);
10922 this.selectRange( offset
+ end
).insertContent( post
);
10924 this.selectRange( offset
+ start
, offset
+ end
);
10929 * Set the validation pattern.
10931 * The validation pattern is either a regular expression, a function, or the symbolic name of a
10932 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
10933 * value must contain only numbers).
10935 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
10936 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
10938 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
10939 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
10940 this.validate
= validate
;
10942 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
10947 * Sets the 'invalid' flag appropriately.
10949 * @param {boolean} [isValid] Optionally override validation result
10951 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
10953 setFlag = function ( valid
) {
10955 widget
.$input
.attr( 'aria-invalid', 'true' );
10957 widget
.$input
.removeAttr( 'aria-invalid' );
10959 widget
.setFlags( { invalid
: !valid
} );
10962 if ( isValid
!== undefined ) {
10963 setFlag( isValid
);
10965 this.getValidity().then( function () {
10974 * Get the validity of current value.
10976 * This method returns a promise that resolves if the value is valid and rejects if
10977 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
10979 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
10981 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
10984 function rejectOrResolve( valid
) {
10986 return $.Deferred().resolve().promise();
10988 return $.Deferred().reject().promise();
10992 // Check browser validity and reject if it is invalid
10994 this.$input
[ 0 ].checkValidity
!== undefined &&
10995 this.$input
[ 0 ].checkValidity() === false
10997 return rejectOrResolve( false );
11000 // Run our checks if the browser thinks the field is valid
11001 if ( this.validate
instanceof Function
) {
11002 result
= this.validate( this.getValue() );
11003 if ( result
&& typeof result
.promise
=== 'function' ) {
11004 return result
.promise().then( function ( valid
) {
11005 return rejectOrResolve( valid
);
11008 return rejectOrResolve( result
);
11011 return rejectOrResolve( this.getValue().match( this.validate
) );
11016 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
11018 * @param {string} labelPosition Label position, 'before' or 'after'
11020 * @return {OO.ui.Widget} The widget, for chaining
11022 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
11023 this.labelPosition
= labelPosition
;
11024 if ( this.label
) {
11025 // If there is no label and we only change the position, #updatePosition is a no-op,
11026 // but it takes really a lot of work to do nothing.
11027 this.updatePosition();
11033 * Update the position of the inline label.
11035 * This method is called by #setLabelPosition, and can also be called on its own if
11036 * something causes the label to be mispositioned.
11039 * @return {OO.ui.Widget} The widget, for chaining
11041 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
11042 var after
= this.labelPosition
=== 'after';
11045 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
11046 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
11048 this.valCache
= null;
11049 this.scrollWidth
= null;
11050 this.positionLabel();
11056 * Position the label by setting the correct padding on the input.
11060 * @return {OO.ui.Widget} The widget, for chaining
11062 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
11063 var after
, rtl
, property
, newCss
;
11065 if ( this.isWaitingToBeAttached
) {
11066 // #onElementAttach will be called soon, which calls this method
11071 'padding-right': '',
11075 if ( this.label
) {
11076 this.$element
.append( this.$label
);
11078 this.$label
.detach();
11079 // Clear old values if present
11080 this.$input
.css( newCss
);
11084 after
= this.labelPosition
=== 'after';
11085 rtl
= this.$element
.css( 'direction' ) === 'rtl';
11086 property
= after
=== rtl
? 'padding-left' : 'padding-right';
11088 newCss
[ property
] = this.$label
.outerWidth( true ) + ( after
? this.scrollWidth
: 0 );
11089 // We have to clear the padding on the other side, in case the element direction changed
11090 this.$input
.css( newCss
);
11096 * SearchInputWidgets are TextInputWidgets with `type="search"` assigned and feature a
11097 * {@link OO.ui.mixin.IconElement search icon} by default.
11098 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
11100 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#SearchInputWidget
11103 * @extends OO.ui.TextInputWidget
11106 * @param {Object} [config] Configuration options
11108 OO
.ui
.SearchInputWidget
= function OoUiSearchInputWidget( config
) {
11109 config
= $.extend( {
11113 // Parent constructor
11114 OO
.ui
.SearchInputWidget
.parent
.call( this, config
);
11117 this.connect( this, {
11122 this.updateSearchIndicator();
11123 this.connect( this, {
11124 disable
: 'onDisable'
11130 OO
.inheritClass( OO
.ui
.SearchInputWidget
, OO
.ui
.TextInputWidget
);
11138 OO
.ui
.SearchInputWidget
.prototype.getSaneType = function () {
11145 OO
.ui
.SearchInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
11146 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
11147 // Clear the text field
11148 this.setValue( '' );
11155 * Update the 'clear' indicator displayed on type: 'search' text
11156 * fields, hiding it when the field is already empty or when it's not
11159 OO
.ui
.SearchInputWidget
.prototype.updateSearchIndicator = function () {
11160 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
11161 this.setIndicator( null );
11163 this.setIndicator( 'clear' );
11168 * Handle change events.
11172 OO
.ui
.SearchInputWidget
.prototype.onChange = function () {
11173 this.updateSearchIndicator();
11177 * Handle disable events.
11179 * @param {boolean} disabled Element is disabled
11182 OO
.ui
.SearchInputWidget
.prototype.onDisable = function () {
11183 this.updateSearchIndicator();
11189 OO
.ui
.SearchInputWidget
.prototype.setReadOnly = function ( state
) {
11190 OO
.ui
.SearchInputWidget
.parent
.prototype.setReadOnly
.call( this, state
);
11191 this.updateSearchIndicator();
11196 * MultilineTextInputWidgets, like HTML textareas, are featuring customization options to
11197 * configure number of rows visible. In addition, these widgets can be autosized to fit user
11198 * inputs and can show {@link OO.ui.mixin.IconElement icons} and
11199 * {@link OO.ui.mixin.IndicatorElement indicators}.
11200 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
11202 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
11205 * // A MultilineTextInputWidget.
11206 * var multilineTextInput = new OO.ui.MultilineTextInputWidget( {
11207 * value: 'Text input on multiple lines'
11209 * $( 'body' ).append( multilineTextInput.$element );
11211 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#MultilineTextInputWidget
11214 * @extends OO.ui.TextInputWidget
11217 * @param {Object} [config] Configuration options
11218 * @cfg {number} [rows] Number of visible lines in textarea. If used with `autosize`,
11219 * specifies minimum number of rows to display.
11220 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
11221 * Use the #maxRows config to specify a maximum number of displayed rows.
11222 * @cfg {number} [maxRows] Maximum number of rows to display when #autosize is set to true.
11223 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
11225 OO
.ui
.MultilineTextInputWidget
= function OoUiMultilineTextInputWidget( config
) {
11226 config
= $.extend( {
11229 // Parent constructor
11230 OO
.ui
.MultilineTextInputWidget
.parent
.call( this, config
);
11233 this.autosize
= !!config
.autosize
;
11234 this.styleHeight
= null;
11235 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
11236 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
11238 // Clone for resizing
11239 if ( this.autosize
) {
11240 this.$clone
= this.$input
11242 .removeAttr( 'id' )
11243 .removeAttr( 'name' )
11244 .insertAfter( this.$input
)
11245 .attr( 'aria-hidden', 'true' )
11246 .addClass( 'oo-ui-element-hidden' );
11250 this.connect( this, {
11255 if ( config
.rows
) {
11256 this.$input
.attr( 'rows', config
.rows
);
11258 if ( this.autosize
) {
11259 this.$input
.addClass( 'oo-ui-textInputWidget-autosized' );
11260 this.isWaitingToBeAttached
= true;
11261 this.installParentChangeDetector();
11267 OO
.inheritClass( OO
.ui
.MultilineTextInputWidget
, OO
.ui
.TextInputWidget
);
11269 /* Static Methods */
11274 OO
.ui
.MultilineTextInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
11275 var state
= OO
.ui
.MultilineTextInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
11276 state
.scrollTop
= config
.$input
.scrollTop();
11285 OO
.ui
.MultilineTextInputWidget
.prototype.onElementAttach = function () {
11286 OO
.ui
.MultilineTextInputWidget
.parent
.prototype.onElementAttach
.call( this );
11291 * Handle change events.
11295 OO
.ui
.MultilineTextInputWidget
.prototype.onChange = function () {
11302 OO
.ui
.MultilineTextInputWidget
.prototype.updatePosition = function () {
11303 OO
.ui
.MultilineTextInputWidget
.parent
.prototype.updatePosition
.call( this );
11310 * Modify to emit 'enter' on Ctrl/Meta+Enter, instead of plain Enter
11312 OO
.ui
.MultilineTextInputWidget
.prototype.onKeyPress = function ( e
) {
11314 ( e
.which
=== OO
.ui
.Keys
.ENTER
&& ( e
.ctrlKey
|| e
.metaKey
) ) ||
11315 // Some platforms emit keycode 10 for Control+Enter keypress in a textarea
11318 this.emit( 'enter', e
);
11323 * Automatically adjust the size of the text input.
11325 * This only affects multiline inputs that are {@link #autosize autosized}.
11328 * @return {OO.ui.Widget} The widget, for chaining
11331 OO
.ui
.MultilineTextInputWidget
.prototype.adjustSize = function () {
11332 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
,
11333 idealHeight
, newHeight
, scrollWidth
, property
;
11335 if ( this.$input
.val() !== this.valCache
) {
11336 if ( this.autosize
) {
11338 .val( this.$input
.val() )
11339 .attr( 'rows', this.minRows
)
11340 // Set inline height property to 0 to measure scroll height
11341 .css( 'height', 0 );
11343 this.$clone
.removeClass( 'oo-ui-element-hidden' );
11345 this.valCache
= this.$input
.val();
11347 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
11349 // Remove inline height property to measure natural heights
11350 this.$clone
.css( 'height', '' );
11351 innerHeight
= this.$clone
.innerHeight();
11352 outerHeight
= this.$clone
.outerHeight();
11354 // Measure max rows height
11356 .attr( 'rows', this.maxRows
)
11357 .css( 'height', 'auto' )
11359 maxInnerHeight
= this.$clone
.innerHeight();
11361 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
11362 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
11363 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
11364 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
11366 this.$clone
.addClass( 'oo-ui-element-hidden' );
11368 // Only apply inline height when expansion beyond natural height is needed
11369 // Use the difference between the inner and outer height as a buffer
11370 newHeight
= idealHeight
> innerHeight
? idealHeight
+ ( outerHeight
- innerHeight
) : '';
11371 if ( newHeight
!== this.styleHeight
) {
11372 this.$input
.css( 'height', newHeight
);
11373 this.styleHeight
= newHeight
;
11374 this.emit( 'resize' );
11377 scrollWidth
= this.$input
[ 0 ].offsetWidth
- this.$input
[ 0 ].clientWidth
;
11378 if ( scrollWidth
!== this.scrollWidth
) {
11379 property
= this.$element
.css( 'direction' ) === 'rtl' ? 'left' : 'right';
11381 this.$label
.css( { right
: '', left
: '' } );
11382 this.$indicator
.css( { right
: '', left
: '' } );
11384 if ( scrollWidth
) {
11385 this.$indicator
.css( property
, scrollWidth
);
11386 if ( this.labelPosition
=== 'after' ) {
11387 this.$label
.css( property
, scrollWidth
);
11391 this.scrollWidth
= scrollWidth
;
11392 this.positionLabel();
11402 OO
.ui
.MultilineTextInputWidget
.prototype.getInputElement = function () {
11403 return $( '<textarea>' );
11407 * Check if the input automatically adjusts its size.
11409 * @return {boolean}
11411 OO
.ui
.MultilineTextInputWidget
.prototype.isAutosizing = function () {
11412 return !!this.autosize
;
11418 OO
.ui
.MultilineTextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
11419 OO
.ui
.MultilineTextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
11420 if ( state
.scrollTop
!== undefined ) {
11421 this.$input
.scrollTop( state
.scrollTop
);
11426 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
11427 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
11428 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
11430 * - by typing a value in the text input field. If the value exactly matches the value of a menu
11431 * option, that option will appear to be selected.
11432 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
11435 * After the user chooses an option, its `data` will be used as a new value for the widget.
11436 * A `label` also can be specified for each option: if given, it will be shown instead of the
11437 * `data` in the dropdown menu.
11439 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
11441 * For more information about menus and options, please see the
11442 * [OOUI documentation on MediaWiki][1].
11445 * // A ComboBoxInputWidget.
11446 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11447 * value: 'Option 1',
11449 * { data: 'Option 1' },
11450 * { data: 'Option 2' },
11451 * { data: 'Option 3' }
11454 * $( document.body ).append( comboBox.$element );
11457 * // Example: A ComboBoxInputWidget with additional option labels.
11458 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11459 * value: 'Option 1',
11462 * data: 'Option 1',
11463 * label: 'Option One'
11466 * data: 'Option 2',
11467 * label: 'Option Two'
11470 * data: 'Option 3',
11471 * label: 'Option Three'
11475 * $( document.body ).append( comboBox.$element );
11477 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
11480 * @extends OO.ui.TextInputWidget
11483 * @param {Object} [config] Configuration options
11484 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
11485 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu
11487 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful
11488 * in cases where the expanded menu is larger than its containing `<div>`. The specified overlay
11489 * layer is usually on top of the containing `<div>` and has a larger area. By default, the menu
11490 * uses relative positioning.
11491 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11493 OO
.ui
.ComboBoxInputWidget
= function OoUiComboBoxInputWidget( config
) {
11494 // Configuration initialization
11495 config
= $.extend( {
11496 autocomplete
: false
11499 // ComboBoxInputWidget shouldn't support `multiline`
11500 config
.multiline
= false;
11502 // See InputWidget#reusePreInfuseDOM about `config.$input`
11503 if ( config
.$input
) {
11504 config
.$input
.removeAttr( 'list' );
11507 // Parent constructor
11508 OO
.ui
.ComboBoxInputWidget
.parent
.call( this, config
);
11511 this.$overlay
= ( config
.$overlay
=== true ?
11512 OO
.ui
.getDefaultOverlay() : config
.$overlay
) || this.$element
;
11513 this.dropdownButton
= new OO
.ui
.ButtonWidget( {
11514 classes
: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ],
11515 label
: OO
.ui
.msg( 'ooui-combobox-button-label' ),
11517 invisibleLabel
: true,
11518 disabled
: this.disabled
11520 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend(
11524 $floatableContainer
: this.$element
,
11525 disabled
: this.isDisabled()
11531 this.connect( this, {
11532 change
: 'onInputChange',
11533 enter
: 'onInputEnter'
11535 this.dropdownButton
.connect( this, {
11536 click
: 'onDropdownButtonClick'
11538 this.menu
.connect( this, {
11539 choose
: 'onMenuChoose',
11540 add
: 'onMenuItemsChange',
11541 remove
: 'onMenuItemsChange',
11542 toggle
: 'onMenuToggle'
11546 this.$input
.attr( {
11548 'aria-owns': this.menu
.getElementId(),
11549 'aria-autocomplete': 'list'
11551 this.dropdownButton
.$button
.attr( {
11552 'aria-controls': this.menu
.getElementId()
11554 // Do not override options set via config.menu.items
11555 if ( config
.options
!== undefined ) {
11556 this.setOptions( config
.options
);
11558 this.$field
= $( '<div>' )
11559 .addClass( 'oo-ui-comboBoxInputWidget-field' )
11560 .append( this.$input
, this.dropdownButton
.$element
);
11562 .addClass( 'oo-ui-comboBoxInputWidget' )
11563 .append( this.$field
);
11564 this.$overlay
.append( this.menu
.$element
);
11565 this.onMenuItemsChange();
11570 OO
.inheritClass( OO
.ui
.ComboBoxInputWidget
, OO
.ui
.TextInputWidget
);
11575 * Get the combobox's menu.
11577 * @return {OO.ui.MenuSelectWidget} Menu widget
11579 OO
.ui
.ComboBoxInputWidget
.prototype.getMenu = function () {
11584 * Get the combobox's text input widget.
11586 * @return {OO.ui.TextInputWidget} Text input widget
11588 OO
.ui
.ComboBoxInputWidget
.prototype.getInput = function () {
11593 * Handle input change events.
11596 * @param {string} value New value
11598 OO
.ui
.ComboBoxInputWidget
.prototype.onInputChange = function ( value
) {
11599 var match
= this.menu
.findItemFromData( value
);
11601 this.menu
.selectItem( match
);
11602 if ( this.menu
.findHighlightedItem() ) {
11603 this.menu
.highlightItem( match
);
11606 if ( !this.isDisabled() ) {
11607 this.menu
.toggle( true );
11612 * Handle input enter events.
11616 OO
.ui
.ComboBoxInputWidget
.prototype.onInputEnter = function () {
11617 if ( !this.isDisabled() ) {
11618 this.menu
.toggle( false );
11623 * Handle button click events.
11627 OO
.ui
.ComboBoxInputWidget
.prototype.onDropdownButtonClick = function () {
11628 this.menu
.toggle();
11633 * Handle menu choose events.
11636 * @param {OO.ui.OptionWidget} item Chosen item
11638 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuChoose = function ( item
) {
11639 this.setValue( item
.getData() );
11643 * Handle menu item change events.
11647 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuItemsChange = function () {
11648 var match
= this.menu
.findItemFromData( this.getValue() );
11649 this.menu
.selectItem( match
);
11650 if ( this.menu
.findHighlightedItem() ) {
11651 this.menu
.highlightItem( match
);
11653 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu
.isEmpty() );
11657 * Handle menu toggle events.
11660 * @param {boolean} isVisible Open state of the menu
11662 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuToggle = function ( isVisible
) {
11663 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-open', isVisible
);
11667 * Update the disabled state of the controls
11671 * @return {OO.ui.ComboBoxInputWidget} The widget, for chaining
11673 OO
.ui
.ComboBoxInputWidget
.prototype.updateControlsDisabled = function () {
11674 var disabled
= this.isDisabled() || this.isReadOnly();
11675 if ( this.dropdownButton
) {
11676 this.dropdownButton
.setDisabled( disabled
);
11679 this.menu
.setDisabled( disabled
);
11687 OO
.ui
.ComboBoxInputWidget
.prototype.setDisabled = function () {
11689 OO
.ui
.ComboBoxInputWidget
.parent
.prototype.setDisabled
.apply( this, arguments
);
11690 this.updateControlsDisabled();
11697 OO
.ui
.ComboBoxInputWidget
.prototype.setReadOnly = function () {
11699 OO
.ui
.ComboBoxInputWidget
.parent
.prototype.setReadOnly
.apply( this, arguments
);
11700 this.updateControlsDisabled();
11705 * Set the options available for this input.
11707 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
11709 * @return {OO.ui.Widget} The widget, for chaining
11711 OO
.ui
.ComboBoxInputWidget
.prototype.setOptions = function ( options
) {
11714 .addItems( options
.map( function ( opt
) {
11715 return new OO
.ui
.MenuOptionWidget( {
11717 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
11725 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
11726 * which is a widget that is specified by reference before any optional configuration settings.
11728 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of
11731 * - **left**: The label is placed before the field-widget and aligned with the left margin.
11732 * A left-alignment is used for forms with many fields.
11733 * - **right**: The label is placed before the field-widget and aligned to the right margin.
11734 * A right-alignment is used for long but familiar forms which users tab through,
11735 * verifying the current field with a quick glance at the label.
11736 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
11737 * that users fill out from top to bottom.
11738 * - **inline**: The label is placed after the field-widget and aligned to the left.
11739 * An inline-alignment is best used with checkboxes or radio buttons.
11741 * Help text can either be:
11743 * - accessed via a help icon that appears in the upper right corner of the rendered field layout,
11745 * - shown as a subtle explanation below the label.
11747 * If the help text is brief, or is essential to always expose it, set `helpInline` to `true`.
11748 * If it is long or not essential, leave `helpInline` to its default, `false`.
11750 * Please see the [OOUI documentation on MediaWiki] [1] for examples and more information.
11752 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
11755 * @extends OO.ui.Layout
11756 * @mixins OO.ui.mixin.LabelElement
11757 * @mixins OO.ui.mixin.TitledElement
11760 * @param {OO.ui.Widget} fieldWidget Field widget
11761 * @param {Object} [config] Configuration options
11762 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top'
11764 * @cfg {Array} [errors] Error messages about the widget, which will be
11765 * displayed below the widget.
11766 * @cfg {Array} [warnings] Warning messages about the widget, which will be
11767 * displayed below the widget.
11768 * @cfg {Array} [successMessages] Success messages on user interactions with the widget,
11769 * which will be displayed below the widget.
11770 * The array may contain strings or OO.ui.HtmlSnippet instances.
11771 * @cfg {Array} [notices] Notices about the widget, which will be displayed
11772 * below the widget.
11773 * The array may contain strings or OO.ui.HtmlSnippet instances.
11774 * These are more visible than `help` messages when `helpInline` is set, and so
11775 * might be good for transient messages.
11776 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified
11777 * and `helpInline` is `false`, a "help" icon will appear in the upper-right
11778 * corner of the rendered field; clicking it will display the text in a popup.
11779 * If `helpInline` is `true`, then a subtle description will be shown after the
11781 * @cfg {boolean} [helpInline=false] Whether or not the help should be inline,
11782 * or shown when the "help" icon is clicked.
11783 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if
11785 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11787 * @throws {Error} An error is thrown if no widget is specified
11789 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
11790 // Allow passing positional parameters inside the config object
11791 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
11792 config
= fieldWidget
;
11793 fieldWidget
= config
.fieldWidget
;
11796 // Make sure we have required constructor arguments
11797 if ( fieldWidget
=== undefined ) {
11798 throw new Error( 'Widget not found' );
11801 // Configuration initialization
11802 config
= $.extend( { align
: 'left', helpInline
: false }, config
);
11804 // Parent constructor
11805 OO
.ui
.FieldLayout
.parent
.call( this, config
);
11807 // Mixin constructors
11808 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {
11809 $label
: $( '<label>' )
11811 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( { $titled
: this.$label
}, config
) );
11814 this.fieldWidget
= fieldWidget
;
11816 this.warnings
= [];
11817 this.successMessages
= [];
11819 this.$field
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
11820 this.$messages
= $( '<ul>' );
11821 this.$header
= $( '<span>' );
11822 this.$body
= $( '<div>' );
11824 this.helpInline
= config
.helpInline
;
11827 this.fieldWidget
.connect( this, {
11828 disable
: 'onFieldDisable'
11832 this.$help
= config
.help
?
11833 this.createHelpElement( config
.help
, config
.$overlay
) :
11835 if ( this.fieldWidget
.getInputId() ) {
11836 this.$label
.attr( 'for', this.fieldWidget
.getInputId() );
11837 if ( this.helpInline
) {
11838 this.$help
.attr( 'for', this.fieldWidget
.getInputId() );
11841 this.$label
.on( 'click', function () {
11842 this.fieldWidget
.simulateLabelClick();
11844 if ( this.helpInline
) {
11845 this.$help
.on( 'click', function () {
11846 this.fieldWidget
.simulateLabelClick();
11851 .addClass( 'oo-ui-fieldLayout' )
11852 .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget
.isDisabled() )
11853 .append( this.$body
);
11854 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
11855 this.$header
.addClass( 'oo-ui-fieldLayout-header' );
11856 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
11858 .addClass( 'oo-ui-fieldLayout-field' )
11859 .append( this.fieldWidget
.$element
);
11861 this.setErrors( config
.errors
|| [] );
11862 this.setWarnings( config
.warnings
|| [] );
11863 this.setSuccess( config
.successMessages
|| [] );
11864 this.setNotices( config
.notices
|| [] );
11865 this.setAlignment( config
.align
);
11866 // Call this again to take into account the widget's accessKey
11867 this.updateTitle();
11872 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
11873 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
11874 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
11879 * Handle field disable events.
11882 * @param {boolean} value Field is disabled
11884 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
11885 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
11889 * Get the widget contained by the field.
11891 * @return {OO.ui.Widget} Field widget
11893 OO
.ui
.FieldLayout
.prototype.getField = function () {
11894 return this.fieldWidget
;
11898 * Return `true` if the given field widget can be used with `'inline'` alignment (see
11899 * #setAlignment). Return `false` if it can't or if this can't be determined.
11901 * @return {boolean}
11903 OO
.ui
.FieldLayout
.prototype.isFieldInline = function () {
11904 // This is very simplistic, but should be good enough.
11905 return this.getField().$element
.prop( 'tagName' ).toLowerCase() === 'span';
11910 * @param {string} kind 'error' or 'notice'
11911 * @param {string|OO.ui.HtmlSnippet} text
11914 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
11915 var $listItem
, $icon
, message
;
11916 $listItem
= $( '<li>' );
11917 if ( kind
=== 'error' ) {
11918 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'error' ] } ).$element
;
11919 $listItem
.attr( 'role', 'alert' );
11920 } else if ( kind
=== 'warning' ) {
11921 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
11922 $listItem
.attr( 'role', 'alert' );
11923 } else if ( kind
=== 'success' ) {
11924 $icon
= new OO
.ui
.IconWidget( { icon
: 'check', flags
: [ 'success' ] } ).$element
;
11925 } else if ( kind
=== 'notice' ) {
11926 $icon
= new OO
.ui
.IconWidget( { icon
: 'notice' } ).$element
;
11930 message
= new OO
.ui
.LabelWidget( { label
: text
} );
11932 .append( $icon
, message
.$element
)
11933 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
11938 * Set the field alignment mode.
11941 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
11943 * @return {OO.ui.BookletLayout} The layout, for chaining
11945 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
11946 if ( value
!== this.align
) {
11947 // Default to 'left'
11948 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
11952 if ( value
=== 'inline' && !this.isFieldInline() ) {
11955 // Reorder elements
11957 if ( this.helpInline
) {
11958 if ( value
=== 'top' ) {
11959 this.$header
.append( this.$label
);
11960 this.$body
.append( this.$header
, this.$field
, this.$help
);
11961 } else if ( value
=== 'inline' ) {
11962 this.$header
.append( this.$label
, this.$help
);
11963 this.$body
.append( this.$field
, this.$header
);
11965 this.$header
.append( this.$label
, this.$help
);
11966 this.$body
.append( this.$header
, this.$field
);
11969 if ( value
=== 'top' ) {
11970 this.$header
.append( this.$help
, this.$label
);
11971 this.$body
.append( this.$header
, this.$field
);
11972 } else if ( value
=== 'inline' ) {
11973 this.$header
.append( this.$help
, this.$label
);
11974 this.$body
.append( this.$field
, this.$header
);
11976 this.$header
.append( this.$label
);
11977 this.$body
.append( this.$header
, this.$help
, this.$field
);
11980 // Set classes. The following classes can be used here:
11981 // * oo-ui-fieldLayout-align-left
11982 // * oo-ui-fieldLayout-align-right
11983 // * oo-ui-fieldLayout-align-top
11984 // * oo-ui-fieldLayout-align-inline
11985 if ( this.align
) {
11986 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
11988 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
11989 this.align
= value
;
11996 * Set the list of error messages.
11998 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
11999 * The array may contain strings or OO.ui.HtmlSnippet instances.
12001 * @return {OO.ui.BookletLayout} The layout, for chaining
12003 OO
.ui
.FieldLayout
.prototype.setErrors = function ( errors
) {
12004 this.errors
= errors
.slice();
12005 this.updateMessages();
12010 * Set the list of warning messages.
12012 * @param {Array} warnings Warning messages about the widget, which will be displayed below
12014 * The array may contain strings or OO.ui.HtmlSnippet instances.
12016 * @return {OO.ui.BookletLayout} The layout, for chaining
12018 OO
.ui
.FieldLayout
.prototype.setWarnings = function ( warnings
) {
12019 this.warnings
= warnings
.slice();
12020 this.updateMessages();
12025 * Set the list of success messages.
12027 * @param {Array} successMessages Success messages about the widget, which will be displayed below
12029 * The array may contain strings or OO.ui.HtmlSnippet instances.
12031 * @return {OO.ui.BookletLayout} The layout, for chaining
12033 OO
.ui
.FieldLayout
.prototype.setSuccess = function ( successMessages
) {
12034 this.successMessages
= successMessages
.slice();
12035 this.updateMessages();
12040 * Set the list of notice messages.
12042 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
12043 * The array may contain strings or OO.ui.HtmlSnippet instances.
12045 * @return {OO.ui.BookletLayout} The layout, for chaining
12047 OO
.ui
.FieldLayout
.prototype.setNotices = function ( notices
) {
12048 this.notices
= notices
.slice();
12049 this.updateMessages();
12054 * Update the rendering of error, warning, success and notice messages.
12058 OO
.ui
.FieldLayout
.prototype.updateMessages = function () {
12060 this.$messages
.empty();
12063 this.errors
.length
||
12064 this.warnings
.length
||
12065 this.successMessages
.length
||
12066 this.notices
.length
12068 this.$body
.after( this.$messages
);
12070 this.$messages
.remove();
12074 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
12075 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
12077 for ( i
= 0; i
< this.warnings
.length
; i
++ ) {
12078 this.$messages
.append( this.makeMessage( 'warning', this.warnings
[ i
] ) );
12080 for ( i
= 0; i
< this.successMessages
.length
; i
++ ) {
12081 this.$messages
.append( this.makeMessage( 'success', this.successMessages
[ i
] ) );
12083 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
12084 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
12089 * Include information about the widget's accessKey in our title. TitledElement calls this method.
12090 * (This is a bit of a hack.)
12093 * @param {string} title Tooltip label for 'title' attribute
12096 OO
.ui
.FieldLayout
.prototype.formatTitleWithAccessKey = function ( title
) {
12097 if ( this.fieldWidget
&& this.fieldWidget
.formatTitleWithAccessKey
) {
12098 return this.fieldWidget
.formatTitleWithAccessKey( title
);
12104 * Creates and returns the help element. Also sets the `aria-describedby`
12105 * attribute on the main element of the `fieldWidget`.
12108 * @param {string|OO.ui.HtmlSnippet} [help] Help text.
12109 * @param {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup.
12110 * @return {jQuery} The element that should become `this.$help`.
12112 OO
.ui
.FieldLayout
.prototype.createHelpElement = function ( help
, $overlay
) {
12113 var helpId
, helpWidget
;
12115 if ( this.helpInline
) {
12116 helpWidget
= new OO
.ui
.LabelWidget( {
12118 classes
: [ 'oo-ui-inline-help' ]
12121 helpId
= helpWidget
.getElementId();
12123 helpWidget
= new OO
.ui
.PopupButtonWidget( {
12124 $overlay
: $overlay
,
12128 classes
: [ 'oo-ui-fieldLayout-help' ],
12131 label
: OO
.ui
.msg( 'ooui-field-help' ),
12132 invisibleLabel
: true
12134 if ( help
instanceof OO
.ui
.HtmlSnippet
) {
12135 helpWidget
.getPopup().$body
.html( help
.toString() );
12137 helpWidget
.getPopup().$body
.text( help
);
12140 helpId
= helpWidget
.getPopup().getBodyId();
12143 // Set the 'aria-describedby' attribute on the fieldWidget
12144 // Preference given to an input or a button
12146 this.fieldWidget
.$input
||
12147 this.fieldWidget
.$button
||
12148 this.fieldWidget
.$element
12149 ).attr( 'aria-describedby', helpId
);
12151 return helpWidget
.$element
;
12155 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget,
12156 * a button, and an optional label and/or help text. The field-widget (e.g., a
12157 * {@link OO.ui.TextInputWidget TextInputWidget}), is required and is specified before any optional
12158 * configuration settings.
12160 * Labels can be aligned in one of four ways:
12162 * - **left**: The label is placed before the field-widget and aligned with the left margin.
12163 * A left-alignment is used for forms with many fields.
12164 * - **right**: The label is placed before the field-widget and aligned to the right margin.
12165 * A right-alignment is used for long but familiar forms which users tab through,
12166 * verifying the current field with a quick glance at the label.
12167 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
12168 * that users fill out from top to bottom.
12169 * - **inline**: The label is placed after the field-widget and aligned to the left.
12170 * An inline-alignment is best used with checkboxes or radio buttons.
12172 * Help text is accessed via a help icon that appears in the upper right corner of the rendered
12173 * field layout when help text is specified.
12176 * // Example of an ActionFieldLayout
12177 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
12178 * new OO.ui.TextInputWidget( {
12179 * placeholder: 'Field widget'
12181 * new OO.ui.ButtonWidget( {
12185 * label: 'An ActionFieldLayout. This label is aligned top',
12187 * help: 'This is help text'
12191 * $( document.body ).append( actionFieldLayout.$element );
12194 * @extends OO.ui.FieldLayout
12197 * @param {OO.ui.Widget} fieldWidget Field widget
12198 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
12199 * @param {Object} config
12201 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
12202 // Allow passing positional parameters inside the config object
12203 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
12204 config
= fieldWidget
;
12205 fieldWidget
= config
.fieldWidget
;
12206 buttonWidget
= config
.buttonWidget
;
12209 // Parent constructor
12210 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
12213 this.buttonWidget
= buttonWidget
;
12214 this.$button
= $( '<span>' );
12215 this.$input
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
12218 this.$element
.addClass( 'oo-ui-actionFieldLayout' );
12220 .addClass( 'oo-ui-actionFieldLayout-button' )
12221 .append( this.buttonWidget
.$element
);
12223 .addClass( 'oo-ui-actionFieldLayout-input' )
12224 .append( this.fieldWidget
.$element
);
12225 this.$field
.append( this.$input
, this.$button
);
12230 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
12233 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
12234 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
12235 * configured with a label as well. For more information and examples,
12236 * please see the [OOUI documentation on MediaWiki][1].
12239 * // Example of a fieldset layout
12240 * var input1 = new OO.ui.TextInputWidget( {
12241 * placeholder: 'A text input field'
12244 * var input2 = new OO.ui.TextInputWidget( {
12245 * placeholder: 'A text input field'
12248 * var fieldset = new OO.ui.FieldsetLayout( {
12249 * label: 'Example of a fieldset layout'
12252 * fieldset.addItems( [
12253 * new OO.ui.FieldLayout( input1, {
12254 * label: 'Field One'
12256 * new OO.ui.FieldLayout( input2, {
12257 * label: 'Field Two'
12260 * $( document.body ).append( fieldset.$element );
12262 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
12265 * @extends OO.ui.Layout
12266 * @mixins OO.ui.mixin.IconElement
12267 * @mixins OO.ui.mixin.LabelElement
12268 * @mixins OO.ui.mixin.GroupElement
12271 * @param {Object} [config] Configuration options
12272 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset.
12273 * See OO.ui.FieldLayout for more information about fields.
12274 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon
12275 * will appear in the upper-right corner of the rendered field; clicking it will display the text
12276 * in a popup. For important messages, you are advised to use `notices`, as they are always shown.
12277 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
12278 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
12280 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
12281 // Configuration initialization
12282 config
= config
|| {};
12284 // Parent constructor
12285 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
12287 // Mixin constructors
12288 OO
.ui
.mixin
.IconElement
.call( this, config
);
12289 OO
.ui
.mixin
.LabelElement
.call( this, config
);
12290 OO
.ui
.mixin
.GroupElement
.call( this, config
);
12293 this.$header
= $( '<legend>' );
12294 if ( config
.help
) {
12295 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
12296 $overlay
: config
.$overlay
,
12300 classes
: [ 'oo-ui-fieldsetLayout-help' ],
12303 label
: OO
.ui
.msg( 'ooui-field-help' ),
12304 invisibleLabel
: true
12306 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
12307 this.popupButtonWidget
.getPopup().$body
.html( config
.help
.toString() );
12309 this.popupButtonWidget
.getPopup().$body
.text( config
.help
);
12311 this.$help
= this.popupButtonWidget
.$element
;
12313 this.$help
= $( [] );
12318 .addClass( 'oo-ui-fieldsetLayout-header' )
12319 .append( this.$icon
, this.$label
, this.$help
);
12320 this.$group
.addClass( 'oo-ui-fieldsetLayout-group' );
12322 .addClass( 'oo-ui-fieldsetLayout' )
12323 .prepend( this.$header
, this.$group
);
12324 if ( Array
.isArray( config
.items
) ) {
12325 this.addItems( config
.items
);
12331 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
12332 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
12333 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
12334 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
12336 /* Static Properties */
12342 OO
.ui
.FieldsetLayout
.static.tagName
= 'fieldset';
12345 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use
12346 * browser-based form submission for the fields instead of handling them in JavaScript. Form layouts
12347 * can be configured with an HTML form action, an encoding type, and a method using the #action,
12348 * #enctype, and #method configs, respectively.
12349 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
12351 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
12352 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
12353 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
12354 * some fancier controls. Some controls have both regular and InputWidget variants, for example
12355 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
12356 * often have simplified APIs to match the capabilities of HTML forms.
12357 * See the [OOUI documentation on MediaWiki] [2] for more information about InputWidgets.
12359 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Forms
12360 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
12363 * // Example of a form layout that wraps a fieldset layout
12364 * var input1 = new OO.ui.TextInputWidget( {
12365 * placeholder: 'Username'
12367 * var input2 = new OO.ui.TextInputWidget( {
12368 * placeholder: 'Password',
12371 * var submit = new OO.ui.ButtonInputWidget( {
12375 * var fieldset = new OO.ui.FieldsetLayout( {
12376 * label: 'A form layout'
12378 * fieldset.addItems( [
12379 * new OO.ui.FieldLayout( input1, {
12380 * label: 'Username',
12383 * new OO.ui.FieldLayout( input2, {
12384 * label: 'Password',
12387 * new OO.ui.FieldLayout( submit )
12389 * var form = new OO.ui.FormLayout( {
12390 * items: [ fieldset ],
12391 * action: '/api/formhandler',
12394 * $( document.body ).append( form.$element );
12397 * @extends OO.ui.Layout
12398 * @mixins OO.ui.mixin.GroupElement
12401 * @param {Object} [config] Configuration options
12402 * @cfg {string} [method] HTML form `method` attribute
12403 * @cfg {string} [action] HTML form `action` attribute
12404 * @cfg {string} [enctype] HTML form `enctype` attribute
12405 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
12407 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
12410 // Configuration initialization
12411 config
= config
|| {};
12413 // Parent constructor
12414 OO
.ui
.FormLayout
.parent
.call( this, config
);
12416 // Mixin constructors
12417 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( { $group
: this.$element
}, config
) );
12420 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
12422 // Make sure the action is safe
12423 action
= config
.action
;
12424 if ( action
!== undefined && !OO
.ui
.isSafeUrl( action
) ) {
12425 action
= './' + action
;
12430 .addClass( 'oo-ui-formLayout' )
12432 method
: config
.method
,
12434 enctype
: config
.enctype
12436 if ( Array
.isArray( config
.items
) ) {
12437 this.addItems( config
.items
);
12443 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
12444 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
12449 * A 'submit' event is emitted when the form is submitted.
12454 /* Static Properties */
12460 OO
.ui
.FormLayout
.static.tagName
= 'form';
12465 * Handle form submit events.
12468 * @param {jQuery.Event} e Submit event
12470 * @return {OO.ui.FormLayout} The layout, for chaining
12472 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
12473 if ( this.emit( 'submit' ) ) {
12479 * PanelLayouts expand to cover the entire area of their parent. They can be configured with
12480 * scrolling, padding, and a frame, and are often used together with
12481 * {@link OO.ui.StackLayout StackLayouts}.
12484 * // Example of a panel layout
12485 * var panel = new OO.ui.PanelLayout( {
12489 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
12491 * $( document.body ).append( panel.$element );
12494 * @extends OO.ui.Layout
12497 * @param {Object} [config] Configuration options
12498 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
12499 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
12500 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
12501 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside
12504 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
12505 // Configuration initialization
12506 config
= $.extend( {
12513 // Parent constructor
12514 OO
.ui
.PanelLayout
.parent
.call( this, config
);
12517 this.$element
.addClass( 'oo-ui-panelLayout' );
12518 if ( config
.scrollable
) {
12519 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
12521 if ( config
.padded
) {
12522 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
12524 if ( config
.expanded
) {
12525 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
12527 if ( config
.framed
) {
12528 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
12534 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
12536 /* Static Methods */
12541 OO
.ui
.PanelLayout
.static.reusePreInfuseDOM = function ( node
, config
) {
12542 config
= OO
.ui
.PanelLayout
.parent
.static.reusePreInfuseDOM( node
, config
);
12543 if ( config
.preserveContent
!== false ) {
12544 config
.$content
= $( node
).contents();
12552 * Focus the panel layout
12554 * The default implementation just focuses the first focusable element in the panel
12556 OO
.ui
.PanelLayout
.prototype.focus = function () {
12557 OO
.ui
.findFocusable( this.$element
).focus();
12561 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
12562 * items), with small margins between them. Convenient when you need to put a number of block-level
12563 * widgets on a single line next to each other.
12565 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
12568 * // HorizontalLayout with a text input and a label
12569 * var layout = new OO.ui.HorizontalLayout( {
12571 * new OO.ui.LabelWidget( { label: 'Label' } ),
12572 * new OO.ui.TextInputWidget( { value: 'Text' } )
12575 * $( document.body ).append( layout.$element );
12578 * @extends OO.ui.Layout
12579 * @mixins OO.ui.mixin.GroupElement
12582 * @param {Object} [config] Configuration options
12583 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
12585 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
12586 // Configuration initialization
12587 config
= config
|| {};
12589 // Parent constructor
12590 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
12592 // Mixin constructors
12593 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( { $group
: this.$element
}, config
) );
12596 this.$element
.addClass( 'oo-ui-horizontalLayout' );
12597 if ( Array
.isArray( config
.items
) ) {
12598 this.addItems( config
.items
);
12604 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
12605 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);
12608 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
12609 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
12610 * (to adjust the value in increments) to allow the user to enter a number.
12613 * // A NumberInputWidget.
12614 * var numberInput = new OO.ui.NumberInputWidget( {
12615 * label: 'NumberInputWidget',
12616 * input: { value: 5 },
12620 * $( document.body ).append( numberInput.$element );
12623 * @extends OO.ui.TextInputWidget
12626 * @param {Object} [config] Configuration options
12627 * @cfg {Object} [minusButton] Configuration options to pass to the
12628 * {@link OO.ui.ButtonWidget decrementing button widget}.
12629 * @cfg {Object} [plusButton] Configuration options to pass to the
12630 * {@link OO.ui.ButtonWidget incrementing button widget}.
12631 * @cfg {number} [min=-Infinity] Minimum allowed value
12632 * @cfg {number} [max=Infinity] Maximum allowed value
12633 * @cfg {number|null} [step] If specified, the field only accepts values that are multiples of this.
12634 * @cfg {number} [buttonStep=step||1] Delta when using the buttons or Up/Down arrow keys.
12635 * Defaults to `step` if specified, otherwise `1`.
12636 * @cfg {number} [pageStep=10*buttonStep] Delta when using the Page-up/Page-down keys.
12637 * Defaults to 10 times `buttonStep`.
12638 * @cfg {boolean} [showButtons=true] Whether to show the plus and minus buttons.
12640 OO
.ui
.NumberInputWidget
= function OoUiNumberInputWidget( config
) {
12641 var $field
= $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' );
12643 // Configuration initialization
12644 config
= $.extend( {
12650 // For backward compatibility
12651 $.extend( config
, config
.input
);
12654 // Parent constructor
12655 OO
.ui
.NumberInputWidget
.parent
.call( this, $.extend( config
, {
12659 if ( config
.showButtons
) {
12660 this.minusButton
= new OO
.ui
.ButtonWidget( $.extend(
12662 disabled
: this.isDisabled(),
12664 classes
: [ 'oo-ui-numberInputWidget-minusButton' ],
12669 this.minusButton
.$element
.attr( 'aria-hidden', 'true' );
12670 this.plusButton
= new OO
.ui
.ButtonWidget( $.extend(
12672 disabled
: this.isDisabled(),
12674 classes
: [ 'oo-ui-numberInputWidget-plusButton' ],
12679 this.plusButton
.$element
.attr( 'aria-hidden', 'true' );
12684 keydown
: this.onKeyDown
.bind( this ),
12685 'wheel mousewheel DOMMouseScroll': this.onWheel
.bind( this )
12687 if ( config
.showButtons
) {
12688 this.plusButton
.connect( this, {
12689 click
: [ 'onButtonClick', +1 ]
12691 this.minusButton
.connect( this, {
12692 click
: [ 'onButtonClick', -1 ]
12697 $field
.append( this.$input
);
12698 if ( config
.showButtons
) {
12700 .prepend( this.minusButton
.$element
)
12701 .append( this.plusButton
.$element
);
12705 if ( config
.allowInteger
|| config
.isInteger
) {
12706 // Backward compatibility
12709 this.setRange( config
.min
, config
.max
);
12710 this.setStep( config
.buttonStep
, config
.pageStep
, config
.step
);
12711 // Set the validation method after we set step and range
12712 // so that it doesn't immediately call setValidityFlag
12713 this.setValidation( this.validateNumber
.bind( this ) );
12716 .addClass( 'oo-ui-numberInputWidget' )
12717 .toggleClass( 'oo-ui-numberInputWidget-buttoned', config
.showButtons
)
12723 OO
.inheritClass( OO
.ui
.NumberInputWidget
, OO
.ui
.TextInputWidget
);
12727 // Backward compatibility
12728 OO
.ui
.NumberInputWidget
.prototype.setAllowInteger = function ( flag
) {
12729 this.setStep( flag
? 1 : null );
12731 // Backward compatibility
12732 OO
.ui
.NumberInputWidget
.prototype.setIsInteger
= OO
.ui
.NumberInputWidget
.prototype.setAllowInteger
;
12734 // Backward compatibility
12735 OO
.ui
.NumberInputWidget
.prototype.getAllowInteger = function () {
12736 return this.step
=== 1;
12738 // Backward compatibility
12739 OO
.ui
.NumberInputWidget
.prototype.getIsInteger
= OO
.ui
.NumberInputWidget
.prototype.getAllowInteger
;
12742 * Set the range of allowed values
12744 * @param {number} min Minimum allowed value
12745 * @param {number} max Maximum allowed value
12747 OO
.ui
.NumberInputWidget
.prototype.setRange = function ( min
, max
) {
12749 throw new Error( 'Minimum (' + min
+ ') must not be greater than maximum (' + max
+ ')' );
12753 this.$input
.attr( 'min', this.min
);
12754 this.$input
.attr( 'max', this.max
);
12755 this.setValidityFlag();
12759 * Get the current range
12761 * @return {number[]} Minimum and maximum values
12763 OO
.ui
.NumberInputWidget
.prototype.getRange = function () {
12764 return [ this.min
, this.max
];
12768 * Set the stepping deltas
12770 * @param {number} [buttonStep=step||1] Delta when using the buttons or up/down arrow keys.
12771 * Defaults to `step` if specified, otherwise `1`.
12772 * @param {number} [pageStep=10*buttonStep] Delta when using the page-up/page-down keys.
12773 * Defaults to 10 times `buttonStep`.
12774 * @param {number|null} [step] If specified, the field only accepts values that are multiples
12777 OO
.ui
.NumberInputWidget
.prototype.setStep = function ( buttonStep
, pageStep
, step
) {
12778 if ( buttonStep
=== undefined ) {
12779 buttonStep
= step
|| 1;
12781 if ( pageStep
=== undefined ) {
12782 pageStep
= 10 * buttonStep
;
12784 if ( step
!== null && step
<= 0 ) {
12785 throw new Error( 'Step value, if given, must be positive' );
12787 if ( buttonStep
<= 0 ) {
12788 throw new Error( 'Button step value must be positive' );
12790 if ( pageStep
<= 0 ) {
12791 throw new Error( 'Page step value must be positive' );
12794 this.buttonStep
= buttonStep
;
12795 this.pageStep
= pageStep
;
12796 this.$input
.attr( 'step', this.step
|| 'any' );
12797 this.setValidityFlag();
12803 OO
.ui
.NumberInputWidget
.prototype.setValue = function ( value
) {
12804 if ( value
=== '' ) {
12805 // Some browsers allow a value in the input even if there isn't one reported by $input.val()
12806 // so here we make sure an 'empty' value is actually displayed as such.
12807 this.$input
.val( '' );
12809 return OO
.ui
.NumberInputWidget
.parent
.prototype.setValue
.call( this, value
);
12813 * Get the current stepping values
12815 * @return {number[]} Button step, page step, and validity step
12817 OO
.ui
.NumberInputWidget
.prototype.getStep = function () {
12818 return [ this.buttonStep
, this.pageStep
, this.step
];
12822 * Get the current value of the widget as a number
12824 * @return {number} May be NaN, or an invalid number
12826 OO
.ui
.NumberInputWidget
.prototype.getNumericValue = function () {
12827 return +this.getValue();
12831 * Adjust the value of the widget
12833 * @param {number} delta Adjustment amount
12835 OO
.ui
.NumberInputWidget
.prototype.adjustValue = function ( delta
) {
12836 var n
, v
= this.getNumericValue();
12839 if ( isNaN( delta
) || !isFinite( delta
) ) {
12840 throw new Error( 'Delta must be a finite number' );
12843 if ( isNaN( v
) ) {
12847 n
= Math
.max( Math
.min( n
, this.max
), this.min
);
12849 n
= Math
.round( n
/ this.step
) * this.step
;
12854 this.setValue( n
);
12861 * @param {string} value Field value
12862 * @return {boolean}
12864 OO
.ui
.NumberInputWidget
.prototype.validateNumber = function ( value
) {
12866 if ( value
=== '' ) {
12867 return !this.isRequired();
12870 if ( isNaN( n
) || !isFinite( n
) ) {
12874 if ( this.step
&& Math
.floor( n
/ this.step
) !== n
/ this.step
) {
12878 if ( n
< this.min
|| n
> this.max
) {
12886 * Handle mouse click events.
12889 * @param {number} dir +1 or -1
12891 OO
.ui
.NumberInputWidget
.prototype.onButtonClick = function ( dir
) {
12892 this.adjustValue( dir
* this.buttonStep
);
12896 * Handle mouse wheel events.
12899 * @param {jQuery.Event} event
12900 * @return {undefined/boolean} False to prevent default if event is handled
12902 OO
.ui
.NumberInputWidget
.prototype.onWheel = function ( event
) {
12905 if ( !this.isDisabled() && this.$input
.is( ':focus' ) ) {
12906 // Standard 'wheel' event
12907 if ( event
.originalEvent
.deltaMode
!== undefined ) {
12908 this.sawWheelEvent
= true;
12910 if ( event
.originalEvent
.deltaY
) {
12911 delta
= -event
.originalEvent
.deltaY
;
12912 } else if ( event
.originalEvent
.deltaX
) {
12913 delta
= event
.originalEvent
.deltaX
;
12916 // Non-standard events
12917 if ( !this.sawWheelEvent
) {
12918 if ( event
.originalEvent
.wheelDeltaX
) {
12919 delta
= -event
.originalEvent
.wheelDeltaX
;
12920 } else if ( event
.originalEvent
.wheelDeltaY
) {
12921 delta
= event
.originalEvent
.wheelDeltaY
;
12922 } else if ( event
.originalEvent
.wheelDelta
) {
12923 delta
= event
.originalEvent
.wheelDelta
;
12924 } else if ( event
.originalEvent
.detail
) {
12925 delta
= -event
.originalEvent
.detail
;
12930 delta
= delta
< 0 ? -1 : 1;
12931 this.adjustValue( delta
* this.buttonStep
);
12939 * Handle key down events.
12942 * @param {jQuery.Event} e Key down event
12943 * @return {undefined/boolean} False to prevent default if event is handled
12945 OO
.ui
.NumberInputWidget
.prototype.onKeyDown = function ( e
) {
12946 if ( !this.isDisabled() ) {
12947 switch ( e
.which
) {
12948 case OO
.ui
.Keys
.UP
:
12949 this.adjustValue( this.buttonStep
);
12951 case OO
.ui
.Keys
.DOWN
:
12952 this.adjustValue( -this.buttonStep
);
12954 case OO
.ui
.Keys
.PAGEUP
:
12955 this.adjustValue( this.pageStep
);
12957 case OO
.ui
.Keys
.PAGEDOWN
:
12958 this.adjustValue( -this.pageStep
);
12967 OO
.ui
.NumberInputWidget
.prototype.setDisabled = function ( disabled
) {
12969 OO
.ui
.NumberInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
12971 if ( this.minusButton
) {
12972 this.minusButton
.setDisabled( this.isDisabled() );
12974 if ( this.plusButton
) {
12975 this.plusButton
.setDisabled( this.isDisabled() );
12983 //# sourceMappingURL=oojs-ui-core.js.map.json