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-14T00:52:20Z
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' );
7477 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
7479 /* Static Properties */
7485 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
7491 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
7494 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
7495 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
7496 * See {@link OO.ui.DropdownWidget DropdownWidget},
7497 * {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}, and
7498 * {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
7499 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
7500 * and customized to be opened, closed, and displayed as needed.
7502 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
7503 * mouse outside the menu.
7505 * Menus also have support for keyboard interaction:
7507 * - Enter/Return key: choose and select a menu option
7508 * - Up-arrow key: highlight the previous menu option
7509 * - Down-arrow key: highlight the next menu option
7510 * - Escape key: hide the menu
7512 * Unlike most widgets, MenuSelectWidget is initially hidden and must be shown by calling #toggle.
7514 * Please see the [OOUI documentation on MediaWiki][1] for more information.
7515 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7518 * @extends OO.ui.SelectWidget
7519 * @mixins OO.ui.mixin.ClippableElement
7520 * @mixins OO.ui.mixin.FloatableElement
7523 * @param {Object} [config] Configuration options
7524 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu
7525 * items that match the text the user types. This config is used by
7526 * {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget} and
7527 * {@link OO.ui.mixin.LookupElement LookupElement}
7528 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
7529 * the text the user types. This config is used by
7530 * {@link OO.ui.TagMultiselectWidget TagMultiselectWidget}
7531 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks
7532 * the mouse anywhere on the page outside of this widget, the menu is hidden. For example, if
7533 * there is a button that toggles the menu's visibility on click, the menu will be hidden then
7534 * re-shown when the user clicks that button, unless the button (or its parent widget) is passed
7536 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
7537 * @cfg {jQuery} [$autoCloseIgnore] If these elements are clicked, don't auto-hide the menu.
7538 * @cfg {boolean} [hideOnChoose=true] Hide the menu when the user chooses an option.
7539 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
7540 * @cfg {boolean} [highlightOnFilter] Highlight the first result when filtering
7541 * @cfg {string} [filterMode='prefix'] The mode by which the menu filters the results.
7542 * Options are 'exact', 'prefix' or 'substring'. See `OO.ui.SelectWidget#getItemMatcher`
7543 * @param {number|string} [width] Width of the menu as a number of pixels or CSS string with unit
7544 * suffix, used by {@link OO.ui.mixin.ClippableElement ClippableElement}
7546 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
7547 // Configuration initialization
7548 config
= config
|| {};
7550 // Parent constructor
7551 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
7553 // Mixin constructors
7554 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( { $clippable
: this.$group
}, config
) );
7555 OO
.ui
.mixin
.FloatableElement
.call( this, config
);
7557 // Initial vertical positions other than 'center' will result in
7558 // the menu being flipped if there is not enough space in the container.
7559 // Store the original position so we know what to reset to.
7560 this.originalVerticalPosition
= this.verticalPosition
;
7563 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
7564 this.hideOnChoose
= config
.hideOnChoose
=== undefined || !!config
.hideOnChoose
;
7565 this.filterFromInput
= !!config
.filterFromInput
;
7566 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
7567 this.$widget
= config
.widget
? config
.widget
.$element
: null;
7568 this.$autoCloseIgnore
= config
.$autoCloseIgnore
|| $( [] );
7569 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
7570 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
7571 this.highlightOnFilter
= !!config
.highlightOnFilter
;
7572 this.lastHighlightedItem
= null;
7573 this.width
= config
.width
;
7574 this.filterMode
= config
.filterMode
;
7577 this.$element
.addClass( 'oo-ui-menuSelectWidget' );
7578 if ( config
.widget
) {
7579 this.setFocusOwner( config
.widget
.$tabIndexed
);
7582 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
7583 // that reference properties not initialized at that time of parent class construction
7584 // TODO: Find a better way to handle post-constructor setup
7585 this.visible
= false;
7586 this.$element
.addClass( 'oo-ui-element-hidden' );
7587 this.$focusOwner
.attr( 'aria-expanded', 'false' );
7592 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
7593 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
7594 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.FloatableElement
);
7601 * The menu is ready: it is visible and has been positioned and clipped.
7604 /* Static properties */
7607 * Positions to flip to if there isn't room in the container for the
7608 * menu in a specific direction.
7610 * @property {Object.<string,string>}
7612 OO
.ui
.MenuSelectWidget
.static.flippedPositions
= {
7622 * Handles document mouse down events.
7625 * @param {MouseEvent} e Mouse down event
7627 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
7631 this.$element
.add( this.$widget
).add( this.$autoCloseIgnore
).get(),
7636 this.toggle( false );
7643 OO
.ui
.MenuSelectWidget
.prototype.onDocumentKeyDown = function ( e
) {
7644 var currentItem
= this.findHighlightedItem() || this.findSelectedItem();
7646 if ( !this.isDisabled() && this.isVisible() ) {
7647 switch ( e
.keyCode
) {
7648 case OO
.ui
.Keys
.LEFT
:
7649 case OO
.ui
.Keys
.RIGHT
:
7650 // Do nothing if a text field is associated, arrow keys will be handled natively
7651 if ( !this.$input
) {
7652 OO
.ui
.MenuSelectWidget
.parent
.prototype.onDocumentKeyDown
.call( this, e
);
7655 case OO
.ui
.Keys
.ESCAPE
:
7656 case OO
.ui
.Keys
.TAB
:
7657 if ( currentItem
) {
7658 currentItem
.setHighlighted( false );
7660 this.toggle( false );
7661 // Don't prevent tabbing away, prevent defocusing
7662 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
7664 e
.stopPropagation();
7668 OO
.ui
.MenuSelectWidget
.parent
.prototype.onDocumentKeyDown
.call( this, e
);
7675 * Update menu item visibility and clipping after input changes (if filterFromInput is enabled)
7676 * or after items were added/removed (always).
7680 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
7681 var i
, item
, items
, visible
, section
, sectionEmpty
, filter
, exactFilter
,
7683 len
= this.items
.length
,
7684 showAll
= !this.isVisible(),
7687 if ( this.$input
&& this.filterFromInput
) {
7688 filter
= showAll
? null : this.getItemMatcher( this.$input
.val(), this.filterMode
);
7689 exactFilter
= this.getItemMatcher( this.$input
.val(), 'exact' );
7690 // Hide non-matching options, and also hide section headers if all options
7691 // in their section are hidden.
7692 for ( i
= 0; i
< len
; i
++ ) {
7693 item
= this.items
[ i
];
7694 if ( item
instanceof OO
.ui
.MenuSectionOptionWidget
) {
7696 // If the previous section was empty, hide its header
7697 section
.toggle( showAll
|| !sectionEmpty
);
7700 sectionEmpty
= true;
7701 } else if ( item
instanceof OO
.ui
.OptionWidget
) {
7702 visible
= showAll
|| filter( item
);
7703 exactMatch
= exactMatch
|| exactFilter( item
);
7704 anyVisible
= anyVisible
|| visible
;
7705 sectionEmpty
= sectionEmpty
&& !visible
;
7706 item
.toggle( visible
);
7709 // Process the final section
7711 section
.toggle( showAll
|| !sectionEmpty
);
7714 if ( anyVisible
&& this.items
.length
&& !exactMatch
) {
7715 this.scrollItemIntoView( this.items
[ 0 ] );
7718 if ( !anyVisible
) {
7719 this.highlightItem( null );
7722 this.$element
.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible
);
7725 this.highlightOnFilter
&&
7726 !( this.lastHighlightedItem
&& this.lastHighlightedItem
.isVisible() )
7728 // Highlight the first item on the list
7730 items
= this.getItems();
7731 for ( i
= 0; i
< items
.length
; i
++ ) {
7732 if ( items
[ i
].isVisible() ) {
7737 this.highlightItem( item
);
7738 this.lastHighlightedItem
= item
;
7743 // Reevaluate clipping
7750 OO
.ui
.MenuSelectWidget
.prototype.bindDocumentKeyDownListener = function () {
7751 if ( this.$input
) {
7752 this.$input
.on( 'keydown', this.onDocumentKeyDownHandler
);
7754 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindDocumentKeyDownListener
.call( this );
7761 OO
.ui
.MenuSelectWidget
.prototype.unbindDocumentKeyDownListener = function () {
7762 if ( this.$input
) {
7763 this.$input
.off( 'keydown', this.onDocumentKeyDownHandler
);
7765 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindDocumentKeyDownListener
.call( this );
7772 OO
.ui
.MenuSelectWidget
.prototype.bindDocumentKeyPressListener = function () {
7773 if ( this.$input
) {
7774 if ( this.filterFromInput
) {
7776 'keydown mouseup cut paste change input select',
7777 this.onInputEditHandler
7779 this.updateItemVisibility();
7782 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindDocumentKeyPressListener
.call( this );
7789 OO
.ui
.MenuSelectWidget
.prototype.unbindDocumentKeyPressListener = function () {
7790 if ( this.$input
) {
7791 if ( this.filterFromInput
) {
7793 'keydown mouseup cut paste change input select',
7794 this.onInputEditHandler
7796 this.updateItemVisibility();
7799 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindDocumentKeyPressListener
.call( this );
7806 * When a user chooses an item, the menu is closed, unless the hideOnChoose config option is
7809 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with
7810 * the keyboard or mouse and it becomes selected. To select an item programmatically,
7811 * use the #selectItem method.
7813 * @param {OO.ui.OptionWidget} item Item to choose
7815 * @return {OO.ui.Widget} The widget, for chaining
7817 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
7818 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
7819 if ( this.hideOnChoose
) {
7820 this.toggle( false );
7828 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
7830 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
7832 this.updateItemVisibility();
7840 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
7842 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
7844 this.updateItemVisibility();
7852 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
7854 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
7856 this.updateItemVisibility();
7862 * Toggle visibility of the menu. The menu is initially hidden and must be shown by calling
7863 * `.toggle( true )` after its #$element is attached to the DOM.
7865 * Do not show the menu while it is not attached to the DOM. The calculations required to display
7866 * it in the right place and with the right dimensions only work correctly while it is attached.
7867 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
7868 * strictly enforced, so currently it only generates a warning in the browser console.
7873 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
7874 var change
, originalHeight
, flippedHeight
;
7876 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
7877 change
= visible
!== this.isVisible();
7879 if ( visible
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
7880 OO
.ui
.warnDeprecation( 'MenuSelectWidget#toggle: Before calling this method, the menu must be attached to the DOM.' );
7881 this.warnedUnattached
= true;
7884 if ( change
&& visible
) {
7885 // Reset position before showing the popup again. It's possible we no longer need to flip
7886 // (e.g. if the user scrolled).
7887 this.setVerticalPosition( this.originalVerticalPosition
);
7891 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
7897 this.setIdealSize( this.width
);
7898 } else if ( this.$floatableContainer
) {
7899 this.$clippable
.css( 'width', 'auto' );
7901 this.$floatableContainer
[ 0 ].offsetWidth
> this.$clippable
[ 0 ].offsetWidth
?
7902 // Dropdown is smaller than handle so expand to width
7903 this.$floatableContainer
[ 0 ].offsetWidth
:
7904 // Dropdown is larger than handle so auto size
7907 this.$clippable
.css( 'width', '' );
7910 this.togglePositioning( !!this.$floatableContainer
);
7911 this.toggleClipping( true );
7913 this.bindDocumentKeyDownListener();
7914 this.bindDocumentKeyPressListener();
7917 ( this.isClippedVertically() || this.isFloatableOutOfView() ) &&
7918 this.originalVerticalPosition
!== 'center'
7920 // If opening the menu in one direction causes it to be clipped, flip it
7921 originalHeight
= this.$element
.height();
7922 this.setVerticalPosition(
7923 this.constructor.static.flippedPositions
[ this.originalVerticalPosition
]
7925 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
7926 // If flipping also causes it to be clipped, open in whichever direction
7927 // we have more space
7928 flippedHeight
= this.$element
.height();
7929 if ( originalHeight
> flippedHeight
) {
7930 this.setVerticalPosition( this.originalVerticalPosition
);
7934 // Note that we do not flip the menu's opening direction if the clipping changes
7935 // later (e.g. after the user scrolls), that seems like it would be annoying
7937 this.$focusOwner
.attr( 'aria-expanded', 'true' );
7939 if ( this.findSelectedItem() ) {
7940 this.$focusOwner
.attr( 'aria-activedescendant', this.findSelectedItem().getElementId() );
7941 this.findSelectedItem().scrollElementIntoView( { duration
: 0 } );
7945 if ( this.autoHide
) {
7946 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
7949 this.emit( 'ready' );
7951 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
7952 this.unbindDocumentKeyDownListener();
7953 this.unbindDocumentKeyPressListener();
7954 this.$focusOwner
.attr( 'aria-expanded', 'false' );
7955 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
7956 this.togglePositioning( false );
7957 this.toggleClipping( false );
7965 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
7966 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
7967 * users can interact with it.
7969 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7970 * OO.ui.DropdownInputWidget instead.
7973 * // A DropdownWidget with a menu that contains three options.
7974 * var dropDown = new OO.ui.DropdownWidget( {
7975 * label: 'Dropdown menu: Select a menu option',
7978 * new OO.ui.MenuOptionWidget( {
7982 * new OO.ui.MenuOptionWidget( {
7986 * new OO.ui.MenuOptionWidget( {
7994 * $( document.body ).append( dropDown.$element );
7996 * dropDown.getMenu().selectItemByData( 'b' );
7998 * dropDown.getMenu().findSelectedItem().getData(); // Returns 'b'.
8000 * For more information, please see the [OOUI documentation on MediaWiki] [1].
8002 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
8005 * @extends OO.ui.Widget
8006 * @mixins OO.ui.mixin.IconElement
8007 * @mixins OO.ui.mixin.IndicatorElement
8008 * @mixins OO.ui.mixin.LabelElement
8009 * @mixins OO.ui.mixin.TitledElement
8010 * @mixins OO.ui.mixin.TabIndexedElement
8013 * @param {Object} [config] Configuration options
8014 * @cfg {Object} [menu] Configuration options to pass to
8015 * {@link OO.ui.MenuSelectWidget menu select widget}.
8016 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful
8017 * in cases where the expanded menu is larger than its containing `<div>`. The specified overlay
8018 * layer is usually on top of the containing `<div>` and has a larger area. By default, the menu
8019 * uses relative positioning.
8020 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
8022 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
8023 // Configuration initialization
8024 config
= $.extend( { indicator
: 'down' }, config
);
8026 // Parent constructor
8027 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
8029 // Properties (must be set before TabIndexedElement constructor call)
8030 this.$handle
= $( '<button>' );
8031 this.$overlay
= ( config
.$overlay
=== true ?
8032 OO
.ui
.getDefaultOverlay() : config
.$overlay
) || this.$element
;
8034 // Mixin constructors
8035 OO
.ui
.mixin
.IconElement
.call( this, config
);
8036 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
8037 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8038 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {
8039 $titled
: this.$label
8041 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {
8042 $tabIndexed
: this.$handle
8046 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend( {
8048 $floatableContainer
: this.$element
8053 click
: this.onClick
.bind( this ),
8054 keydown
: this.onKeyDown
.bind( this ),
8055 // Hack? Handle type-to-search when menu is not expanded and not handling its own events.
8056 keypress
: this.menu
.onDocumentKeyPressHandler
,
8057 blur
: this.menu
.clearKeyPressBuffer
.bind( this.menu
)
8059 this.menu
.connect( this, {
8060 select
: 'onMenuSelect',
8061 toggle
: 'onMenuToggle'
8066 .addClass( 'oo-ui-dropdownWidget-handle' )
8069 'aria-owns': this.menu
.getElementId(),
8070 'aria-haspopup': 'listbox'
8072 .append( this.$icon
, this.$label
, this.$indicator
);
8074 .addClass( 'oo-ui-dropdownWidget' )
8075 .append( this.$handle
);
8076 this.$overlay
.append( this.menu
.$element
);
8081 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
8082 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
8083 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
8084 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
8085 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
8086 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
8093 * @return {OO.ui.MenuSelectWidget} Menu of widget
8095 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
8100 * Handles menu select events.
8103 * @param {OO.ui.MenuOptionWidget} item Selected menu item
8105 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
8109 this.setLabel( null );
8113 selectedLabel
= item
.getLabel();
8115 // If the label is a DOM element, clone it, because setLabel will append() it
8116 if ( selectedLabel
instanceof $ ) {
8117 selectedLabel
= selectedLabel
.clone();
8120 this.setLabel( selectedLabel
);
8124 * Handle menu toggle events.
8127 * @param {boolean} isVisible Open state of the menu
8129 OO
.ui
.DropdownWidget
.prototype.onMenuToggle = function ( isVisible
) {
8130 this.$element
.toggleClass( 'oo-ui-dropdownWidget-open', isVisible
);
8134 * Handle mouse click events.
8137 * @param {jQuery.Event} e Mouse click event
8138 * @return {undefined/boolean} False to prevent default if event is handled
8140 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
8141 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
8148 * Handle key down events.
8151 * @param {jQuery.Event} e Key down event
8152 * @return {undefined/boolean} False to prevent default if event is handled
8154 OO
.ui
.DropdownWidget
.prototype.onKeyDown = function ( e
) {
8156 !this.isDisabled() &&
8158 e
.which
=== OO
.ui
.Keys
.ENTER
||
8160 e
.which
=== OO
.ui
.Keys
.SPACE
&&
8161 // Avoid conflicts with type-to-search, see SelectWidget#onKeyPress.
8162 // Space only closes the menu is the user is not typing to search.
8163 this.menu
.keyPressBuffer
=== ''
8166 !this.menu
.isVisible() &&
8168 e
.which
=== OO
.ui
.Keys
.UP
||
8169 e
.which
=== OO
.ui
.Keys
.DOWN
8180 * RadioOptionWidget is an option widget that looks like a radio button.
8181 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
8182 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8184 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8187 * @extends OO.ui.OptionWidget
8190 * @param {Object} [config] Configuration options
8192 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
8193 // Configuration initialization
8194 config
= config
|| {};
8196 // Properties (must be done before parent constructor which calls #setDisabled)
8197 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
8199 // Parent constructor
8200 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
8203 // Remove implicit role, we're handling it ourselves
8204 this.radio
.$input
.attr( 'role', 'presentation' );
8206 .addClass( 'oo-ui-radioOptionWidget' )
8207 .attr( 'role', 'radio' )
8208 .attr( 'aria-checked', 'false' )
8209 .removeAttr( 'aria-selected' )
8210 .prepend( this.radio
.$element
);
8215 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
8217 /* Static Properties */
8223 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
8229 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
8235 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
8241 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
8248 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
8249 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
8251 this.radio
.setSelected( state
);
8253 .attr( 'aria-checked', state
.toString() )
8254 .removeAttr( 'aria-selected' );
8262 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
8263 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
8265 this.radio
.setDisabled( this.isDisabled() );
8271 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
8272 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
8273 * an interface for adding, removing and selecting options.
8274 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8276 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8277 * OO.ui.RadioSelectInputWidget instead.
8280 * // A RadioSelectWidget with RadioOptions.
8281 * var option1 = new OO.ui.RadioOptionWidget( {
8283 * label: 'Selected radio option'
8285 * option2 = new OO.ui.RadioOptionWidget( {
8287 * label: 'Unselected radio option'
8289 * radioSelect = new OO.ui.RadioSelectWidget( {
8290 * items: [ option1, option2 ]
8293 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
8294 * radioSelect.selectItem( option1 );
8296 * $( document.body ).append( radioSelect.$element );
8298 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8302 * @extends OO.ui.SelectWidget
8303 * @mixins OO.ui.mixin.TabIndexedElement
8306 * @param {Object} [config] Configuration options
8308 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
8309 // Parent constructor
8310 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
8312 // Mixin constructors
8313 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
8317 focus
: this.bindDocumentKeyDownListener
.bind( this ),
8318 blur
: this.unbindDocumentKeyDownListener
.bind( this )
8323 .addClass( 'oo-ui-radioSelectWidget' )
8324 .attr( 'role', 'radiogroup' );
8329 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
8330 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
8333 * MultioptionWidgets are special elements that can be selected and configured with data. The
8334 * data is often unique for each option, but it does not have to be. MultioptionWidgets are used
8335 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
8336 * and examples, please see the [OOUI documentation on MediaWiki][1].
8338 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8341 * @extends OO.ui.Widget
8342 * @mixins OO.ui.mixin.ItemWidget
8343 * @mixins OO.ui.mixin.LabelElement
8344 * @mixins OO.ui.mixin.TitledElement
8347 * @param {Object} [config] Configuration options
8348 * @cfg {boolean} [selected=false] Whether the option is initially selected
8350 OO
.ui
.MultioptionWidget
= function OoUiMultioptionWidget( config
) {
8351 // Configuration initialization
8352 config
= config
|| {};
8354 // Parent constructor
8355 OO
.ui
.MultioptionWidget
.parent
.call( this, config
);
8357 // Mixin constructors
8358 OO
.ui
.mixin
.ItemWidget
.call( this );
8359 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8360 OO
.ui
.mixin
.TitledElement
.call( this, config
);
8363 this.selected
= null;
8367 .addClass( 'oo-ui-multioptionWidget' )
8368 .append( this.$label
);
8369 this.setSelected( config
.selected
);
8374 OO
.inheritClass( OO
.ui
.MultioptionWidget
, OO
.ui
.Widget
);
8375 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.ItemWidget
);
8376 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.LabelElement
);
8377 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.TitledElement
);
8384 * A change event is emitted when the selected state of the option changes.
8386 * @param {boolean} selected Whether the option is now selected
8392 * Check if the option is selected.
8394 * @return {boolean} Item is selected
8396 OO
.ui
.MultioptionWidget
.prototype.isSelected = function () {
8397 return this.selected
;
8401 * Set the option’s selected state. In general, all modifications to the selection
8402 * should be handled by the SelectWidget’s
8403 * {@link OO.ui.SelectWidget#selectItem selectItem( [item] )} method instead of this method.
8405 * @param {boolean} [state=false] Select option
8407 * @return {OO.ui.Widget} The widget, for chaining
8409 OO
.ui
.MultioptionWidget
.prototype.setSelected = function ( state
) {
8411 if ( this.selected
!== state
) {
8412 this.selected
= state
;
8413 this.emit( 'change', state
);
8414 this.$element
.toggleClass( 'oo-ui-multioptionWidget-selected', state
);
8420 * MultiselectWidget allows selecting multiple options from a list.
8422 * For more information about menus and options, please see the [OOUI documentation
8425 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
8429 * @extends OO.ui.Widget
8430 * @mixins OO.ui.mixin.GroupWidget
8431 * @mixins OO.ui.mixin.TitledElement
8434 * @param {Object} [config] Configuration options
8435 * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
8437 OO
.ui
.MultiselectWidget
= function OoUiMultiselectWidget( config
) {
8438 // Parent constructor
8439 OO
.ui
.MultiselectWidget
.parent
.call( this, config
);
8441 // Configuration initialization
8442 config
= config
|| {};
8444 // Mixin constructors
8445 OO
.ui
.mixin
.GroupWidget
.call( this, config
);
8446 OO
.ui
.mixin
.TitledElement
.call( this, config
);
8452 // This is mostly for compatibility with TagMultiselectWidget... normally, 'change' is emitted
8453 // by GroupElement only when items are added/removed
8454 this.connect( this, {
8455 select
: [ 'emit', 'change' ]
8459 if ( config
.items
) {
8460 this.addItems( config
.items
);
8462 this.$group
.addClass( 'oo-ui-multiselectWidget-group' );
8463 this.$element
.addClass( 'oo-ui-multiselectWidget' )
8464 .append( this.$group
);
8469 OO
.inheritClass( OO
.ui
.MultiselectWidget
, OO
.ui
.Widget
);
8470 OO
.mixinClass( OO
.ui
.MultiselectWidget
, OO
.ui
.mixin
.GroupWidget
);
8471 OO
.mixinClass( OO
.ui
.MultiselectWidget
, OO
.ui
.mixin
.TitledElement
);
8478 * A change event is emitted when the set of items changes, or an item is selected or deselected.
8484 * A select event is emitted when an item is selected or deselected.
8490 * Find options that are selected.
8492 * @return {OO.ui.MultioptionWidget[]} Selected options
8494 OO
.ui
.MultiselectWidget
.prototype.findSelectedItems = function () {
8495 return this.items
.filter( function ( item
) {
8496 return item
.isSelected();
8501 * Find the data of options that are selected.
8503 * @return {Object[]|string[]} Values of selected options
8505 OO
.ui
.MultiselectWidget
.prototype.findSelectedItemsData = function () {
8506 return this.findSelectedItems().map( function ( item
) {
8512 * Select options by reference. Options not mentioned in the `items` array will be deselected.
8514 * @param {OO.ui.MultioptionWidget[]} items Items to select
8516 * @return {OO.ui.Widget} The widget, for chaining
8518 OO
.ui
.MultiselectWidget
.prototype.selectItems = function ( items
) {
8519 this.items
.forEach( function ( item
) {
8520 var selected
= items
.indexOf( item
) !== -1;
8521 item
.setSelected( selected
);
8527 * Select items by their data. Options not mentioned in the `datas` array will be deselected.
8529 * @param {Object[]|string[]} datas Values of items to select
8531 * @return {OO.ui.Widget} The widget, for chaining
8533 OO
.ui
.MultiselectWidget
.prototype.selectItemsByData = function ( datas
) {
8536 items
= datas
.map( function ( data
) {
8537 return widget
.findItemFromData( data
);
8539 this.selectItems( items
);
8544 * CheckboxMultioptionWidget is an option widget that looks like a checkbox.
8545 * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
8546 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8548 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8551 * @extends OO.ui.MultioptionWidget
8554 * @param {Object} [config] Configuration options
8556 OO
.ui
.CheckboxMultioptionWidget
= function OoUiCheckboxMultioptionWidget( config
) {
8557 // Configuration initialization
8558 config
= config
|| {};
8560 // Properties (must be done before parent constructor which calls #setDisabled)
8561 this.checkbox
= new OO
.ui
.CheckboxInputWidget();
8563 // Parent constructor
8564 OO
.ui
.CheckboxMultioptionWidget
.parent
.call( this, config
);
8567 this.checkbox
.on( 'change', this.onCheckboxChange
.bind( this ) );
8568 this.$element
.on( 'keydown', this.onKeyDown
.bind( this ) );
8572 .addClass( 'oo-ui-checkboxMultioptionWidget' )
8573 .prepend( this.checkbox
.$element
);
8578 OO
.inheritClass( OO
.ui
.CheckboxMultioptionWidget
, OO
.ui
.MultioptionWidget
);
8580 /* Static Properties */
8586 OO
.ui
.CheckboxMultioptionWidget
.static.tagName
= 'label';
8591 * Handle checkbox selected state change.
8595 OO
.ui
.CheckboxMultioptionWidget
.prototype.onCheckboxChange = function () {
8596 this.setSelected( this.checkbox
.isSelected() );
8602 OO
.ui
.CheckboxMultioptionWidget
.prototype.setSelected = function ( state
) {
8603 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setSelected
.call( this, state
);
8604 this.checkbox
.setSelected( state
);
8611 OO
.ui
.CheckboxMultioptionWidget
.prototype.setDisabled = function ( disabled
) {
8612 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
8613 this.checkbox
.setDisabled( this.isDisabled() );
8620 OO
.ui
.CheckboxMultioptionWidget
.prototype.focus = function () {
8621 this.checkbox
.focus();
8625 * Handle key down events.
8628 * @param {jQuery.Event} e
8630 OO
.ui
.CheckboxMultioptionWidget
.prototype.onKeyDown = function ( e
) {
8632 element
= this.getElementGroup(),
8635 if ( e
.keyCode
=== OO
.ui
.Keys
.LEFT
|| e
.keyCode
=== OO
.ui
.Keys
.UP
) {
8636 nextItem
= element
.getRelativeFocusableItem( this, -1 );
8637 } else if ( e
.keyCode
=== OO
.ui
.Keys
.RIGHT
|| e
.keyCode
=== OO
.ui
.Keys
.DOWN
) {
8638 nextItem
= element
.getRelativeFocusableItem( this, 1 );
8648 * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
8649 * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
8650 * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
8651 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8653 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8654 * OO.ui.CheckboxMultiselectInputWidget instead.
8657 * // A CheckboxMultiselectWidget with CheckboxMultioptions.
8658 * var option1 = new OO.ui.CheckboxMultioptionWidget( {
8661 * label: 'Selected checkbox'
8663 * option2 = new OO.ui.CheckboxMultioptionWidget( {
8665 * label: 'Unselected checkbox'
8667 * multiselect = new OO.ui.CheckboxMultiselectWidget( {
8668 * items: [ option1, option2 ]
8670 * $( document.body ).append( multiselect.$element );
8672 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8675 * @extends OO.ui.MultiselectWidget
8678 * @param {Object} [config] Configuration options
8680 OO
.ui
.CheckboxMultiselectWidget
= function OoUiCheckboxMultiselectWidget( config
) {
8681 // Parent constructor
8682 OO
.ui
.CheckboxMultiselectWidget
.parent
.call( this, config
);
8685 this.$lastClicked
= null;
8688 this.$group
.on( 'click', this.onClick
.bind( this ) );
8691 this.$element
.addClass( 'oo-ui-checkboxMultiselectWidget' );
8696 OO
.inheritClass( OO
.ui
.CheckboxMultiselectWidget
, OO
.ui
.MultiselectWidget
);
8701 * Get an option by its position relative to the specified item (or to the start of the
8702 * option array, if item is `null`). The direction in which to search through the option array
8703 * is specified with a number: -1 for reverse (the default) or 1 for forward. The method will
8704 * return an option, or `null` if there are no options in the array.
8706 * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or
8707 * `null` to start at the beginning of the array.
8708 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
8709 * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items
8712 OO
.ui
.CheckboxMultiselectWidget
.prototype.getRelativeFocusableItem = function ( item
, direction
) {
8713 var currentIndex
, nextIndex
, i
,
8714 increase
= direction
> 0 ? 1 : -1,
8715 len
= this.items
.length
;
8718 currentIndex
= this.items
.indexOf( item
);
8719 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
8721 // If no item is selected and moving forward, start at the beginning.
8722 // If moving backward, start at the end.
8723 nextIndex
= direction
> 0 ? 0 : len
- 1;
8726 for ( i
= 0; i
< len
; i
++ ) {
8727 item
= this.items
[ nextIndex
];
8728 if ( item
&& !item
.isDisabled() ) {
8731 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
8737 * Handle click events on checkboxes.
8739 * @param {jQuery.Event} e
8741 OO
.ui
.CheckboxMultiselectWidget
.prototype.onClick = function ( e
) {
8742 var $options
, lastClickedIndex
, nowClickedIndex
, i
, direction
, wasSelected
, items
,
8743 $lastClicked
= this.$lastClicked
,
8744 $nowClicked
= $( e
.target
).closest( '.oo-ui-checkboxMultioptionWidget' )
8745 .not( '.oo-ui-widget-disabled' );
8747 // Allow selecting multiple options at once by Shift-clicking them
8748 if ( $lastClicked
&& $nowClicked
.length
&& e
.shiftKey
) {
8749 $options
= this.$group
.find( '.oo-ui-checkboxMultioptionWidget' );
8750 lastClickedIndex
= $options
.index( $lastClicked
);
8751 nowClickedIndex
= $options
.index( $nowClicked
);
8752 // If it's the same item, either the user is being silly, or it's a fake event generated
8753 // by the browser. In either case we don't need custom handling.
8754 if ( nowClickedIndex
!== lastClickedIndex
) {
8756 wasSelected
= items
[ nowClickedIndex
].isSelected();
8757 direction
= nowClickedIndex
> lastClickedIndex
? 1 : -1;
8759 // This depends on the DOM order of the items and the order of the .items array being
8761 for ( i
= lastClickedIndex
; i
!== nowClickedIndex
; i
+= direction
) {
8762 if ( !items
[ i
].isDisabled() ) {
8763 items
[ i
].setSelected( !wasSelected
);
8766 // For the now-clicked element, use immediate timeout to allow the browser to do its own
8767 // handling first, then set our value. The order in which events happen is different for
8768 // clicks on the <input> and on the <label> and there are additional fake clicks fired
8769 // for non-click actions that change the checkboxes.
8771 setTimeout( function () {
8772 if ( !items
[ nowClickedIndex
].isDisabled() ) {
8773 items
[ nowClickedIndex
].setSelected( !wasSelected
);
8779 if ( $nowClicked
.length
) {
8780 this.$lastClicked
= $nowClicked
;
8788 * @return {OO.ui.Widget} The widget, for chaining
8790 OO
.ui
.CheckboxMultiselectWidget
.prototype.focus = function () {
8792 if ( !this.isDisabled() ) {
8793 item
= this.getRelativeFocusableItem( null, 1 );
8804 OO
.ui
.CheckboxMultiselectWidget
.prototype.simulateLabelClick = function () {
8809 * Progress bars visually display the status of an operation, such as a download,
8810 * and can be either determinate or indeterminate:
8812 * - **determinate** process bars show the percent of an operation that is complete.
8814 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
8815 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
8816 * not use percentages.
8818 * The value of the `progress` configuration determines whether the bar is determinate
8822 * // Examples of determinate and indeterminate progress bars.
8823 * var progressBar1 = new OO.ui.ProgressBarWidget( {
8826 * var progressBar2 = new OO.ui.ProgressBarWidget();
8828 * // Create a FieldsetLayout to layout progress bars.
8829 * var fieldset = new OO.ui.FieldsetLayout;
8830 * fieldset.addItems( [
8831 * new OO.ui.FieldLayout( progressBar1, {
8832 * label: 'Determinate',
8835 * new OO.ui.FieldLayout( progressBar2, {
8836 * label: 'Indeterminate',
8840 * $( document.body ).append( fieldset.$element );
8843 * @extends OO.ui.Widget
8846 * @param {Object} [config] Configuration options
8847 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
8848 * To create a determinate progress bar, specify a number that reflects the initial
8850 * By default, the progress bar is indeterminate.
8852 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
8853 // Configuration initialization
8854 config
= config
|| {};
8856 // Parent constructor
8857 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
8860 this.$bar
= $( '<div>' );
8861 this.progress
= null;
8864 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
8865 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
8868 role
: 'progressbar',
8870 'aria-valuemax': 100
8872 .addClass( 'oo-ui-progressBarWidget' )
8873 .append( this.$bar
);
8878 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
8880 /* Static Properties */
8886 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
8891 * Get the percent of the progress that has been completed. Indeterminate progresses will
8894 * @return {number|boolean} Progress percent
8896 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
8897 return this.progress
;
8901 * Set the percent of the process completed or `false` for an indeterminate process.
8903 * @param {number|boolean} progress Progress percent or `false` for indeterminate
8905 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
8906 this.progress
= progress
;
8908 if ( progress
!== false ) {
8909 this.$bar
.css( 'width', this.progress
+ '%' );
8910 this.$element
.attr( 'aria-valuenow', this.progress
);
8912 this.$bar
.css( 'width', '' );
8913 this.$element
.removeAttr( 'aria-valuenow' );
8915 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress
=== false );
8919 * InputWidget is the base class for all input widgets, which
8920 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox
8921 * inputs}, {@link OO.ui.RadioInputWidget radio inputs}, and
8922 * {@link OO.ui.ButtonInputWidget button inputs}.
8923 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
8925 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
8929 * @extends OO.ui.Widget
8930 * @mixins OO.ui.mixin.TabIndexedElement
8931 * @mixins OO.ui.mixin.TitledElement
8932 * @mixins OO.ui.mixin.AccessKeyedElement
8935 * @param {Object} [config] Configuration options
8936 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
8937 * @cfg {string} [value=''] The value of the input.
8938 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
8939 * @cfg {string} [inputId] The value of the input’s HTML `id` attribute.
8940 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the
8941 * value of an input before it is accepted.
8943 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
8944 // Configuration initialization
8945 config
= config
|| {};
8947 // Parent constructor
8948 OO
.ui
.InputWidget
.parent
.call( this, config
);
8951 // See #reusePreInfuseDOM about config.$input
8952 this.$input
= config
.$input
|| this.getInputElement( config
);
8954 this.inputFilter
= config
.inputFilter
;
8956 // Mixin constructors
8957 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {
8958 $tabIndexed
: this.$input
8960 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {
8961 $titled
: this.$input
8963 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {
8964 $accessKeyed
: this.$input
8968 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
8972 .addClass( 'oo-ui-inputWidget-input' )
8973 .attr( 'name', config
.name
)
8974 .prop( 'disabled', this.isDisabled() );
8976 .addClass( 'oo-ui-inputWidget' )
8977 .append( this.$input
);
8978 this.setValue( config
.value
);
8980 this.setDir( config
.dir
);
8982 if ( config
.inputId
!== undefined ) {
8983 this.setInputId( config
.inputId
);
8989 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
8990 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
8991 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
8992 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
8994 /* Static Methods */
8999 OO
.ui
.InputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
9000 config
= OO
.ui
.InputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
9001 // Reusing `$input` lets browsers preserve inputted values across page reloads, see T114134.
9002 config
.$input
= $( node
).find( '.oo-ui-inputWidget-input' );
9009 OO
.ui
.InputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9010 var state
= OO
.ui
.InputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9011 if ( config
.$input
&& config
.$input
.length
) {
9012 state
.value
= config
.$input
.val();
9013 // Might be better in TabIndexedElement, but it's awkward to do there because
9014 // mixins are awkward
9015 state
.focus
= config
.$input
.is( ':focus' );
9025 * A change event is emitted when the value of the input changes.
9027 * @param {string} value
9033 * Get input element.
9035 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
9036 * different circumstances. The element must have a `value` property (like form elements).
9039 * @param {Object} config Configuration options
9040 * @return {jQuery} Input element
9042 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
9043 return $( '<input>' );
9047 * Handle potentially value-changing events.
9050 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
9052 OO
.ui
.InputWidget
.prototype.onEdit = function () {
9054 if ( !this.isDisabled() ) {
9055 // Allow the stack to clear so the value will be updated
9056 setTimeout( function () {
9057 widget
.setValue( widget
.$input
.val() );
9063 * Get the value of the input.
9065 * @return {string} Input value
9067 OO
.ui
.InputWidget
.prototype.getValue = function () {
9068 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
9069 // it, and we won't know unless they're kind enough to trigger a 'change' event.
9070 var value
= this.$input
.val();
9071 if ( this.value
!== value
) {
9072 this.setValue( value
);
9078 * Set the directionality of the input.
9080 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
9082 * @return {OO.ui.Widget} The widget, for chaining
9084 OO
.ui
.InputWidget
.prototype.setDir = function ( dir
) {
9085 this.$input
.prop( 'dir', dir
);
9090 * Set the value of the input.
9092 * @param {string} value New value
9095 * @return {OO.ui.Widget} The widget, for chaining
9097 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
9098 value
= this.cleanUpValue( value
);
9099 // Update the DOM if it has changed. Note that with cleanUpValue, it
9100 // is possible for the DOM value to change without this.value changing.
9101 if ( this.$input
.val() !== value
) {
9102 this.$input
.val( value
);
9104 if ( this.value
!== value
) {
9106 this.emit( 'change', this.value
);
9108 // The first time that the value is set (probably while constructing the widget),
9109 // remember it in defaultValue. This property can be later used to check whether
9110 // the value of the input has been changed since it was created.
9111 if ( this.defaultValue
=== undefined ) {
9112 this.defaultValue
= this.value
;
9113 this.$input
[ 0 ].defaultValue
= this.defaultValue
;
9119 * Clean up incoming value.
9121 * Ensures value is a string, and converts undefined and null to empty string.
9124 * @param {string} value Original value
9125 * @return {string} Cleaned up value
9127 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
9128 if ( value
=== undefined || value
=== null ) {
9130 } else if ( this.inputFilter
) {
9131 return this.inputFilter( String( value
) );
9133 return String( value
);
9140 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
9141 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9142 if ( this.$input
) {
9143 this.$input
.prop( 'disabled', this.isDisabled() );
9149 * Set the 'id' attribute of the `<input>` element.
9151 * @param {string} id
9153 * @return {OO.ui.Widget} The widget, for chaining
9155 OO
.ui
.InputWidget
.prototype.setInputId = function ( id
) {
9156 this.$input
.attr( 'id', id
);
9163 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
9164 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
9165 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
9166 this.setValue( state
.value
);
9168 if ( state
.focus
) {
9174 * Data widget intended for creating `<input type="hidden">` inputs.
9177 * @extends OO.ui.Widget
9180 * @param {Object} [config] Configuration options
9181 * @cfg {string} [value=''] The value of the input.
9182 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
9184 OO
.ui
.HiddenInputWidget
= function OoUiHiddenInputWidget( config
) {
9185 // Configuration initialization
9186 config
= $.extend( { value
: '', name
: '' }, config
);
9188 // Parent constructor
9189 OO
.ui
.HiddenInputWidget
.parent
.call( this, config
);
9192 this.$element
.attr( {
9194 value
: config
.value
,
9197 this.$element
.removeAttr( 'aria-disabled' );
9202 OO
.inheritClass( OO
.ui
.HiddenInputWidget
, OO
.ui
.Widget
);
9204 /* Static Properties */
9210 OO
.ui
.HiddenInputWidget
.static.tagName
= 'input';
9213 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
9214 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
9215 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
9216 * HTML `<button>` (the default) or an HTML `<input>` tags. See the
9217 * [OOUI documentation on MediaWiki] [1] for more information.
9220 * // A ButtonInputWidget rendered as an HTML button, the default.
9221 * var button = new OO.ui.ButtonInputWidget( {
9222 * label: 'Input button',
9226 * $( document.body ).append( button.$element );
9228 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#Button_inputs
9231 * @extends OO.ui.InputWidget
9232 * @mixins OO.ui.mixin.ButtonElement
9233 * @mixins OO.ui.mixin.IconElement
9234 * @mixins OO.ui.mixin.IndicatorElement
9235 * @mixins OO.ui.mixin.LabelElement
9236 * @mixins OO.ui.mixin.FlaggedElement
9239 * @param {Object} [config] Configuration options
9240 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute:
9241 * 'button', 'submit' or 'reset'.
9242 * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
9243 * Widgets configured to be an `<input>` do not support {@link #icon icons} and
9244 * {@link #indicator indicators},
9245 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should
9246 * only be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
9248 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
9249 // Configuration initialization
9250 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
9252 // See InputWidget#reusePreInfuseDOM about config.$input
9253 if ( config
.$input
) {
9254 config
.$input
.empty();
9257 // Properties (must be set before parent constructor, which calls #setValue)
9258 this.useInputTag
= config
.useInputTag
;
9260 // Parent constructor
9261 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
9263 // Mixin constructors
9264 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {
9265 $button
: this.$input
9267 OO
.ui
.mixin
.IconElement
.call( this, config
);
9268 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
9269 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9270 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
9273 if ( !config
.useInputTag
) {
9274 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
9276 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
9281 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
9282 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
9283 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
9284 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
9285 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
9286 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.FlaggedElement
);
9288 /* Static Properties */
9294 OO
.ui
.ButtonInputWidget
.static.tagName
= 'span';
9302 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
9304 type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ? config
.type
: 'button';
9305 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
9311 * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
9313 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
9314 * text, or `null` for no label
9316 * @return {OO.ui.Widget} The widget, for chaining
9318 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
9319 if ( typeof label
=== 'function' ) {
9320 label
= OO
.ui
.resolveMsg( label
);
9323 if ( this.useInputTag
) {
9324 // Discard non-plaintext labels
9325 if ( typeof label
!== 'string' ) {
9329 this.$input
.val( label
);
9332 return OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
9336 * Set the value of the input.
9338 * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
9339 * they do not support {@link #value values}.
9341 * @param {string} value New value
9343 * @return {OO.ui.Widget} The widget, for chaining
9345 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
9346 if ( !this.useInputTag
) {
9347 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
9355 OO
.ui
.ButtonInputWidget
.prototype.getInputId = function () {
9356 // Disable generating `<label>` elements for buttons. One would very rarely need additional
9357 // label for a button, and it's already a big clickable target, and it causes
9358 // unexpected rendering.
9363 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
9364 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
9365 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
9366 * alignment. For more information, please see the [OOUI documentation on MediaWiki][1].
9368 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9371 * // An example of selected, unselected, and disabled checkbox inputs.
9372 * var checkbox1 = new OO.ui.CheckboxInputWidget( {
9376 * checkbox2 = new OO.ui.CheckboxInputWidget( {
9379 * checkbox3 = new OO.ui.CheckboxInputWidget( {
9383 * // Create a fieldset layout with fields for each checkbox.
9384 * fieldset = new OO.ui.FieldsetLayout( {
9385 * label: 'Checkboxes'
9387 * fieldset.addItems( [
9388 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
9389 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
9390 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
9392 * $( document.body ).append( fieldset.$element );
9394 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9397 * @extends OO.ui.InputWidget
9400 * @param {Object} [config] Configuration options
9401 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is
9404 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
9405 // Configuration initialization
9406 config
= config
|| {};
9408 // Parent constructor
9409 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
9412 this.checkIcon
= new OO
.ui
.IconWidget( {
9414 classes
: [ 'oo-ui-checkboxInputWidget-checkIcon' ]
9419 .addClass( 'oo-ui-checkboxInputWidget' )
9420 // Required for pretty styling in WikimediaUI theme
9421 .append( this.checkIcon
.$element
);
9422 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
9427 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
9429 /* Static Properties */
9435 OO
.ui
.CheckboxInputWidget
.static.tagName
= 'span';
9437 /* Static Methods */
9442 OO
.ui
.CheckboxInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9443 var state
= OO
.ui
.CheckboxInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9444 state
.checked
= config
.$input
.prop( 'checked' );
9454 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
9455 return $( '<input>' ).attr( 'type', 'checkbox' );
9461 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
9463 if ( !this.isDisabled() ) {
9464 // Allow the stack to clear so the value will be updated
9465 setTimeout( function () {
9466 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
9472 * Set selection state of this checkbox.
9474 * @param {boolean} state `true` for selected
9476 * @return {OO.ui.Widget} The widget, for chaining
9478 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
9480 if ( this.selected
!== state
) {
9481 this.selected
= state
;
9482 this.$input
.prop( 'checked', this.selected
);
9483 this.emit( 'change', this.selected
);
9485 // The first time that the selection state is set (probably while constructing the widget),
9486 // remember it in defaultSelected. This property can be later used to check whether
9487 // the selection state of the input has been changed since it was created.
9488 if ( this.defaultSelected
=== undefined ) {
9489 this.defaultSelected
= this.selected
;
9490 this.$input
[ 0 ].defaultChecked
= this.defaultSelected
;
9496 * Check if this checkbox is selected.
9498 * @return {boolean} Checkbox is selected
9500 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
9501 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
9502 // it, and we won't know unless they're kind enough to trigger a 'change' event.
9503 var selected
= this.$input
.prop( 'checked' );
9504 if ( this.selected
!== selected
) {
9505 this.setSelected( selected
);
9507 return this.selected
;
9513 OO
.ui
.CheckboxInputWidget
.prototype.simulateLabelClick = function () {
9514 if ( !this.isDisabled() ) {
9515 this.$handle
.trigger( 'click' );
9523 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
9524 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
9525 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
9526 this.setSelected( state
.checked
);
9531 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
9532 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the
9533 * value of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9534 * more information about input widgets.
9536 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
9537 * are no options. If no `value` configuration option is provided, the first option is selected.
9538 * If you need a state representing no value (no option being selected), use a DropdownWidget.
9540 * This and OO.ui.RadioSelectInputWidget support similar configuration options.
9543 * // A DropdownInputWidget with three options.
9544 * var dropdownInput = new OO.ui.DropdownInputWidget( {
9546 * { data: 'a', label: 'First' },
9547 * { data: 'b', label: 'Second', disabled: true },
9548 * { optgroup: 'Group label' },
9549 * { data: 'c', label: 'First sub-item)' }
9552 * $( document.body ).append( dropdownInput.$element );
9554 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9557 * @extends OO.ui.InputWidget
9560 * @param {Object} [config] Configuration options
9561 * @cfg {Object[]} [options=[]] Array of menu options in the format described above.
9562 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
9563 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful
9564 * in cases where the expanded menu is larger than its containing `<div>`. The specified overlay
9565 * layer is usually on top of the containing `<div>` and has a larger area. By default, the menu
9566 * uses relative positioning.
9567 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
9569 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
9570 // Configuration initialization
9571 config
= config
|| {};
9573 // Properties (must be done before parent constructor which calls #setDisabled)
9574 this.dropdownWidget
= new OO
.ui
.DropdownWidget( $.extend(
9576 $overlay
: config
.$overlay
9580 // Set up the options before parent constructor, which uses them to validate config.value.
9581 // Use this instead of setOptions() because this.$input is not set up yet.
9582 this.setOptionsData( config
.options
|| [] );
9584 // Parent constructor
9585 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
9588 this.dropdownWidget
.getMenu().connect( this, {
9589 select
: 'onMenuSelect'
9594 .addClass( 'oo-ui-dropdownInputWidget' )
9595 .append( this.dropdownWidget
.$element
);
9596 this.setTabIndexedElement( this.dropdownWidget
.$tabIndexed
);
9597 this.setTitledElement( this.dropdownWidget
.$handle
);
9602 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
9610 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
9611 return $( '<select>' );
9615 * Handles menu select events.
9618 * @param {OO.ui.MenuOptionWidget|null} item Selected menu item
9620 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
9621 this.setValue( item
? item
.getData() : '' );
9627 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
9629 value
= this.cleanUpValue( value
);
9630 // Only allow setting values that are actually present in the dropdown
9631 selected
= this.dropdownWidget
.getMenu().findItemFromData( value
) ||
9632 this.dropdownWidget
.getMenu().findFirstSelectableItem();
9633 this.dropdownWidget
.getMenu().selectItem( selected
);
9634 value
= selected
? selected
.getData() : '';
9635 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
9636 if ( this.optionsDirty
) {
9637 // We reached this from the constructor or from #setOptions.
9638 // We have to update the <select> element.
9639 this.updateOptionsInterface();
9647 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
9648 this.dropdownWidget
.setDisabled( state
);
9649 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9654 * Set the options available for this input.
9656 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9658 * @return {OO.ui.Widget} The widget, for chaining
9660 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
9661 var value
= this.getValue();
9663 this.setOptionsData( options
);
9665 // Re-set the value to update the visible interface (DropdownWidget and <select>).
9666 // In case the previous value is no longer an available option, select the first valid one.
9667 this.setValue( value
);
9673 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
9675 * This method may be called before the parent constructor, so various properties may not be
9678 * @param {Object[]} options Array of menu options (see #constructor for details).
9681 OO
.ui
.DropdownInputWidget
.prototype.setOptionsData = function ( options
) {
9682 var optionWidgets
, optIndex
, opt
, previousOptgroup
, optionWidget
, optValue
,
9685 this.optionsDirty
= true;
9687 // Go through all the supplied option configs and create either
9688 // MenuSectionOption or MenuOption widgets from each.
9690 for ( optIndex
= 0; optIndex
< options
.length
; optIndex
++ ) {
9691 opt
= options
[ optIndex
];
9693 if ( opt
.optgroup
!== undefined ) {
9694 // Create a <optgroup> menu item.
9695 optionWidget
= widget
.createMenuSectionOptionWidget( opt
.optgroup
);
9696 previousOptgroup
= optionWidget
;
9699 // Create a normal <option> menu item.
9700 optValue
= widget
.cleanUpValue( opt
.data
);
9701 optionWidget
= widget
.createMenuOptionWidget(
9703 opt
.label
!== undefined ? opt
.label
: optValue
9707 // Disable the menu option if it is itself disabled or if its parent optgroup is disabled.
9709 opt
.disabled
!== undefined ||
9710 previousOptgroup
instanceof OO
.ui
.MenuSectionOptionWidget
&&
9711 previousOptgroup
.isDisabled()
9713 optionWidget
.setDisabled( true );
9716 optionWidgets
.push( optionWidget
);
9719 this.dropdownWidget
.getMenu().clearItems().addItems( optionWidgets
);
9723 * Create a menu option widget.
9726 * @param {string} data Item data
9727 * @param {string} label Item label
9728 * @return {OO.ui.MenuOptionWidget} Option widget
9730 OO
.ui
.DropdownInputWidget
.prototype.createMenuOptionWidget = function ( data
, label
) {
9731 return new OO
.ui
.MenuOptionWidget( {
9738 * Create a menu section option widget.
9741 * @param {string} label Section item label
9742 * @return {OO.ui.MenuSectionOptionWidget} Menu section option widget
9744 OO
.ui
.DropdownInputWidget
.prototype.createMenuSectionOptionWidget = function ( label
) {
9745 return new OO
.ui
.MenuSectionOptionWidget( {
9751 * Update the user-visible interface to match the internal list of options and value.
9753 * This method must only be called after the parent constructor.
9757 OO
.ui
.DropdownInputWidget
.prototype.updateOptionsInterface = function () {
9759 $optionsContainer
= this.$input
,
9760 defaultValue
= this.defaultValue
,
9763 this.$input
.empty();
9765 this.dropdownWidget
.getMenu().getItems().forEach( function ( optionWidget
) {
9768 if ( !( optionWidget
instanceof OO
.ui
.MenuSectionOptionWidget
) ) {
9769 $optionNode
= $( '<option>' )
9770 .attr( 'value', optionWidget
.getData() )
9771 .text( optionWidget
.getLabel() );
9773 // Remember original selection state. This property can be later used to check whether
9774 // the selection state of the input has been changed since it was created.
9775 $optionNode
[ 0 ].defaultSelected
= ( optionWidget
.getData() === defaultValue
);
9777 $optionsContainer
.append( $optionNode
);
9779 $optionNode
= $( '<optgroup>' )
9780 .attr( 'label', optionWidget
.getLabel() );
9781 widget
.$input
.append( $optionNode
);
9782 $optionsContainer
= $optionNode
;
9785 // Disable the option or optgroup if required.
9786 if ( optionWidget
.isDisabled() ) {
9787 $optionNode
.prop( 'disabled', true );
9791 this.optionsDirty
= false;
9797 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
9798 this.dropdownWidget
.focus();
9805 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
9806 this.dropdownWidget
.blur();
9811 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
9812 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
9813 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
9814 * please see the [OOUI documentation on MediaWiki][1].
9816 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9819 * // An example of selected, unselected, and disabled radio inputs
9820 * var radio1 = new OO.ui.RadioInputWidget( {
9824 * var radio2 = new OO.ui.RadioInputWidget( {
9827 * var radio3 = new OO.ui.RadioInputWidget( {
9831 * // Create a fieldset layout with fields for each radio button.
9832 * var fieldset = new OO.ui.FieldsetLayout( {
9833 * label: 'Radio inputs'
9835 * fieldset.addItems( [
9836 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
9837 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
9838 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
9840 * $( document.body ).append( fieldset.$element );
9842 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9845 * @extends OO.ui.InputWidget
9848 * @param {Object} [config] Configuration options
9849 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button
9852 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
9853 // Configuration initialization
9854 config
= config
|| {};
9856 // Parent constructor
9857 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
9861 .addClass( 'oo-ui-radioInputWidget' )
9862 // Required for pretty styling in WikimediaUI theme
9863 .append( $( '<span>' ) );
9864 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
9869 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
9871 /* Static Properties */
9877 OO
.ui
.RadioInputWidget
.static.tagName
= 'span';
9879 /* Static Methods */
9884 OO
.ui
.RadioInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9885 var state
= OO
.ui
.RadioInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9886 state
.checked
= config
.$input
.prop( 'checked' );
9896 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
9897 return $( '<input>' ).attr( 'type', 'radio' );
9903 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
9904 // RadioInputWidget doesn't track its state.
9908 * Set selection state of this radio button.
9910 * @param {boolean} state `true` for selected
9912 * @return {OO.ui.Widget} The widget, for chaining
9914 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
9915 // RadioInputWidget doesn't track its state.
9916 this.$input
.prop( 'checked', state
);
9917 // The first time that the selection state is set (probably while constructing the widget),
9918 // remember it in defaultSelected. This property can be later used to check whether
9919 // the selection state of the input has been changed since it was created.
9920 if ( this.defaultSelected
=== undefined ) {
9921 this.defaultSelected
= state
;
9922 this.$input
[ 0 ].defaultChecked
= this.defaultSelected
;
9928 * Check if this radio button is selected.
9930 * @return {boolean} Radio is selected
9932 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
9933 return this.$input
.prop( 'checked' );
9939 OO
.ui
.RadioInputWidget
.prototype.simulateLabelClick = function () {
9940 if ( !this.isDisabled() ) {
9941 this.$input
.trigger( 'click' );
9949 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
9950 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
9951 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
9952 this.setSelected( state
.checked
);
9957 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be
9958 * used within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with
9959 * the value of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9960 * more information about input widgets.
9962 * This and OO.ui.DropdownInputWidget support similar configuration options.
9965 * // A RadioSelectInputWidget with three options
9966 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
9968 * { data: 'a', label: 'First' },
9969 * { data: 'b', label: 'Second'},
9970 * { data: 'c', label: 'Third' }
9973 * $( document.body ).append( radioSelectInput.$element );
9975 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9978 * @extends OO.ui.InputWidget
9981 * @param {Object} [config] Configuration options
9982 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9984 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
9985 // Configuration initialization
9986 config
= config
|| {};
9988 // Properties (must be done before parent constructor which calls #setDisabled)
9989 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
9990 // Set up the options before parent constructor, which uses them to validate config.value.
9991 // Use this instead of setOptions() because this.$input is not set up yet
9992 this.setOptionsData( config
.options
|| [] );
9994 // Parent constructor
9995 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
9998 this.radioSelectWidget
.connect( this, {
9999 select
: 'onMenuSelect'
10004 .addClass( 'oo-ui-radioSelectInputWidget' )
10005 .append( this.radioSelectWidget
.$element
);
10006 this.setTabIndexedElement( this.radioSelectWidget
.$tabIndexed
);
10011 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
10013 /* Static Methods */
10018 OO
.ui
.RadioSelectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
10019 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
10020 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
10027 OO
.ui
.RadioSelectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
10028 config
= OO
.ui
.RadioSelectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
10029 // Cannot reuse the `<input type=radio>` set
10030 delete config
.$input
;
10040 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
10041 // Use this instead of <input type="hidden">, because hidden inputs do not have separate
10042 // 'value' and 'defaultValue' properties, and InputWidget wants to handle 'defaultValue'.
10043 return $( '<input>' ).addClass( 'oo-ui-element-hidden' );
10047 * Handles menu select events.
10050 * @param {OO.ui.RadioOptionWidget} item Selected menu item
10052 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
10053 this.setValue( item
.getData() );
10059 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
10061 value
= this.cleanUpValue( value
);
10062 // Only allow setting values that are actually present in the dropdown
10063 selected
= this.radioSelectWidget
.findItemFromData( value
) ||
10064 this.radioSelectWidget
.findFirstSelectableItem();
10065 this.radioSelectWidget
.selectItem( selected
);
10066 value
= selected
? selected
.getData() : '';
10067 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
10074 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
10075 this.radioSelectWidget
.setDisabled( state
);
10076 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
10081 * Set the options available for this input.
10083 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10085 * @return {OO.ui.Widget} The widget, for chaining
10087 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
10088 var value
= this.getValue();
10090 this.setOptionsData( options
);
10092 // Re-set the value to update the visible interface (RadioSelectWidget).
10093 // In case the previous value is no longer an available option, select the first valid one.
10094 this.setValue( value
);
10100 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
10102 * This method may be called before the parent constructor, so various properties may not be
10105 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10108 OO
.ui
.RadioSelectInputWidget
.prototype.setOptionsData = function ( options
) {
10111 this.radioSelectWidget
10113 .addItems( options
.map( function ( opt
) {
10114 var optValue
= widget
.cleanUpValue( opt
.data
);
10115 return new OO
.ui
.RadioOptionWidget( {
10117 label
: opt
.label
!== undefined ? opt
.label
: optValue
10125 OO
.ui
.RadioSelectInputWidget
.prototype.focus = function () {
10126 this.radioSelectWidget
.focus();
10133 OO
.ui
.RadioSelectInputWidget
.prototype.blur = function () {
10134 this.radioSelectWidget
.blur();
10139 * CheckboxMultiselectInputWidget is a
10140 * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
10141 * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
10142 * HTML `<input type=checkbox>` tags. Please see the [OOUI documentation on MediaWiki][1] for
10143 * more information about input widgets.
10146 * // A CheckboxMultiselectInputWidget with three options.
10147 * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
10149 * { data: 'a', label: 'First' },
10150 * { data: 'b', label: 'Second' },
10151 * { data: 'c', label: 'Third' }
10154 * $( document.body ).append( multiselectInput.$element );
10156 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
10159 * @extends OO.ui.InputWidget
10162 * @param {Object} [config] Configuration options
10163 * @cfg {Object[]} [options=[]] Array of menu options in the format
10164 * `{ data: …, label: …, disabled: … }`
10166 OO
.ui
.CheckboxMultiselectInputWidget
= function OoUiCheckboxMultiselectInputWidget( config
) {
10167 // Configuration initialization
10168 config
= config
|| {};
10170 // Properties (must be done before parent constructor which calls #setDisabled)
10171 this.checkboxMultiselectWidget
= new OO
.ui
.CheckboxMultiselectWidget();
10172 // Must be set before the #setOptionsData call below
10173 this.inputName
= config
.name
;
10174 // Set up the options before parent constructor, which uses them to validate config.value.
10175 // Use this instead of setOptions() because this.$input is not set up yet
10176 this.setOptionsData( config
.options
|| [] );
10178 // Parent constructor
10179 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.call( this, config
);
10182 this.checkboxMultiselectWidget
.connect( this, {
10183 select
: 'onCheckboxesSelect'
10188 .addClass( 'oo-ui-checkboxMultiselectInputWidget' )
10189 .append( this.checkboxMultiselectWidget
.$element
);
10190 // We don't use this.$input, but rather the CheckboxInputWidgets inside each option
10191 this.$input
.detach();
10196 OO
.inheritClass( OO
.ui
.CheckboxMultiselectInputWidget
, OO
.ui
.InputWidget
);
10198 /* Static Methods */
10203 OO
.ui
.CheckboxMultiselectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
10204 var state
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.gatherPreInfuseState(
10207 state
.value
= $( node
).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
10208 .toArray().map( function ( el
) { return el
.value
; } );
10215 OO
.ui
.CheckboxMultiselectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
10216 config
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
10217 // Cannot reuse the `<input type=checkbox>` set
10218 delete config
.$input
;
10228 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getInputElement = function () {
10230 return $( '<unused>' );
10234 * Handles CheckboxMultiselectWidget select events.
10238 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.onCheckboxesSelect = function () {
10239 this.setValue( this.checkboxMultiselectWidget
.findSelectedItemsData() );
10245 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getValue = function () {
10246 var value
= this.$element
.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
10247 .toArray().map( function ( el
) { return el
.value
; } );
10248 if ( this.value
!== value
) {
10249 this.setValue( value
);
10257 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setValue = function ( value
) {
10258 value
= this.cleanUpValue( value
);
10259 this.checkboxMultiselectWidget
.selectItemsByData( value
);
10260 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setValue
.call( this, value
);
10261 if ( this.optionsDirty
) {
10262 // We reached this from the constructor or from #setOptions.
10263 // We have to update the <select> element.
10264 this.updateOptionsInterface();
10270 * Clean up incoming value.
10272 * @param {string[]} value Original value
10273 * @return {string[]} Cleaned up value
10275 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.cleanUpValue = function ( value
) {
10276 var i
, singleValue
,
10278 if ( !Array
.isArray( value
) ) {
10281 for ( i
= 0; i
< value
.length
; i
++ ) {
10282 singleValue
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
10283 .call( this, value
[ i
] );
10284 // Remove options that we don't have here
10285 if ( !this.checkboxMultiselectWidget
.findItemFromData( singleValue
) ) {
10288 cleanValue
.push( singleValue
);
10296 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setDisabled = function ( state
) {
10297 this.checkboxMultiselectWidget
.setDisabled( state
);
10298 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
10303 * Set the options available for this input.
10305 * @param {Object[]} options Array of menu options in the format
10306 * `{ data: …, label: …, disabled: … }`
10308 * @return {OO.ui.Widget} The widget, for chaining
10310 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setOptions = function ( options
) {
10311 var value
= this.getValue();
10313 this.setOptionsData( options
);
10315 // Re-set the value to update the visible interface (CheckboxMultiselectWidget).
10316 // This will also get rid of any stale options that we just removed.
10317 this.setValue( value
);
10323 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
10325 * This method may be called before the parent constructor, so various properties may not be
10328 * @param {Object[]} options Array of menu options in the format
10329 * `{ data: …, label: … }`
10332 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setOptionsData = function ( options
) {
10335 this.optionsDirty
= true;
10337 this.checkboxMultiselectWidget
10339 .addItems( options
.map( function ( opt
) {
10340 var optValue
, item
, optDisabled
;
10341 optValue
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
10342 .call( widget
, opt
.data
);
10343 optDisabled
= opt
.disabled
!== undefined ? opt
.disabled
: false;
10344 item
= new OO
.ui
.CheckboxMultioptionWidget( {
10346 label
: opt
.label
!== undefined ? opt
.label
: optValue
,
10347 disabled
: optDisabled
10349 // Set the 'name' and 'value' for form submission
10350 item
.checkbox
.$input
.attr( 'name', widget
.inputName
);
10351 item
.checkbox
.setValue( optValue
);
10357 * Update the user-visible interface to match the internal list of options and value.
10359 * This method must only be called after the parent constructor.
10363 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.updateOptionsInterface = function () {
10364 var defaultValue
= this.defaultValue
;
10366 this.checkboxMultiselectWidget
.getItems().forEach( function ( item
) {
10367 // Remember original selection state. This property can be later used to check whether
10368 // the selection state of the input has been changed since it was created.
10369 var isDefault
= defaultValue
.indexOf( item
.getData() ) !== -1;
10370 item
.checkbox
.defaultSelected
= isDefault
;
10371 item
.checkbox
.$input
[ 0 ].defaultChecked
= isDefault
;
10374 this.optionsDirty
= false;
10380 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.focus = function () {
10381 this.checkboxMultiselectWidget
.focus();
10386 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
10387 * size of the field as well as its presentation. In addition, these widgets can be configured
10388 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an
10389 * optional validation-pattern (used to determine if an input value is valid or not) and an input
10390 * filter, which modifies incoming values rather than validating them.
10391 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
10393 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
10396 * // A TextInputWidget.
10397 * var textInput = new OO.ui.TextInputWidget( {
10398 * value: 'Text input'
10400 * $( document.body ).append( textInput.$element );
10402 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
10405 * @extends OO.ui.InputWidget
10406 * @mixins OO.ui.mixin.IconElement
10407 * @mixins OO.ui.mixin.IndicatorElement
10408 * @mixins OO.ui.mixin.PendingElement
10409 * @mixins OO.ui.mixin.LabelElement
10410 * @mixins OO.ui.mixin.FlaggedElement
10413 * @param {Object} [config] Configuration options
10414 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password'
10415 * 'email', 'url' or 'number'.
10416 * @cfg {string} [placeholder] Placeholder text
10417 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
10418 * instruct the browser to focus this widget.
10419 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
10420 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
10422 * For unfortunate historical reasons, this counts the number of UTF-16 code units rather than
10423 * Unicode codepoints, which means that codepoints outside the Basic Multilingual Plane (e.g.
10424 * many emojis) count as 2 characters each.
10425 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
10426 * the value or placeholder text: `'before'` or `'after'`
10427 * @cfg {boolean} [required=false] Mark the field as required with `true`. Implies `indicator:
10428 * 'required'`. Note that `false` & setting `indicator: 'required' will result in no indicator
10430 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
10431 * @cfg {boolean} [spellcheck] Should the browser support spellcheck for this field (`undefined`
10432 * means leaving it up to the browser).
10433 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
10434 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
10435 * (the value must contain only numbers); when RegExp, a regular expression that must match the
10436 * value for it to be considered valid; when Function, a function receiving the value as parameter
10437 * that must return true, or promise resolving to true, for it to be considered valid.
10439 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
10440 // Configuration initialization
10441 config
= $.extend( {
10443 labelPosition
: 'after'
10446 // Parent constructor
10447 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
10449 // Mixin constructors
10450 OO
.ui
.mixin
.IconElement
.call( this, config
);
10451 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
10452 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( { $pending
: this.$input
}, config
) );
10453 OO
.ui
.mixin
.LabelElement
.call( this, config
);
10454 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
10457 this.type
= this.getSaneType( config
);
10458 this.readOnly
= false;
10459 this.required
= false;
10460 this.validate
= null;
10461 this.scrollWidth
= null;
10463 this.setValidation( config
.validate
);
10464 this.setLabelPosition( config
.labelPosition
);
10468 keypress
: this.onKeyPress
.bind( this ),
10469 blur
: this.onBlur
.bind( this ),
10470 focus
: this.onFocus
.bind( this )
10472 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
10473 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
10474 this.on( 'labelChange', this.updatePosition
.bind( this ) );
10475 this.on( 'change', OO
.ui
.debounce( this.onDebouncedChange
.bind( this ), 250 ) );
10479 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
10480 .append( this.$icon
, this.$indicator
);
10481 this.setReadOnly( !!config
.readOnly
);
10482 this.setRequired( !!config
.required
);
10483 if ( config
.placeholder
!== undefined ) {
10484 this.$input
.attr( 'placeholder', config
.placeholder
);
10486 if ( config
.maxLength
!== undefined ) {
10487 this.$input
.attr( 'maxlength', config
.maxLength
);
10489 if ( config
.autofocus
) {
10490 this.$input
.attr( 'autofocus', 'autofocus' );
10492 if ( config
.autocomplete
=== false ) {
10493 this.$input
.attr( 'autocomplete', 'off' );
10494 // Turning off autocompletion also disables "form caching" when the user navigates to a
10495 // different page and then clicks "Back". Re-enable it when leaving.
10496 // Borrowed from jQuery UI.
10498 beforeunload: function () {
10499 this.$input
.removeAttr( 'autocomplete' );
10501 pageshow: function () {
10502 // Browsers don't seem to actually fire this event on "Back", they instead just
10503 // reload the whole page... it shouldn't hurt, though.
10504 this.$input
.attr( 'autocomplete', 'off' );
10508 if ( config
.spellcheck
!== undefined ) {
10509 this.$input
.attr( 'spellcheck', config
.spellcheck
? 'true' : 'false' );
10511 if ( this.label
) {
10512 this.isWaitingToBeAttached
= true;
10513 this.installParentChangeDetector();
10519 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
10520 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
10521 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
10522 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
10523 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
10524 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.FlaggedElement
);
10526 /* Static Properties */
10528 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
10536 * An `enter` event is emitted when the user presses Enter key inside the text box.
10544 * Handle icon mouse down events.
10547 * @param {jQuery.Event} e Mouse down event
10548 * @return {undefined/boolean} False to prevent default if event is handled
10550 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
10551 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
10558 * Handle indicator mouse down events.
10561 * @param {jQuery.Event} e Mouse down event
10562 * @return {undefined/boolean} False to prevent default if event is handled
10564 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
10565 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
10572 * Handle key press events.
10575 * @param {jQuery.Event} e Key press event
10576 * @fires enter If Enter key is pressed
10578 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
10579 if ( e
.which
=== OO
.ui
.Keys
.ENTER
) {
10580 this.emit( 'enter', e
);
10585 * Handle blur events.
10588 * @param {jQuery.Event} e Blur event
10590 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
10591 this.setValidityFlag();
10595 * Handle focus events.
10598 * @param {jQuery.Event} e Focus event
10600 OO
.ui
.TextInputWidget
.prototype.onFocus = function () {
10601 if ( this.isWaitingToBeAttached
) {
10602 // If we've received focus, then we must be attached to the document, and if
10603 // isWaitingToBeAttached is still true, that means the handler never fired. Fire it now.
10604 this.onElementAttach();
10606 this.setValidityFlag( true );
10610 * Handle element attach events.
10613 * @param {jQuery.Event} e Element attach event
10615 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
10616 this.isWaitingToBeAttached
= false;
10617 // Any previously calculated size is now probably invalid if we reattached elsewhere
10618 this.valCache
= null;
10619 this.positionLabel();
10623 * Handle debounced change events.
10625 * @param {string} value
10628 OO
.ui
.TextInputWidget
.prototype.onDebouncedChange = function () {
10629 this.setValidityFlag();
10633 * Check if the input is {@link #readOnly read-only}.
10635 * @return {boolean}
10637 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
10638 return this.readOnly
;
10642 * Set the {@link #readOnly read-only} state of the input.
10644 * @param {boolean} state Make input read-only
10646 * @return {OO.ui.Widget} The widget, for chaining
10648 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
10649 this.readOnly
= !!state
;
10650 this.$input
.prop( 'readOnly', this.readOnly
);
10655 * Check if the input is {@link #required required}.
10657 * @return {boolean}
10659 OO
.ui
.TextInputWidget
.prototype.isRequired = function () {
10660 return this.required
;
10664 * Set the {@link #required required} state of the input.
10666 * @param {boolean} state Make input required
10668 * @return {OO.ui.Widget} The widget, for chaining
10670 OO
.ui
.TextInputWidget
.prototype.setRequired = function ( state
) {
10671 this.required
= !!state
;
10672 if ( this.required
) {
10674 .prop( 'required', true )
10675 .attr( 'aria-required', 'true' );
10676 if ( this.getIndicator() === null ) {
10677 this.setIndicator( 'required' );
10681 .prop( 'required', false )
10682 .removeAttr( 'aria-required' );
10683 if ( this.getIndicator() === 'required' ) {
10684 this.setIndicator( null );
10691 * Support function for making #onElementAttach work across browsers.
10693 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
10694 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
10696 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
10697 * first time that the element gets attached to the documented.
10699 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
10700 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
10701 MutationObserver
= window
.MutationObserver
||
10702 window
.WebKitMutationObserver
||
10703 window
.MozMutationObserver
,
10706 if ( MutationObserver
) {
10707 // The new way. If only it wasn't so ugly.
10709 if ( this.isElementAttached() ) {
10710 // Widget is attached already, do nothing. This breaks the functionality of this
10711 // function when the widget is detached and reattached. Alas, doing this correctly with
10712 // MutationObserver would require observation of the whole document, which would hurt
10713 // performance of other, more important code.
10717 // Find topmost node in the tree
10718 topmostNode
= this.$element
[ 0 ];
10719 while ( topmostNode
.parentNode
) {
10720 topmostNode
= topmostNode
.parentNode
;
10723 // We have no way to detect the $element being attached somewhere without observing the
10724 // entire DOM with subtree modifications, which would hurt performance. So we cheat: we hook
10725 // to the parent node of $element, and instead detect when $element is removed from it (and
10726 // thus probably attached somewhere else). If there is no parent, we create a "fake" one. If
10727 // it doesn't get attached, we end up back here and create the parent.
10728 mutationObserver
= new MutationObserver( function ( mutations
) {
10729 var i
, j
, removedNodes
;
10730 for ( i
= 0; i
< mutations
.length
; i
++ ) {
10731 removedNodes
= mutations
[ i
].removedNodes
;
10732 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
10733 if ( removedNodes
[ j
] === topmostNode
) {
10734 setTimeout( onRemove
, 0 );
10741 onRemove = function () {
10742 // If the node was attached somewhere else, report it
10743 if ( widget
.isElementAttached() ) {
10744 widget
.onElementAttach();
10746 mutationObserver
.disconnect();
10747 widget
.installParentChangeDetector();
10750 // Create a fake parent and observe it
10751 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
10752 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
10754 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
10755 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
10756 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
10764 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
10765 if ( this.getSaneType( config
) === 'number' ) {
10766 return $( '<input>' )
10767 .attr( 'step', 'any' )
10768 .attr( 'type', 'number' );
10770 return $( '<input>' ).attr( 'type', this.getSaneType( config
) );
10775 * Get sanitized value for 'type' for given config.
10777 * @param {Object} config Configuration options
10778 * @return {string|null}
10781 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
10782 var allowedTypes
= [
10789 return allowedTypes
.indexOf( config
.type
) !== -1 ? config
.type
: 'text';
10793 * Focus the input and select a specified range within the text.
10795 * @param {number} from Select from offset
10796 * @param {number} [to] Select to offset, defaults to from
10798 * @return {OO.ui.Widget} The widget, for chaining
10800 OO
.ui
.TextInputWidget
.prototype.selectRange = function ( from, to
) {
10801 var isBackwards
, start
, end
,
10802 input
= this.$input
[ 0 ];
10806 isBackwards
= to
< from;
10807 start
= isBackwards
? to
: from;
10808 end
= isBackwards
? from : to
;
10813 input
.setSelectionRange( start
, end
, isBackwards
? 'backward' : 'forward' );
10815 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
10816 // Rather than expensively check if the input is attached every time, just check
10817 // if it was the cause of an error being thrown. If not, rethrow the error.
10818 if ( this.getElementDocument().body
.contains( input
) ) {
10826 * Get an object describing the current selection range in a directional manner
10828 * @return {Object} Object containing 'from' and 'to' offsets
10830 OO
.ui
.TextInputWidget
.prototype.getRange = function () {
10831 var input
= this.$input
[ 0 ],
10832 start
= input
.selectionStart
,
10833 end
= input
.selectionEnd
,
10834 isBackwards
= input
.selectionDirection
=== 'backward';
10837 from: isBackwards
? end
: start
,
10838 to
: isBackwards
? start
: end
10843 * Get the length of the text input value.
10845 * This could differ from the length of #getValue if the
10846 * value gets filtered
10848 * @return {number} Input length
10850 OO
.ui
.TextInputWidget
.prototype.getInputLength = function () {
10851 return this.$input
[ 0 ].value
.length
;
10855 * Focus the input and select the entire text.
10858 * @return {OO.ui.Widget} The widget, for chaining
10860 OO
.ui
.TextInputWidget
.prototype.select = function () {
10861 return this.selectRange( 0, this.getInputLength() );
10865 * Focus the input and move the cursor to the start.
10868 * @return {OO.ui.Widget} The widget, for chaining
10870 OO
.ui
.TextInputWidget
.prototype.moveCursorToStart = function () {
10871 return this.selectRange( 0 );
10875 * Focus the input and move the cursor to the end.
10878 * @return {OO.ui.Widget} The widget, for chaining
10880 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
10881 return this.selectRange( this.getInputLength() );
10885 * Insert new content into the input.
10887 * @param {string} content Content to be inserted
10889 * @return {OO.ui.Widget} The widget, for chaining
10891 OO
.ui
.TextInputWidget
.prototype.insertContent = function ( content
) {
10893 range
= this.getRange(),
10894 value
= this.getValue();
10896 start
= Math
.min( range
.from, range
.to
);
10897 end
= Math
.max( range
.from, range
.to
);
10899 this.setValue( value
.slice( 0, start
) + content
+ value
.slice( end
) );
10900 this.selectRange( start
+ content
.length
);
10905 * Insert new content either side of a selection.
10907 * @param {string} pre Content to be inserted before the selection
10908 * @param {string} post Content to be inserted after the selection
10910 * @return {OO.ui.Widget} The widget, for chaining
10912 OO
.ui
.TextInputWidget
.prototype.encapsulateContent = function ( pre
, post
) {
10914 range
= this.getRange(),
10915 offset
= pre
.length
;
10917 start
= Math
.min( range
.from, range
.to
);
10918 end
= Math
.max( range
.from, range
.to
);
10920 this.selectRange( start
).insertContent( pre
);
10921 this.selectRange( offset
+ end
).insertContent( post
);
10923 this.selectRange( offset
+ start
, offset
+ end
);
10928 * Set the validation pattern.
10930 * The validation pattern is either a regular expression, a function, or the symbolic name of a
10931 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
10932 * value must contain only numbers).
10934 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
10935 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
10937 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
10938 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
10939 this.validate
= validate
;
10941 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
10946 * Sets the 'invalid' flag appropriately.
10948 * @param {boolean} [isValid] Optionally override validation result
10950 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
10952 setFlag = function ( valid
) {
10954 widget
.$input
.attr( 'aria-invalid', 'true' );
10956 widget
.$input
.removeAttr( 'aria-invalid' );
10958 widget
.setFlags( { invalid
: !valid
} );
10961 if ( isValid
!== undefined ) {
10962 setFlag( isValid
);
10964 this.getValidity().then( function () {
10973 * Get the validity of current value.
10975 * This method returns a promise that resolves if the value is valid and rejects if
10976 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
10978 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
10980 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
10983 function rejectOrResolve( valid
) {
10985 return $.Deferred().resolve().promise();
10987 return $.Deferred().reject().promise();
10991 // Check browser validity and reject if it is invalid
10993 this.$input
[ 0 ].checkValidity
!== undefined &&
10994 this.$input
[ 0 ].checkValidity() === false
10996 return rejectOrResolve( false );
10999 // Run our checks if the browser thinks the field is valid
11000 if ( this.validate
instanceof Function
) {
11001 result
= this.validate( this.getValue() );
11002 if ( result
&& typeof result
.promise
=== 'function' ) {
11003 return result
.promise().then( function ( valid
) {
11004 return rejectOrResolve( valid
);
11007 return rejectOrResolve( result
);
11010 return rejectOrResolve( this.getValue().match( this.validate
) );
11015 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
11017 * @param {string} labelPosition Label position, 'before' or 'after'
11019 * @return {OO.ui.Widget} The widget, for chaining
11021 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
11022 this.labelPosition
= labelPosition
;
11023 if ( this.label
) {
11024 // If there is no label and we only change the position, #updatePosition is a no-op,
11025 // but it takes really a lot of work to do nothing.
11026 this.updatePosition();
11032 * Update the position of the inline label.
11034 * This method is called by #setLabelPosition, and can also be called on its own if
11035 * something causes the label to be mispositioned.
11038 * @return {OO.ui.Widget} The widget, for chaining
11040 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
11041 var after
= this.labelPosition
=== 'after';
11044 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
11045 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
11047 this.valCache
= null;
11048 this.scrollWidth
= null;
11049 this.positionLabel();
11055 * Position the label by setting the correct padding on the input.
11059 * @return {OO.ui.Widget} The widget, for chaining
11061 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
11062 var after
, rtl
, property
, newCss
;
11064 if ( this.isWaitingToBeAttached
) {
11065 // #onElementAttach will be called soon, which calls this method
11070 'padding-right': '',
11074 if ( this.label
) {
11075 this.$element
.append( this.$label
);
11077 this.$label
.detach();
11078 // Clear old values if present
11079 this.$input
.css( newCss
);
11083 after
= this.labelPosition
=== 'after';
11084 rtl
= this.$element
.css( 'direction' ) === 'rtl';
11085 property
= after
=== rtl
? 'padding-left' : 'padding-right';
11087 newCss
[ property
] = this.$label
.outerWidth( true ) + ( after
? this.scrollWidth
: 0 );
11088 // We have to clear the padding on the other side, in case the element direction changed
11089 this.$input
.css( newCss
);
11095 * SearchInputWidgets are TextInputWidgets with `type="search"` assigned and feature a
11096 * {@link OO.ui.mixin.IconElement search icon} by default.
11097 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
11099 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#SearchInputWidget
11102 * @extends OO.ui.TextInputWidget
11105 * @param {Object} [config] Configuration options
11107 OO
.ui
.SearchInputWidget
= function OoUiSearchInputWidget( config
) {
11108 config
= $.extend( {
11112 // Parent constructor
11113 OO
.ui
.SearchInputWidget
.parent
.call( this, config
);
11116 this.connect( this, {
11121 this.updateSearchIndicator();
11122 this.connect( this, {
11123 disable
: 'onDisable'
11129 OO
.inheritClass( OO
.ui
.SearchInputWidget
, OO
.ui
.TextInputWidget
);
11137 OO
.ui
.SearchInputWidget
.prototype.getSaneType = function () {
11144 OO
.ui
.SearchInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
11145 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
11146 // Clear the text field
11147 this.setValue( '' );
11154 * Update the 'clear' indicator displayed on type: 'search' text
11155 * fields, hiding it when the field is already empty or when it's not
11158 OO
.ui
.SearchInputWidget
.prototype.updateSearchIndicator = function () {
11159 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
11160 this.setIndicator( null );
11162 this.setIndicator( 'clear' );
11167 * Handle change events.
11171 OO
.ui
.SearchInputWidget
.prototype.onChange = function () {
11172 this.updateSearchIndicator();
11176 * Handle disable events.
11178 * @param {boolean} disabled Element is disabled
11181 OO
.ui
.SearchInputWidget
.prototype.onDisable = function () {
11182 this.updateSearchIndicator();
11188 OO
.ui
.SearchInputWidget
.prototype.setReadOnly = function ( state
) {
11189 OO
.ui
.SearchInputWidget
.parent
.prototype.setReadOnly
.call( this, state
);
11190 this.updateSearchIndicator();
11195 * MultilineTextInputWidgets, like HTML textareas, are featuring customization options to
11196 * configure number of rows visible. In addition, these widgets can be autosized to fit user
11197 * inputs and can show {@link OO.ui.mixin.IconElement icons} and
11198 * {@link OO.ui.mixin.IndicatorElement indicators}.
11199 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
11201 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
11204 * // A MultilineTextInputWidget.
11205 * var multilineTextInput = new OO.ui.MultilineTextInputWidget( {
11206 * value: 'Text input on multiple lines'
11208 * $( 'body' ).append( multilineTextInput.$element );
11210 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#MultilineTextInputWidget
11213 * @extends OO.ui.TextInputWidget
11216 * @param {Object} [config] Configuration options
11217 * @cfg {number} [rows] Number of visible lines in textarea. If used with `autosize`,
11218 * specifies minimum number of rows to display.
11219 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
11220 * Use the #maxRows config to specify a maximum number of displayed rows.
11221 * @cfg {number} [maxRows] Maximum number of rows to display when #autosize is set to true.
11222 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
11224 OO
.ui
.MultilineTextInputWidget
= function OoUiMultilineTextInputWidget( config
) {
11225 config
= $.extend( {
11228 // Parent constructor
11229 OO
.ui
.MultilineTextInputWidget
.parent
.call( this, config
);
11232 this.autosize
= !!config
.autosize
;
11233 this.styleHeight
= null;
11234 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
11235 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
11237 // Clone for resizing
11238 if ( this.autosize
) {
11239 this.$clone
= this.$input
11241 .removeAttr( 'id' )
11242 .removeAttr( 'name' )
11243 .insertAfter( this.$input
)
11244 .attr( 'aria-hidden', 'true' )
11245 .addClass( 'oo-ui-element-hidden' );
11249 this.connect( this, {
11254 if ( config
.rows
) {
11255 this.$input
.attr( 'rows', config
.rows
);
11257 if ( this.autosize
) {
11258 this.$input
.addClass( 'oo-ui-textInputWidget-autosized' );
11259 this.isWaitingToBeAttached
= true;
11260 this.installParentChangeDetector();
11266 OO
.inheritClass( OO
.ui
.MultilineTextInputWidget
, OO
.ui
.TextInputWidget
);
11268 /* Static Methods */
11273 OO
.ui
.MultilineTextInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
11274 var state
= OO
.ui
.MultilineTextInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
11275 state
.scrollTop
= config
.$input
.scrollTop();
11284 OO
.ui
.MultilineTextInputWidget
.prototype.onElementAttach = function () {
11285 OO
.ui
.MultilineTextInputWidget
.parent
.prototype.onElementAttach
.call( this );
11290 * Handle change events.
11294 OO
.ui
.MultilineTextInputWidget
.prototype.onChange = function () {
11301 OO
.ui
.MultilineTextInputWidget
.prototype.updatePosition = function () {
11302 OO
.ui
.MultilineTextInputWidget
.parent
.prototype.updatePosition
.call( this );
11309 * Modify to emit 'enter' on Ctrl/Meta+Enter, instead of plain Enter
11311 OO
.ui
.MultilineTextInputWidget
.prototype.onKeyPress = function ( e
) {
11313 ( e
.which
=== OO
.ui
.Keys
.ENTER
&& ( e
.ctrlKey
|| e
.metaKey
) ) ||
11314 // Some platforms emit keycode 10 for Control+Enter keypress in a textarea
11317 this.emit( 'enter', e
);
11322 * Automatically adjust the size of the text input.
11324 * This only affects multiline inputs that are {@link #autosize autosized}.
11327 * @return {OO.ui.Widget} The widget, for chaining
11330 OO
.ui
.MultilineTextInputWidget
.prototype.adjustSize = function () {
11331 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
,
11332 idealHeight
, newHeight
, scrollWidth
, property
;
11334 if ( this.$input
.val() !== this.valCache
) {
11335 if ( this.autosize
) {
11337 .val( this.$input
.val() )
11338 .attr( 'rows', this.minRows
)
11339 // Set inline height property to 0 to measure scroll height
11340 .css( 'height', 0 );
11342 this.$clone
.removeClass( 'oo-ui-element-hidden' );
11344 this.valCache
= this.$input
.val();
11346 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
11348 // Remove inline height property to measure natural heights
11349 this.$clone
.css( 'height', '' );
11350 innerHeight
= this.$clone
.innerHeight();
11351 outerHeight
= this.$clone
.outerHeight();
11353 // Measure max rows height
11355 .attr( 'rows', this.maxRows
)
11356 .css( 'height', 'auto' )
11358 maxInnerHeight
= this.$clone
.innerHeight();
11360 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
11361 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
11362 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
11363 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
11365 this.$clone
.addClass( 'oo-ui-element-hidden' );
11367 // Only apply inline height when expansion beyond natural height is needed
11368 // Use the difference between the inner and outer height as a buffer
11369 newHeight
= idealHeight
> innerHeight
? idealHeight
+ ( outerHeight
- innerHeight
) : '';
11370 if ( newHeight
!== this.styleHeight
) {
11371 this.$input
.css( 'height', newHeight
);
11372 this.styleHeight
= newHeight
;
11373 this.emit( 'resize' );
11376 scrollWidth
= this.$input
[ 0 ].offsetWidth
- this.$input
[ 0 ].clientWidth
;
11377 if ( scrollWidth
!== this.scrollWidth
) {
11378 property
= this.$element
.css( 'direction' ) === 'rtl' ? 'left' : 'right';
11380 this.$label
.css( { right
: '', left
: '' } );
11381 this.$indicator
.css( { right
: '', left
: '' } );
11383 if ( scrollWidth
) {
11384 this.$indicator
.css( property
, scrollWidth
);
11385 if ( this.labelPosition
=== 'after' ) {
11386 this.$label
.css( property
, scrollWidth
);
11390 this.scrollWidth
= scrollWidth
;
11391 this.positionLabel();
11401 OO
.ui
.MultilineTextInputWidget
.prototype.getInputElement = function () {
11402 return $( '<textarea>' );
11406 * Check if the input automatically adjusts its size.
11408 * @return {boolean}
11410 OO
.ui
.MultilineTextInputWidget
.prototype.isAutosizing = function () {
11411 return !!this.autosize
;
11417 OO
.ui
.MultilineTextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
11418 OO
.ui
.MultilineTextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
11419 if ( state
.scrollTop
!== undefined ) {
11420 this.$input
.scrollTop( state
.scrollTop
);
11425 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
11426 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
11427 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
11429 * - by typing a value in the text input field. If the value exactly matches the value of a menu
11430 * option, that option will appear to be selected.
11431 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
11434 * After the user chooses an option, its `data` will be used as a new value for the widget.
11435 * A `label` also can be specified for each option: if given, it will be shown instead of the
11436 * `data` in the dropdown menu.
11438 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
11440 * For more information about menus and options, please see the
11441 * [OOUI documentation on MediaWiki][1].
11444 * // A ComboBoxInputWidget.
11445 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11446 * value: 'Option 1',
11448 * { data: 'Option 1' },
11449 * { data: 'Option 2' },
11450 * { data: 'Option 3' }
11453 * $( document.body ).append( comboBox.$element );
11456 * // Example: A ComboBoxInputWidget with additional option labels.
11457 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11458 * value: 'Option 1',
11461 * data: 'Option 1',
11462 * label: 'Option One'
11465 * data: 'Option 2',
11466 * label: 'Option Two'
11469 * data: 'Option 3',
11470 * label: 'Option Three'
11474 * $( document.body ).append( comboBox.$element );
11476 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
11479 * @extends OO.ui.TextInputWidget
11482 * @param {Object} [config] Configuration options
11483 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
11484 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu
11486 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful
11487 * in cases where the expanded menu is larger than its containing `<div>`. The specified overlay
11488 * layer is usually on top of the containing `<div>` and has a larger area. By default, the menu
11489 * uses relative positioning.
11490 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11492 OO
.ui
.ComboBoxInputWidget
= function OoUiComboBoxInputWidget( config
) {
11493 // Configuration initialization
11494 config
= $.extend( {
11495 autocomplete
: false
11498 // ComboBoxInputWidget shouldn't support `multiline`
11499 config
.multiline
= false;
11501 // See InputWidget#reusePreInfuseDOM about `config.$input`
11502 if ( config
.$input
) {
11503 config
.$input
.removeAttr( 'list' );
11506 // Parent constructor
11507 OO
.ui
.ComboBoxInputWidget
.parent
.call( this, config
);
11510 this.$overlay
= ( config
.$overlay
=== true ?
11511 OO
.ui
.getDefaultOverlay() : config
.$overlay
) || this.$element
;
11512 this.dropdownButton
= new OO
.ui
.ButtonWidget( {
11513 classes
: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ],
11514 label
: OO
.ui
.msg( 'ooui-combobox-button-label' ),
11516 invisibleLabel
: true,
11517 disabled
: this.disabled
11519 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend(
11523 $floatableContainer
: this.$element
,
11524 disabled
: this.isDisabled()
11530 this.connect( this, {
11531 change
: 'onInputChange',
11532 enter
: 'onInputEnter'
11534 this.dropdownButton
.connect( this, {
11535 click
: 'onDropdownButtonClick'
11537 this.menu
.connect( this, {
11538 choose
: 'onMenuChoose',
11539 add
: 'onMenuItemsChange',
11540 remove
: 'onMenuItemsChange',
11541 toggle
: 'onMenuToggle'
11545 this.$input
.attr( {
11547 'aria-owns': this.menu
.getElementId(),
11548 'aria-autocomplete': 'list'
11550 this.dropdownButton
.$button
.attr( {
11551 'aria-controls': this.menu
.getElementId()
11553 // Do not override options set via config.menu.items
11554 if ( config
.options
!== undefined ) {
11555 this.setOptions( config
.options
);
11557 this.$field
= $( '<div>' )
11558 .addClass( 'oo-ui-comboBoxInputWidget-field' )
11559 .append( this.$input
, this.dropdownButton
.$element
);
11561 .addClass( 'oo-ui-comboBoxInputWidget' )
11562 .append( this.$field
);
11563 this.$overlay
.append( this.menu
.$element
);
11564 this.onMenuItemsChange();
11569 OO
.inheritClass( OO
.ui
.ComboBoxInputWidget
, OO
.ui
.TextInputWidget
);
11574 * Get the combobox's menu.
11576 * @return {OO.ui.MenuSelectWidget} Menu widget
11578 OO
.ui
.ComboBoxInputWidget
.prototype.getMenu = function () {
11583 * Get the combobox's text input widget.
11585 * @return {OO.ui.TextInputWidget} Text input widget
11587 OO
.ui
.ComboBoxInputWidget
.prototype.getInput = function () {
11592 * Handle input change events.
11595 * @param {string} value New value
11597 OO
.ui
.ComboBoxInputWidget
.prototype.onInputChange = function ( value
) {
11598 var match
= this.menu
.findItemFromData( value
);
11600 this.menu
.selectItem( match
);
11601 if ( this.menu
.findHighlightedItem() ) {
11602 this.menu
.highlightItem( match
);
11605 if ( !this.isDisabled() ) {
11606 this.menu
.toggle( true );
11611 * Handle input enter events.
11615 OO
.ui
.ComboBoxInputWidget
.prototype.onInputEnter = function () {
11616 if ( !this.isDisabled() ) {
11617 this.menu
.toggle( false );
11622 * Handle button click events.
11626 OO
.ui
.ComboBoxInputWidget
.prototype.onDropdownButtonClick = function () {
11627 this.menu
.toggle();
11632 * Handle menu choose events.
11635 * @param {OO.ui.OptionWidget} item Chosen item
11637 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuChoose = function ( item
) {
11638 this.setValue( item
.getData() );
11642 * Handle menu item change events.
11646 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuItemsChange = function () {
11647 var match
= this.menu
.findItemFromData( this.getValue() );
11648 this.menu
.selectItem( match
);
11649 if ( this.menu
.findHighlightedItem() ) {
11650 this.menu
.highlightItem( match
);
11652 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu
.isEmpty() );
11656 * Handle menu toggle events.
11659 * @param {boolean} isVisible Open state of the menu
11661 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuToggle = function ( isVisible
) {
11662 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-open', isVisible
);
11666 * Update the disabled state of the controls
11670 * @return {OO.ui.ComboBoxInputWidget} The widget, for chaining
11672 OO
.ui
.ComboBoxInputWidget
.prototype.updateControlsDisabled = function () {
11673 var disabled
= this.isDisabled() || this.isReadOnly();
11674 if ( this.dropdownButton
) {
11675 this.dropdownButton
.setDisabled( disabled
);
11678 this.menu
.setDisabled( disabled
);
11686 OO
.ui
.ComboBoxInputWidget
.prototype.setDisabled = function () {
11688 OO
.ui
.ComboBoxInputWidget
.parent
.prototype.setDisabled
.apply( this, arguments
);
11689 this.updateControlsDisabled();
11696 OO
.ui
.ComboBoxInputWidget
.prototype.setReadOnly = function () {
11698 OO
.ui
.ComboBoxInputWidget
.parent
.prototype.setReadOnly
.apply( this, arguments
);
11699 this.updateControlsDisabled();
11704 * Set the options available for this input.
11706 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
11708 * @return {OO.ui.Widget} The widget, for chaining
11710 OO
.ui
.ComboBoxInputWidget
.prototype.setOptions = function ( options
) {
11713 .addItems( options
.map( function ( opt
) {
11714 return new OO
.ui
.MenuOptionWidget( {
11716 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
11724 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
11725 * which is a widget that is specified by reference before any optional configuration settings.
11727 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of
11730 * - **left**: The label is placed before the field-widget and aligned with the left margin.
11731 * A left-alignment is used for forms with many fields.
11732 * - **right**: The label is placed before the field-widget and aligned to the right margin.
11733 * A right-alignment is used for long but familiar forms which users tab through,
11734 * verifying the current field with a quick glance at the label.
11735 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
11736 * that users fill out from top to bottom.
11737 * - **inline**: The label is placed after the field-widget and aligned to the left.
11738 * An inline-alignment is best used with checkboxes or radio buttons.
11740 * Help text can either be:
11742 * - accessed via a help icon that appears in the upper right corner of the rendered field layout,
11744 * - shown as a subtle explanation below the label.
11746 * If the help text is brief, or is essential to always expose it, set `helpInline` to `true`.
11747 * If it is long or not essential, leave `helpInline` to its default, `false`.
11749 * Please see the [OOUI documentation on MediaWiki] [1] for examples and more information.
11751 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
11754 * @extends OO.ui.Layout
11755 * @mixins OO.ui.mixin.LabelElement
11756 * @mixins OO.ui.mixin.TitledElement
11759 * @param {OO.ui.Widget} fieldWidget Field widget
11760 * @param {Object} [config] Configuration options
11761 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top'
11763 * @cfg {Array} [errors] Error messages about the widget, which will be
11764 * displayed below the widget.
11765 * @cfg {Array} [warnings] Warning messages about the widget, which will be
11766 * displayed below the widget.
11767 * @cfg {Array} [successMessages] Success messages on user interactions with the widget,
11768 * which will be displayed below the widget.
11769 * The array may contain strings or OO.ui.HtmlSnippet instances.
11770 * @cfg {Array} [notices] Notices about the widget, which will be displayed
11771 * below the widget.
11772 * The array may contain strings or OO.ui.HtmlSnippet instances.
11773 * These are more visible than `help` messages when `helpInline` is set, and so
11774 * might be good for transient messages.
11775 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified
11776 * and `helpInline` is `false`, a "help" icon will appear in the upper-right
11777 * corner of the rendered field; clicking it will display the text in a popup.
11778 * If `helpInline` is `true`, then a subtle description will be shown after the
11780 * @cfg {boolean} [helpInline=false] Whether or not the help should be inline,
11781 * or shown when the "help" icon is clicked.
11782 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if
11784 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11786 * @throws {Error} An error is thrown if no widget is specified
11788 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
11789 // Allow passing positional parameters inside the config object
11790 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
11791 config
= fieldWidget
;
11792 fieldWidget
= config
.fieldWidget
;
11795 // Make sure we have required constructor arguments
11796 if ( fieldWidget
=== undefined ) {
11797 throw new Error( 'Widget not found' );
11800 // Configuration initialization
11801 config
= $.extend( { align
: 'left', helpInline
: false }, config
);
11803 // Parent constructor
11804 OO
.ui
.FieldLayout
.parent
.call( this, config
);
11806 // Mixin constructors
11807 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {
11808 $label
: $( '<label>' )
11810 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( { $titled
: this.$label
}, config
) );
11813 this.fieldWidget
= fieldWidget
;
11815 this.warnings
= [];
11816 this.successMessages
= [];
11818 this.$field
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
11819 this.$messages
= $( '<ul>' );
11820 this.$header
= $( '<span>' );
11821 this.$body
= $( '<div>' );
11823 this.helpInline
= config
.helpInline
;
11826 this.fieldWidget
.connect( this, {
11827 disable
: 'onFieldDisable'
11831 this.$help
= config
.help
?
11832 this.createHelpElement( config
.help
, config
.$overlay
) :
11834 if ( this.fieldWidget
.getInputId() ) {
11835 this.$label
.attr( 'for', this.fieldWidget
.getInputId() );
11836 if ( this.helpInline
) {
11837 this.$help
.attr( 'for', this.fieldWidget
.getInputId() );
11840 this.$label
.on( 'click', function () {
11841 this.fieldWidget
.simulateLabelClick();
11843 if ( this.helpInline
) {
11844 this.$help
.on( 'click', function () {
11845 this.fieldWidget
.simulateLabelClick();
11850 .addClass( 'oo-ui-fieldLayout' )
11851 .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget
.isDisabled() )
11852 .append( this.$body
);
11853 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
11854 this.$header
.addClass( 'oo-ui-fieldLayout-header' );
11855 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
11857 .addClass( 'oo-ui-fieldLayout-field' )
11858 .append( this.fieldWidget
.$element
);
11860 this.setErrors( config
.errors
|| [] );
11861 this.setWarnings( config
.warnings
|| [] );
11862 this.setSuccess( config
.successMessages
|| [] );
11863 this.setNotices( config
.notices
|| [] );
11864 this.setAlignment( config
.align
);
11865 // Call this again to take into account the widget's accessKey
11866 this.updateTitle();
11871 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
11872 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
11873 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
11878 * Handle field disable events.
11881 * @param {boolean} value Field is disabled
11883 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
11884 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
11888 * Get the widget contained by the field.
11890 * @return {OO.ui.Widget} Field widget
11892 OO
.ui
.FieldLayout
.prototype.getField = function () {
11893 return this.fieldWidget
;
11897 * Return `true` if the given field widget can be used with `'inline'` alignment (see
11898 * #setAlignment). Return `false` if it can't or if this can't be determined.
11900 * @return {boolean}
11902 OO
.ui
.FieldLayout
.prototype.isFieldInline = function () {
11903 // This is very simplistic, but should be good enough.
11904 return this.getField().$element
.prop( 'tagName' ).toLowerCase() === 'span';
11909 * @param {string} kind 'error' or 'notice'
11910 * @param {string|OO.ui.HtmlSnippet} text
11913 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
11914 var $listItem
, $icon
, message
;
11915 $listItem
= $( '<li>' );
11916 if ( kind
=== 'error' ) {
11917 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'error' ] } ).$element
;
11918 $listItem
.attr( 'role', 'alert' );
11919 } else if ( kind
=== 'warning' ) {
11920 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
11921 $listItem
.attr( 'role', 'alert' );
11922 } else if ( kind
=== 'success' ) {
11923 $icon
= new OO
.ui
.IconWidget( { icon
: 'check', flags
: [ 'success' ] } ).$element
;
11924 } else if ( kind
=== 'notice' ) {
11925 $icon
= new OO
.ui
.IconWidget( { icon
: 'notice' } ).$element
;
11929 message
= new OO
.ui
.LabelWidget( { label
: text
} );
11931 .append( $icon
, message
.$element
)
11932 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
11937 * Set the field alignment mode.
11940 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
11942 * @return {OO.ui.BookletLayout} The layout, for chaining
11944 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
11945 if ( value
!== this.align
) {
11946 // Default to 'left'
11947 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
11951 if ( value
=== 'inline' && !this.isFieldInline() ) {
11954 // Reorder elements
11956 if ( this.helpInline
) {
11957 if ( value
=== 'top' ) {
11958 this.$header
.append( this.$label
);
11959 this.$body
.append( this.$header
, this.$field
, this.$help
);
11960 } else if ( value
=== 'inline' ) {
11961 this.$header
.append( this.$label
, this.$help
);
11962 this.$body
.append( this.$field
, this.$header
);
11964 this.$header
.append( this.$label
, this.$help
);
11965 this.$body
.append( this.$header
, this.$field
);
11968 if ( value
=== 'top' ) {
11969 this.$header
.append( this.$help
, this.$label
);
11970 this.$body
.append( this.$header
, this.$field
);
11971 } else if ( value
=== 'inline' ) {
11972 this.$header
.append( this.$help
, this.$label
);
11973 this.$body
.append( this.$field
, this.$header
);
11975 this.$header
.append( this.$label
);
11976 this.$body
.append( this.$header
, this.$help
, this.$field
);
11979 // Set classes. The following classes can be used here:
11980 // * oo-ui-fieldLayout-align-left
11981 // * oo-ui-fieldLayout-align-right
11982 // * oo-ui-fieldLayout-align-top
11983 // * oo-ui-fieldLayout-align-inline
11984 if ( this.align
) {
11985 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
11987 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
11988 this.align
= value
;
11995 * Set the list of error messages.
11997 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
11998 * The array may contain strings or OO.ui.HtmlSnippet instances.
12000 * @return {OO.ui.BookletLayout} The layout, for chaining
12002 OO
.ui
.FieldLayout
.prototype.setErrors = function ( errors
) {
12003 this.errors
= errors
.slice();
12004 this.updateMessages();
12009 * Set the list of warning messages.
12011 * @param {Array} warnings Warning messages about the widget, which will be displayed below
12013 * The array may contain strings or OO.ui.HtmlSnippet instances.
12015 * @return {OO.ui.BookletLayout} The layout, for chaining
12017 OO
.ui
.FieldLayout
.prototype.setWarnings = function ( warnings
) {
12018 this.warnings
= warnings
.slice();
12019 this.updateMessages();
12024 * Set the list of success messages.
12026 * @param {Array} successMessages Success messages about the widget, which will be displayed below
12028 * The array may contain strings or OO.ui.HtmlSnippet instances.
12030 * @return {OO.ui.BookletLayout} The layout, for chaining
12032 OO
.ui
.FieldLayout
.prototype.setSuccess = function ( successMessages
) {
12033 this.successMessages
= successMessages
.slice();
12034 this.updateMessages();
12039 * Set the list of notice messages.
12041 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
12042 * The array may contain strings or OO.ui.HtmlSnippet instances.
12044 * @return {OO.ui.BookletLayout} The layout, for chaining
12046 OO
.ui
.FieldLayout
.prototype.setNotices = function ( notices
) {
12047 this.notices
= notices
.slice();
12048 this.updateMessages();
12053 * Update the rendering of error, warning, success and notice messages.
12057 OO
.ui
.FieldLayout
.prototype.updateMessages = function () {
12059 this.$messages
.empty();
12062 this.errors
.length
||
12063 this.warnings
.length
||
12064 this.successMessages
.length
||
12065 this.notices
.length
12067 this.$body
.after( this.$messages
);
12069 this.$messages
.remove();
12073 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
12074 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
12076 for ( i
= 0; i
< this.warnings
.length
; i
++ ) {
12077 this.$messages
.append( this.makeMessage( 'warning', this.warnings
[ i
] ) );
12079 for ( i
= 0; i
< this.successMessages
.length
; i
++ ) {
12080 this.$messages
.append( this.makeMessage( 'success', this.successMessages
[ i
] ) );
12082 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
12083 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
12088 * Include information about the widget's accessKey in our title. TitledElement calls this method.
12089 * (This is a bit of a hack.)
12092 * @param {string} title Tooltip label for 'title' attribute
12095 OO
.ui
.FieldLayout
.prototype.formatTitleWithAccessKey = function ( title
) {
12096 if ( this.fieldWidget
&& this.fieldWidget
.formatTitleWithAccessKey
) {
12097 return this.fieldWidget
.formatTitleWithAccessKey( title
);
12103 * Creates and returns the help element. Also sets the `aria-describedby`
12104 * attribute on the main element of the `fieldWidget`.
12107 * @param {string|OO.ui.HtmlSnippet} [help] Help text.
12108 * @param {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup.
12109 * @return {jQuery} The element that should become `this.$help`.
12111 OO
.ui
.FieldLayout
.prototype.createHelpElement = function ( help
, $overlay
) {
12112 var helpId
, helpWidget
;
12114 if ( this.helpInline
) {
12115 helpWidget
= new OO
.ui
.LabelWidget( {
12117 classes
: [ 'oo-ui-inline-help' ]
12120 helpId
= helpWidget
.getElementId();
12122 helpWidget
= new OO
.ui
.PopupButtonWidget( {
12123 $overlay
: $overlay
,
12127 classes
: [ 'oo-ui-fieldLayout-help' ],
12130 label
: OO
.ui
.msg( 'ooui-field-help' ),
12131 invisibleLabel
: true
12133 if ( help
instanceof OO
.ui
.HtmlSnippet
) {
12134 helpWidget
.getPopup().$body
.html( help
.toString() );
12136 helpWidget
.getPopup().$body
.text( help
);
12139 helpId
= helpWidget
.getPopup().getBodyId();
12142 // Set the 'aria-describedby' attribute on the fieldWidget
12143 // Preference given to an input or a button
12145 this.fieldWidget
.$input
||
12146 this.fieldWidget
.$button
||
12147 this.fieldWidget
.$element
12148 ).attr( 'aria-describedby', helpId
);
12150 return helpWidget
.$element
;
12154 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget,
12155 * a button, and an optional label and/or help text. The field-widget (e.g., a
12156 * {@link OO.ui.TextInputWidget TextInputWidget}), is required and is specified before any optional
12157 * configuration settings.
12159 * Labels can be aligned in one of four ways:
12161 * - **left**: The label is placed before the field-widget and aligned with the left margin.
12162 * A left-alignment is used for forms with many fields.
12163 * - **right**: The label is placed before the field-widget and aligned to the right margin.
12164 * A right-alignment is used for long but familiar forms which users tab through,
12165 * verifying the current field with a quick glance at the label.
12166 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
12167 * that users fill out from top to bottom.
12168 * - **inline**: The label is placed after the field-widget and aligned to the left.
12169 * An inline-alignment is best used with checkboxes or radio buttons.
12171 * Help text is accessed via a help icon that appears in the upper right corner of the rendered
12172 * field layout when help text is specified.
12175 * // Example of an ActionFieldLayout
12176 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
12177 * new OO.ui.TextInputWidget( {
12178 * placeholder: 'Field widget'
12180 * new OO.ui.ButtonWidget( {
12184 * label: 'An ActionFieldLayout. This label is aligned top',
12186 * help: 'This is help text'
12190 * $( document.body ).append( actionFieldLayout.$element );
12193 * @extends OO.ui.FieldLayout
12196 * @param {OO.ui.Widget} fieldWidget Field widget
12197 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
12198 * @param {Object} config
12200 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
12201 // Allow passing positional parameters inside the config object
12202 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
12203 config
= fieldWidget
;
12204 fieldWidget
= config
.fieldWidget
;
12205 buttonWidget
= config
.buttonWidget
;
12208 // Parent constructor
12209 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
12212 this.buttonWidget
= buttonWidget
;
12213 this.$button
= $( '<span>' );
12214 this.$input
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
12217 this.$element
.addClass( 'oo-ui-actionFieldLayout' );
12219 .addClass( 'oo-ui-actionFieldLayout-button' )
12220 .append( this.buttonWidget
.$element
);
12222 .addClass( 'oo-ui-actionFieldLayout-input' )
12223 .append( this.fieldWidget
.$element
);
12224 this.$field
.append( this.$input
, this.$button
);
12229 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
12232 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
12233 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
12234 * configured with a label as well. For more information and examples,
12235 * please see the [OOUI documentation on MediaWiki][1].
12238 * // Example of a fieldset layout
12239 * var input1 = new OO.ui.TextInputWidget( {
12240 * placeholder: 'A text input field'
12243 * var input2 = new OO.ui.TextInputWidget( {
12244 * placeholder: 'A text input field'
12247 * var fieldset = new OO.ui.FieldsetLayout( {
12248 * label: 'Example of a fieldset layout'
12251 * fieldset.addItems( [
12252 * new OO.ui.FieldLayout( input1, {
12253 * label: 'Field One'
12255 * new OO.ui.FieldLayout( input2, {
12256 * label: 'Field Two'
12259 * $( document.body ).append( fieldset.$element );
12261 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
12264 * @extends OO.ui.Layout
12265 * @mixins OO.ui.mixin.IconElement
12266 * @mixins OO.ui.mixin.LabelElement
12267 * @mixins OO.ui.mixin.GroupElement
12270 * @param {Object} [config] Configuration options
12271 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset.
12272 * See OO.ui.FieldLayout for more information about fields.
12273 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon
12274 * will appear in the upper-right corner of the rendered field; clicking it will display the text
12275 * in a popup. For important messages, you are advised to use `notices`, as they are always shown.
12276 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
12277 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
12279 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
12280 // Configuration initialization
12281 config
= config
|| {};
12283 // Parent constructor
12284 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
12286 // Mixin constructors
12287 OO
.ui
.mixin
.IconElement
.call( this, config
);
12288 OO
.ui
.mixin
.LabelElement
.call( this, config
);
12289 OO
.ui
.mixin
.GroupElement
.call( this, config
);
12292 this.$header
= $( '<legend>' );
12293 if ( config
.help
) {
12294 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
12295 $overlay
: config
.$overlay
,
12299 classes
: [ 'oo-ui-fieldsetLayout-help' ],
12302 label
: OO
.ui
.msg( 'ooui-field-help' ),
12303 invisibleLabel
: true
12305 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
12306 this.popupButtonWidget
.getPopup().$body
.html( config
.help
.toString() );
12308 this.popupButtonWidget
.getPopup().$body
.text( config
.help
);
12310 this.$help
= this.popupButtonWidget
.$element
;
12312 this.$help
= $( [] );
12317 .addClass( 'oo-ui-fieldsetLayout-header' )
12318 .append( this.$icon
, this.$label
, this.$help
);
12319 this.$group
.addClass( 'oo-ui-fieldsetLayout-group' );
12321 .addClass( 'oo-ui-fieldsetLayout' )
12322 .prepend( this.$header
, this.$group
);
12323 if ( Array
.isArray( config
.items
) ) {
12324 this.addItems( config
.items
);
12330 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
12331 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
12332 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
12333 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
12335 /* Static Properties */
12341 OO
.ui
.FieldsetLayout
.static.tagName
= 'fieldset';
12344 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use
12345 * browser-based form submission for the fields instead of handling them in JavaScript. Form layouts
12346 * can be configured with an HTML form action, an encoding type, and a method using the #action,
12347 * #enctype, and #method configs, respectively.
12348 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
12350 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
12351 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
12352 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
12353 * some fancier controls. Some controls have both regular and InputWidget variants, for example
12354 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
12355 * often have simplified APIs to match the capabilities of HTML forms.
12356 * See the [OOUI documentation on MediaWiki] [2] for more information about InputWidgets.
12358 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Forms
12359 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
12362 * // Example of a form layout that wraps a fieldset layout
12363 * var input1 = new OO.ui.TextInputWidget( {
12364 * placeholder: 'Username'
12366 * var input2 = new OO.ui.TextInputWidget( {
12367 * placeholder: 'Password',
12370 * var submit = new OO.ui.ButtonInputWidget( {
12374 * var fieldset = new OO.ui.FieldsetLayout( {
12375 * label: 'A form layout'
12377 * fieldset.addItems( [
12378 * new OO.ui.FieldLayout( input1, {
12379 * label: 'Username',
12382 * new OO.ui.FieldLayout( input2, {
12383 * label: 'Password',
12386 * new OO.ui.FieldLayout( submit )
12388 * var form = new OO.ui.FormLayout( {
12389 * items: [ fieldset ],
12390 * action: '/api/formhandler',
12393 * $( document.body ).append( form.$element );
12396 * @extends OO.ui.Layout
12397 * @mixins OO.ui.mixin.GroupElement
12400 * @param {Object} [config] Configuration options
12401 * @cfg {string} [method] HTML form `method` attribute
12402 * @cfg {string} [action] HTML form `action` attribute
12403 * @cfg {string} [enctype] HTML form `enctype` attribute
12404 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
12406 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
12409 // Configuration initialization
12410 config
= config
|| {};
12412 // Parent constructor
12413 OO
.ui
.FormLayout
.parent
.call( this, config
);
12415 // Mixin constructors
12416 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( { $group
: this.$element
}, config
) );
12419 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
12421 // Make sure the action is safe
12422 action
= config
.action
;
12423 if ( action
!== undefined && !OO
.ui
.isSafeUrl( action
) ) {
12424 action
= './' + action
;
12429 .addClass( 'oo-ui-formLayout' )
12431 method
: config
.method
,
12433 enctype
: config
.enctype
12435 if ( Array
.isArray( config
.items
) ) {
12436 this.addItems( config
.items
);
12442 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
12443 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
12448 * A 'submit' event is emitted when the form is submitted.
12453 /* Static Properties */
12459 OO
.ui
.FormLayout
.static.tagName
= 'form';
12464 * Handle form submit events.
12467 * @param {jQuery.Event} e Submit event
12469 * @return {OO.ui.FormLayout} The layout, for chaining
12471 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
12472 if ( this.emit( 'submit' ) ) {
12478 * PanelLayouts expand to cover the entire area of their parent. They can be configured with
12479 * scrolling, padding, and a frame, and are often used together with
12480 * {@link OO.ui.StackLayout StackLayouts}.
12483 * // Example of a panel layout
12484 * var panel = new OO.ui.PanelLayout( {
12488 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
12490 * $( document.body ).append( panel.$element );
12493 * @extends OO.ui.Layout
12496 * @param {Object} [config] Configuration options
12497 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
12498 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
12499 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
12500 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside
12503 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
12504 // Configuration initialization
12505 config
= $.extend( {
12512 // Parent constructor
12513 OO
.ui
.PanelLayout
.parent
.call( this, config
);
12516 this.$element
.addClass( 'oo-ui-panelLayout' );
12517 if ( config
.scrollable
) {
12518 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
12520 if ( config
.padded
) {
12521 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
12523 if ( config
.expanded
) {
12524 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
12526 if ( config
.framed
) {
12527 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
12533 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
12535 /* Static Methods */
12540 OO
.ui
.PanelLayout
.static.reusePreInfuseDOM = function ( node
, config
) {
12541 config
= OO
.ui
.PanelLayout
.parent
.static.reusePreInfuseDOM( node
, config
);
12542 if ( config
.preserveContent
!== false ) {
12543 config
.$content
= $( node
).contents();
12551 * Focus the panel layout
12553 * The default implementation just focuses the first focusable element in the panel
12555 OO
.ui
.PanelLayout
.prototype.focus = function () {
12556 OO
.ui
.findFocusable( this.$element
).focus();
12560 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
12561 * items), with small margins between them. Convenient when you need to put a number of block-level
12562 * widgets on a single line next to each other.
12564 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
12567 * // HorizontalLayout with a text input and a label
12568 * var layout = new OO.ui.HorizontalLayout( {
12570 * new OO.ui.LabelWidget( { label: 'Label' } ),
12571 * new OO.ui.TextInputWidget( { value: 'Text' } )
12574 * $( document.body ).append( layout.$element );
12577 * @extends OO.ui.Layout
12578 * @mixins OO.ui.mixin.GroupElement
12581 * @param {Object} [config] Configuration options
12582 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
12584 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
12585 // Configuration initialization
12586 config
= config
|| {};
12588 // Parent constructor
12589 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
12591 // Mixin constructors
12592 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( { $group
: this.$element
}, config
) );
12595 this.$element
.addClass( 'oo-ui-horizontalLayout' );
12596 if ( Array
.isArray( config
.items
) ) {
12597 this.addItems( config
.items
);
12603 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
12604 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);
12607 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
12608 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
12609 * (to adjust the value in increments) to allow the user to enter a number.
12612 * // A NumberInputWidget.
12613 * var numberInput = new OO.ui.NumberInputWidget( {
12614 * label: 'NumberInputWidget',
12615 * input: { value: 5 },
12619 * $( document.body ).append( numberInput.$element );
12622 * @extends OO.ui.TextInputWidget
12625 * @param {Object} [config] Configuration options
12626 * @cfg {Object} [minusButton] Configuration options to pass to the
12627 * {@link OO.ui.ButtonWidget decrementing button widget}.
12628 * @cfg {Object} [plusButton] Configuration options to pass to the
12629 * {@link OO.ui.ButtonWidget incrementing button widget}.
12630 * @cfg {number} [min=-Infinity] Minimum allowed value
12631 * @cfg {number} [max=Infinity] Maximum allowed value
12632 * @cfg {number|null} [step] If specified, the field only accepts values that are multiples of this.
12633 * @cfg {number} [buttonStep=step||1] Delta when using the buttons or Up/Down arrow keys.
12634 * Defaults to `step` if specified, otherwise `1`.
12635 * @cfg {number} [pageStep=10*buttonStep] Delta when using the Page-up/Page-down keys.
12636 * Defaults to 10 times `buttonStep`.
12637 * @cfg {boolean} [showButtons=true] Whether to show the plus and minus buttons.
12639 OO
.ui
.NumberInputWidget
= function OoUiNumberInputWidget( config
) {
12640 var $field
= $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' );
12642 // Configuration initialization
12643 config
= $.extend( {
12649 // For backward compatibility
12650 $.extend( config
, config
.input
);
12653 // Parent constructor
12654 OO
.ui
.NumberInputWidget
.parent
.call( this, $.extend( config
, {
12658 if ( config
.showButtons
) {
12659 this.minusButton
= new OO
.ui
.ButtonWidget( $.extend(
12661 disabled
: this.isDisabled(),
12663 classes
: [ 'oo-ui-numberInputWidget-minusButton' ],
12668 this.minusButton
.$element
.attr( 'aria-hidden', 'true' );
12669 this.plusButton
= new OO
.ui
.ButtonWidget( $.extend(
12671 disabled
: this.isDisabled(),
12673 classes
: [ 'oo-ui-numberInputWidget-plusButton' ],
12678 this.plusButton
.$element
.attr( 'aria-hidden', 'true' );
12683 keydown
: this.onKeyDown
.bind( this ),
12684 'wheel mousewheel DOMMouseScroll': this.onWheel
.bind( this )
12686 if ( config
.showButtons
) {
12687 this.plusButton
.connect( this, {
12688 click
: [ 'onButtonClick', +1 ]
12690 this.minusButton
.connect( this, {
12691 click
: [ 'onButtonClick', -1 ]
12696 $field
.append( this.$input
);
12697 if ( config
.showButtons
) {
12699 .prepend( this.minusButton
.$element
)
12700 .append( this.plusButton
.$element
);
12704 if ( config
.allowInteger
|| config
.isInteger
) {
12705 // Backward compatibility
12708 this.setRange( config
.min
, config
.max
);
12709 this.setStep( config
.buttonStep
, config
.pageStep
, config
.step
);
12710 // Set the validation method after we set step and range
12711 // so that it doesn't immediately call setValidityFlag
12712 this.setValidation( this.validateNumber
.bind( this ) );
12715 .addClass( 'oo-ui-numberInputWidget' )
12716 .toggleClass( 'oo-ui-numberInputWidget-buttoned', config
.showButtons
)
12722 OO
.inheritClass( OO
.ui
.NumberInputWidget
, OO
.ui
.TextInputWidget
);
12726 // Backward compatibility
12727 OO
.ui
.NumberInputWidget
.prototype.setAllowInteger = function ( flag
) {
12728 this.setStep( flag
? 1 : null );
12730 // Backward compatibility
12731 OO
.ui
.NumberInputWidget
.prototype.setIsInteger
= OO
.ui
.NumberInputWidget
.prototype.setAllowInteger
;
12733 // Backward compatibility
12734 OO
.ui
.NumberInputWidget
.prototype.getAllowInteger = function () {
12735 return this.step
=== 1;
12737 // Backward compatibility
12738 OO
.ui
.NumberInputWidget
.prototype.getIsInteger
= OO
.ui
.NumberInputWidget
.prototype.getAllowInteger
;
12741 * Set the range of allowed values
12743 * @param {number} min Minimum allowed value
12744 * @param {number} max Maximum allowed value
12746 OO
.ui
.NumberInputWidget
.prototype.setRange = function ( min
, max
) {
12748 throw new Error( 'Minimum (' + min
+ ') must not be greater than maximum (' + max
+ ')' );
12752 this.$input
.attr( 'min', this.min
);
12753 this.$input
.attr( 'max', this.max
);
12754 this.setValidityFlag();
12758 * Get the current range
12760 * @return {number[]} Minimum and maximum values
12762 OO
.ui
.NumberInputWidget
.prototype.getRange = function () {
12763 return [ this.min
, this.max
];
12767 * Set the stepping deltas
12769 * @param {number} [buttonStep=step||1] Delta when using the buttons or up/down arrow keys.
12770 * Defaults to `step` if specified, otherwise `1`.
12771 * @param {number} [pageStep=10*buttonStep] Delta when using the page-up/page-down keys.
12772 * Defaults to 10 times `buttonStep`.
12773 * @param {number|null} [step] If specified, the field only accepts values that are multiples
12776 OO
.ui
.NumberInputWidget
.prototype.setStep = function ( buttonStep
, pageStep
, step
) {
12777 if ( buttonStep
=== undefined ) {
12778 buttonStep
= step
|| 1;
12780 if ( pageStep
=== undefined ) {
12781 pageStep
= 10 * buttonStep
;
12783 if ( step
!== null && step
<= 0 ) {
12784 throw new Error( 'Step value, if given, must be positive' );
12786 if ( buttonStep
<= 0 ) {
12787 throw new Error( 'Button step value must be positive' );
12789 if ( pageStep
<= 0 ) {
12790 throw new Error( 'Page step value must be positive' );
12793 this.buttonStep
= buttonStep
;
12794 this.pageStep
= pageStep
;
12795 this.$input
.attr( 'step', this.step
|| 'any' );
12796 this.setValidityFlag();
12802 OO
.ui
.NumberInputWidget
.prototype.setValue = function ( value
) {
12803 if ( value
=== '' ) {
12804 // Some browsers allow a value in the input even if there isn't one reported by $input.val()
12805 // so here we make sure an 'empty' value is actually displayed as such.
12806 this.$input
.val( '' );
12808 return OO
.ui
.NumberInputWidget
.parent
.prototype.setValue
.call( this, value
);
12812 * Get the current stepping values
12814 * @return {number[]} Button step, page step, and validity step
12816 OO
.ui
.NumberInputWidget
.prototype.getStep = function () {
12817 return [ this.buttonStep
, this.pageStep
, this.step
];
12821 * Get the current value of the widget as a number
12823 * @return {number} May be NaN, or an invalid number
12825 OO
.ui
.NumberInputWidget
.prototype.getNumericValue = function () {
12826 return +this.getValue();
12830 * Adjust the value of the widget
12832 * @param {number} delta Adjustment amount
12834 OO
.ui
.NumberInputWidget
.prototype.adjustValue = function ( delta
) {
12835 var n
, v
= this.getNumericValue();
12838 if ( isNaN( delta
) || !isFinite( delta
) ) {
12839 throw new Error( 'Delta must be a finite number' );
12842 if ( isNaN( v
) ) {
12846 n
= Math
.max( Math
.min( n
, this.max
), this.min
);
12848 n
= Math
.round( n
/ this.step
) * this.step
;
12853 this.setValue( n
);
12860 * @param {string} value Field value
12861 * @return {boolean}
12863 OO
.ui
.NumberInputWidget
.prototype.validateNumber = function ( value
) {
12865 if ( value
=== '' ) {
12866 return !this.isRequired();
12869 if ( isNaN( n
) || !isFinite( n
) ) {
12873 if ( this.step
&& Math
.floor( n
/ this.step
) !== n
/ this.step
) {
12877 if ( n
< this.min
|| n
> this.max
) {
12885 * Handle mouse click events.
12888 * @param {number} dir +1 or -1
12890 OO
.ui
.NumberInputWidget
.prototype.onButtonClick = function ( dir
) {
12891 this.adjustValue( dir
* this.buttonStep
);
12895 * Handle mouse wheel events.
12898 * @param {jQuery.Event} event
12899 * @return {undefined/boolean} False to prevent default if event is handled
12901 OO
.ui
.NumberInputWidget
.prototype.onWheel = function ( event
) {
12904 if ( !this.isDisabled() && this.$input
.is( ':focus' ) ) {
12905 // Standard 'wheel' event
12906 if ( event
.originalEvent
.deltaMode
!== undefined ) {
12907 this.sawWheelEvent
= true;
12909 if ( event
.originalEvent
.deltaY
) {
12910 delta
= -event
.originalEvent
.deltaY
;
12911 } else if ( event
.originalEvent
.deltaX
) {
12912 delta
= event
.originalEvent
.deltaX
;
12915 // Non-standard events
12916 if ( !this.sawWheelEvent
) {
12917 if ( event
.originalEvent
.wheelDeltaX
) {
12918 delta
= -event
.originalEvent
.wheelDeltaX
;
12919 } else if ( event
.originalEvent
.wheelDeltaY
) {
12920 delta
= event
.originalEvent
.wheelDeltaY
;
12921 } else if ( event
.originalEvent
.wheelDelta
) {
12922 delta
= event
.originalEvent
.wheelDelta
;
12923 } else if ( event
.originalEvent
.detail
) {
12924 delta
= -event
.originalEvent
.detail
;
12929 delta
= delta
< 0 ? -1 : 1;
12930 this.adjustValue( delta
* this.buttonStep
);
12938 * Handle key down events.
12941 * @param {jQuery.Event} e Key down event
12942 * @return {undefined/boolean} False to prevent default if event is handled
12944 OO
.ui
.NumberInputWidget
.prototype.onKeyDown = function ( e
) {
12945 if ( !this.isDisabled() ) {
12946 switch ( e
.which
) {
12947 case OO
.ui
.Keys
.UP
:
12948 this.adjustValue( this.buttonStep
);
12950 case OO
.ui
.Keys
.DOWN
:
12951 this.adjustValue( -this.buttonStep
);
12953 case OO
.ui
.Keys
.PAGEUP
:
12954 this.adjustValue( this.pageStep
);
12956 case OO
.ui
.Keys
.PAGEDOWN
:
12957 this.adjustValue( -this.pageStep
);
12966 OO
.ui
.NumberInputWidget
.prototype.setDisabled = function ( disabled
) {
12968 OO
.ui
.NumberInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
12970 if ( this.minusButton
) {
12971 this.minusButton
.setDisabled( this.isDisabled() );
12973 if ( this.plusButton
) {
12974 this.plusButton
.setDisabled( this.isDisabled() );
12982 //# sourceMappingURL=oojs-ui-core.js.map.json