3 * https://www.mediawiki.org/wiki/OOjs_UI
5 * Copyright 2011–2017 OOjs UI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: 2017-08-22T21:37:37Z
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 'oojsui-' + OO
.ui
.elementId
;
75 * Check if an element is focusable.
76 * Inspired by :focusable in jQueryUI v1.11.4 - 2015-04-14
78 * @param {jQuery} $element Element to test
79 * @return {boolean} Element is focusable
81 OO
.ui
.isFocusableElement = function ( $element
) {
83 element
= $element
[ 0 ];
85 // Anything disabled is not focusable
86 if ( element
.disabled
) {
90 // Check if the element is visible
92 // This is quicker than calling $element.is( ':visible' )
93 $.expr
.pseudos
.visible( element
) &&
94 // Check that all parents are visible
95 !$element
.parents().addBack().filter( function () {
96 return $.css( this, 'visibility' ) === 'hidden';
102 // Check if the element is ContentEditable, which is the string 'true'
103 if ( element
.contentEditable
=== 'true' ) {
107 // Anything with a non-negative numeric tabIndex is focusable.
108 // Use .prop to avoid browser bugs
109 if ( $element
.prop( 'tabIndex' ) >= 0 ) {
113 // Some element types are naturally focusable
114 // (indexOf is much faster than regex in Chrome and about the
115 // same in FF: https://jsperf.com/regex-vs-indexof-array2)
116 nodeName
= element
.nodeName
.toLowerCase();
117 if ( [ 'input', 'select', 'textarea', 'button', 'object' ].indexOf( nodeName
) !== -1 ) {
121 // Links and areas are focusable if they have an href
122 if ( ( nodeName
=== 'a' || nodeName
=== 'area' ) && $element
.attr( 'href' ) !== undefined ) {
130 * Find a focusable child
132 * @param {jQuery} $container Container to search in
133 * @param {boolean} [backwards] Search backwards
134 * @return {jQuery} Focusable child, or an empty jQuery object if none found
136 OO
.ui
.findFocusable = function ( $container
, backwards
) {
137 var $focusable
= $( [] ),
138 // $focusableCandidates is a superset of things that
139 // could get matched by isFocusableElement
140 $focusableCandidates
= $container
141 .find( 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]' );
144 $focusableCandidates
= Array
.prototype.reverse
.call( $focusableCandidates
);
147 $focusableCandidates
.each( function () {
148 var $this = $( this );
149 if ( OO
.ui
.isFocusableElement( $this ) ) {
158 * Get the user's language and any fallback languages.
160 * These language codes are used to localize user interface elements in the user's language.
162 * In environments that provide a localization system, this function should be overridden to
163 * return the user's language(s). The default implementation returns English (en) only.
165 * @return {string[]} Language codes, in descending order of priority
167 OO
.ui
.getUserLanguages = function () {
172 * Get a value in an object keyed by language code.
174 * @param {Object.<string,Mixed>} obj Object keyed by language code
175 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
176 * @param {string} [fallback] Fallback code, used if no matching language can be found
177 * @return {Mixed} Local value
179 OO
.ui
.getLocalValue = function ( obj
, lang
, fallback
) {
182 // Requested language
186 // Known user language
187 langs
= OO
.ui
.getUserLanguages();
188 for ( i
= 0, len
= langs
.length
; i
< len
; i
++ ) {
195 if ( obj
[ fallback
] ) {
196 return obj
[ fallback
];
198 // First existing language
199 for ( lang
in obj
) {
207 * Check if a node is contained within another node
209 * Similar to jQuery#contains except a list of containers can be supplied
210 * and a boolean argument allows you to include the container in the match list
212 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
213 * @param {HTMLElement} contained Node to find
214 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
215 * @return {boolean} The node is in the list of target nodes
217 OO
.ui
.contains = function ( containers
, contained
, matchContainers
) {
219 if ( !Array
.isArray( containers
) ) {
220 containers
= [ containers
];
222 for ( i
= containers
.length
- 1; i
>= 0; i
-- ) {
223 if ( ( matchContainers
&& contained
=== containers
[ i
] ) || $.contains( containers
[ i
], contained
) ) {
231 * Return a function, that, as long as it continues to be invoked, will not
232 * be triggered. The function will be called after it stops being called for
233 * N milliseconds. If `immediate` is passed, trigger the function on the
234 * leading edge, instead of the trailing.
236 * Ported from: http://underscorejs.org/underscore.js
238 * @param {Function} func Function to debounce
239 * @param {number} [wait=0] Wait period in milliseconds
240 * @param {boolean} [immediate] Trigger on leading edge
241 * @return {Function} Debounced function
243 OO
.ui
.debounce = function ( func
, wait
, immediate
) {
248 later = function () {
251 func
.apply( context
, args
);
254 if ( immediate
&& !timeout
) {
255 func
.apply( context
, args
);
257 if ( !timeout
|| wait
) {
258 clearTimeout( timeout
);
259 timeout
= setTimeout( later
, wait
);
265 * Puts a console warning with provided message.
267 * @param {string} message Message
269 OO
.ui
.warnDeprecation = function ( message
) {
270 if ( OO
.getProp( window
, 'console', 'warn' ) !== undefined ) {
271 // eslint-disable-next-line no-console
272 console
.warn( message
);
277 * Returns a function, that, when invoked, will only be triggered at most once
278 * during a given window of time. If called again during that window, it will
279 * wait until the window ends and then trigger itself again.
281 * As it's not knowable to the caller whether the function will actually run
282 * when the wrapper is called, return values from the function are entirely
285 * @param {Function} func Function to throttle
286 * @param {number} wait Throttle window length, in milliseconds
287 * @return {Function} Throttled function
289 OO
.ui
.throttle = function ( func
, wait
) {
290 var context
, args
, timeout
,
294 previous
= OO
.ui
.now();
295 func
.apply( context
, args
);
298 // Check how long it's been since the last time the function was
299 // called, and whether it's more or less than the requested throttle
300 // period. If it's less, run the function immediately. If it's more,
301 // set a timeout for the remaining time -- but don't replace an
302 // existing timeout, since that'd indefinitely prolong the wait.
303 var remaining
= wait
- ( OO
.ui
.now() - previous
);
306 if ( remaining
<= 0 ) {
307 // Note: unless wait was ridiculously large, this means we'll
308 // automatically run the first time the function was called in a
309 // given period. (If you provide a wait period larger than the
310 // current Unix timestamp, you *deserve* unexpected behavior.)
311 clearTimeout( timeout
);
313 } else if ( !timeout
) {
314 timeout
= setTimeout( run
, remaining
);
320 * A (possibly faster) way to get the current timestamp as an integer
322 * @return {number} Current timestamp, in milliseconds since the Unix epoch
324 OO
.ui
.now
= Date
.now
|| function () {
325 return new Date().getTime();
329 * Reconstitute a JavaScript object corresponding to a widget created by
330 * the PHP implementation.
332 * This is an alias for `OO.ui.Element.static.infuse()`.
334 * @param {string|HTMLElement|jQuery} idOrNode
335 * A DOM id (if a string) or node for the widget to infuse.
336 * @return {OO.ui.Element}
337 * The `OO.ui.Element` corresponding to this (infusable) document node.
339 OO
.ui
.infuse = function ( idOrNode
) {
340 return OO
.ui
.Element
.static.infuse( idOrNode
);
345 * Message store for the default implementation of OO.ui.msg
347 * Environments that provide a localization system should not use this, but should override
348 * OO.ui.msg altogether.
353 // Tool tip for a button that moves items in a list down one place
354 'ooui-outline-control-move-down': 'Move item down',
355 // Tool tip for a button that moves items in a list up one place
356 'ooui-outline-control-move-up': 'Move item up',
357 // Tool tip for a button that removes items from a list
358 'ooui-outline-control-remove': 'Remove item',
359 // Label for the toolbar group that contains a list of all other available tools
360 'ooui-toolbar-more': 'More',
361 // Label for the fake tool that expands the full list of tools in a toolbar group
362 'ooui-toolgroup-expand': 'More',
363 // Label for the fake tool that collapses the full list of tools in a toolbar group
364 'ooui-toolgroup-collapse': 'Fewer',
365 // Default label for the tooltip for the button that removes a tag item
366 'ooui-item-remove': 'Remove',
367 // Default label for the accept button of a confirmation dialog
368 'ooui-dialog-message-accept': 'OK',
369 // Default label for the reject button of a confirmation dialog
370 'ooui-dialog-message-reject': 'Cancel',
371 // Title for process dialog error description
372 'ooui-dialog-process-error': 'Something went wrong',
373 // Label for process dialog dismiss error button, visible when describing errors
374 'ooui-dialog-process-dismiss': 'Dismiss',
375 // Label for process dialog retry action button, visible when describing only recoverable errors
376 'ooui-dialog-process-retry': 'Try again',
377 // Label for process dialog retry action button, visible when describing only warnings
378 'ooui-dialog-process-continue': 'Continue',
379 // Label for the file selection widget's select file button
380 'ooui-selectfile-button-select': 'Select a file',
381 // Label for the file selection widget if file selection is not supported
382 'ooui-selectfile-not-supported': 'File selection is not supported',
383 // Label for the file selection widget when no file is currently selected
384 'ooui-selectfile-placeholder': 'No file is selected',
385 // Label for the file selection widget's drop target
386 'ooui-selectfile-dragdrop-placeholder': 'Drop file here'
390 * Get a localized message.
392 * After the message key, message parameters may optionally be passed. In the default implementation,
393 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
394 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
395 * they support unnamed, ordered message parameters.
397 * In environments that provide a localization system, this function should be overridden to
398 * return the message translated in the user's language. The default implementation always returns
399 * English messages. An example of doing this with [jQuery.i18n](https://github.com/wikimedia/jquery.i18n)
403 * var i, iLen, button,
404 * messagePath = 'oojs-ui/dist/i18n/',
405 * languages = [ $.i18n().locale, 'ur', 'en' ],
408 * for ( i = 0, iLen = languages.length; i < iLen; i++ ) {
409 * languageMap[ languages[ i ] ] = messagePath + languages[ i ].toLowerCase() + '.json';
412 * $.i18n().load( languageMap ).done( function() {
413 * // Replace the built-in `msg` only once we've loaded the internationalization.
414 * // OOjs UI uses `OO.ui.deferMsg` for all initially-loaded messages. So long as
415 * // you put off creating any widgets until this promise is complete, no English
416 * // will be displayed.
417 * OO.ui.msg = $.i18n;
419 * // A button displaying "OK" in the default locale
420 * button = new OO.ui.ButtonWidget( {
421 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
424 * $( 'body' ).append( button.$element );
426 * // A button displaying "OK" in Urdu
427 * $.i18n().locale = 'ur';
428 * button = new OO.ui.ButtonWidget( {
429 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
432 * $( 'body' ).append( button.$element );
435 * @param {string} key Message key
436 * @param {...Mixed} [params] Message parameters
437 * @return {string} Translated message with parameters substituted
439 OO
.ui
.msg = function ( key
) {
440 var message
= messages
[ key
],
441 params
= Array
.prototype.slice
.call( arguments
, 1 );
442 if ( typeof message
=== 'string' ) {
443 // Perform $1 substitution
444 message
= message
.replace( /\$(\d+)/g, function ( unused
, n
) {
445 var i
= parseInt( n
, 10 );
446 return params
[ i
- 1 ] !== undefined ? params
[ i
- 1 ] : '$' + n
;
449 // Return placeholder if message not found
450 message
= '[' + key
+ ']';
457 * Package a message and arguments for deferred resolution.
459 * Use this when you are statically specifying a message and the message may not yet be present.
461 * @param {string} key Message key
462 * @param {...Mixed} [params] Message parameters
463 * @return {Function} Function that returns the resolved message when executed
465 OO
.ui
.deferMsg = function () {
466 var args
= arguments
;
468 return OO
.ui
.msg
.apply( OO
.ui
, args
);
475 * If the message is a function it will be executed, otherwise it will pass through directly.
477 * @param {Function|string} msg Deferred message, or message text
478 * @return {string} Resolved message
480 OO
.ui
.resolveMsg = function ( msg
) {
481 if ( $.isFunction( msg
) ) {
488 * @param {string} url
491 OO
.ui
.isSafeUrl = function ( url
) {
492 // Keep this function in sync with php/Tag.php
493 var i
, protocolWhitelist
;
495 function stringStartsWith( haystack
, needle
) {
496 return haystack
.substr( 0, needle
.length
) === needle
;
499 protocolWhitelist
= [
500 'bitcoin', 'ftp', 'ftps', 'geo', 'git', 'gopher', 'http', 'https', 'irc', 'ircs',
501 'magnet', 'mailto', 'mms', 'news', 'nntp', 'redis', 'sftp', 'sip', 'sips', 'sms', 'ssh',
502 'svn', 'tel', 'telnet', 'urn', 'worldwind', 'xmpp'
509 for ( i
= 0; i
< protocolWhitelist
.length
; i
++ ) {
510 if ( stringStartsWith( url
, protocolWhitelist
[ i
] + ':' ) ) {
515 // This matches '//' too
516 if ( stringStartsWith( url
, '/' ) || stringStartsWith( url
, './' ) ) {
519 if ( stringStartsWith( url
, '?' ) || stringStartsWith( url
, '#' ) ) {
527 * Check if the user has a 'mobile' device.
529 * For our purposes this means the user is primarily using an
530 * on-screen keyboard, touch input instead of a mouse and may
531 * have a physically small display.
533 * It is left up to implementors to decide how to compute this
534 * so the default implementation always returns false.
536 * @return {boolean} Use is on a mobile device
538 OO
.ui
.isMobile = function () {
547 * Namespace for OOjs UI mixins.
549 * Mixins are named according to the type of object they are intended to
550 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
551 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
552 * is intended to be mixed in to an instance of OO.ui.Widget.
560 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
561 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
562 * connected to them and can't be interacted with.
568 * @param {Object} [config] Configuration options
569 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
570 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
572 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
573 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
574 * @cfg {string} [text] Text to insert
575 * @cfg {Array} [content] An array of content elements to append (after #text).
576 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
577 * Instances of OO.ui.Element will have their $element appended.
578 * @cfg {jQuery} [$content] Content elements to append (after #text).
579 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
580 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
581 * Data can also be specified with the #setData method.
583 OO
.ui
.Element
= function OoUiElement( config
) {
584 this.initialConfig
= config
;
585 // Configuration initialization
586 config
= config
|| {};
590 this.elementId
= null;
592 this.data
= config
.data
;
593 this.$element
= config
.$element
||
594 $( document
.createElement( this.getTagName() ) );
595 this.elementGroup
= null;
598 if ( Array
.isArray( config
.classes
) ) {
599 this.$element
.addClass( config
.classes
.join( ' ' ) );
602 this.setElementId( config
.id
);
605 this.$element
.text( config
.text
);
607 if ( config
.content
) {
608 // The `content` property treats plain strings as text; use an
609 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
610 // appropriate $element appended.
611 this.$element
.append( config
.content
.map( function ( v
) {
612 if ( typeof v
=== 'string' ) {
613 // Escape string so it is properly represented in HTML.
614 return document
.createTextNode( v
);
615 } else if ( v
instanceof OO
.ui
.HtmlSnippet
) {
618 } else if ( v
instanceof OO
.ui
.Element
) {
624 if ( config
.$content
) {
625 // The `$content` property treats plain strings as HTML.
626 this.$element
.append( config
.$content
);
632 OO
.initClass( OO
.ui
.Element
);
634 /* Static Properties */
637 * The name of the HTML tag used by the element.
639 * The static value may be ignored if the #getTagName method is overridden.
645 OO
.ui
.Element
.static.tagName
= 'div';
650 * Reconstitute a JavaScript object corresponding to a widget created
651 * by the PHP implementation.
653 * @param {string|HTMLElement|jQuery} idOrNode
654 * A DOM id (if a string) or node for the widget to infuse.
655 * @return {OO.ui.Element}
656 * The `OO.ui.Element` corresponding to this (infusable) document node.
657 * For `Tag` objects emitted on the HTML side (used occasionally for content)
658 * the value returned is a newly-created Element wrapping around the existing
661 OO
.ui
.Element
.static.infuse = function ( idOrNode
) {
662 var obj
= OO
.ui
.Element
.static.unsafeInfuse( idOrNode
, false );
663 // Verify that the type matches up.
664 // FIXME: uncomment after T89721 is fixed, see T90929.
666 if ( !( obj instanceof this['class'] ) ) {
667 throw new Error( 'Infusion type mismatch!' );
674 * Implementation helper for `infuse`; skips the type check and has an
675 * extra property so that only the top-level invocation touches the DOM.
678 * @param {string|HTMLElement|jQuery} idOrNode
679 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
680 * when the top-level widget of this infusion is inserted into DOM,
681 * replacing the original node; or false for top-level invocation.
682 * @return {OO.ui.Element}
684 OO
.ui
.Element
.static.unsafeInfuse = function ( idOrNode
, domPromise
) {
685 // look for a cached result of a previous infusion.
686 var id
, $elem
, data
, cls
, parts
, parent
, obj
, top
, state
, infusedChildren
;
687 if ( typeof idOrNode
=== 'string' ) {
689 $elem
= $( document
.getElementById( id
) );
691 $elem
= $( idOrNode
);
692 id
= $elem
.attr( 'id' );
694 if ( !$elem
.length
) {
695 throw new Error( 'Widget not found: ' + id
);
697 if ( $elem
[ 0 ].oouiInfused
) {
698 $elem
= $elem
[ 0 ].oouiInfused
;
700 data
= $elem
.data( 'ooui-infused' );
703 if ( data
=== true ) {
704 throw new Error( 'Circular dependency! ' + id
);
707 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
708 state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
709 // restore dynamic state after the new element is re-inserted into DOM under infused parent
710 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
711 infusedChildren
= $elem
.data( 'ooui-infused-children' );
712 if ( infusedChildren
&& infusedChildren
.length
) {
713 infusedChildren
.forEach( function ( data
) {
714 var state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
715 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
721 data
= $elem
.attr( 'data-ooui' );
723 throw new Error( 'No infusion data found: ' + id
);
726 data
= JSON
.parse( data
);
730 if ( !( data
&& data
._
) ) {
731 throw new Error( 'No valid infusion data found: ' + id
);
733 if ( data
._
=== 'Tag' ) {
734 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
735 return new OO
.ui
.Element( { $element
: $elem
} );
737 parts
= data
._
.split( '.' );
738 cls
= OO
.getProp
.apply( OO
, [ window
].concat( parts
) );
739 if ( cls
=== undefined ) {
740 // The PHP output might be old and not including the "OO.ui" prefix
741 // TODO: Remove this back-compat after next major release
742 cls
= OO
.getProp
.apply( OO
, [ OO
.ui
].concat( parts
) );
743 if ( cls
=== undefined ) {
744 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
748 // Verify that we're creating an OO.ui.Element instance
751 while ( parent
!== undefined ) {
752 if ( parent
=== OO
.ui
.Element
) {
757 parent
= parent
.parent
;
760 if ( parent
!== OO
.ui
.Element
) {
761 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
764 if ( domPromise
=== false ) {
766 domPromise
= top
.promise();
768 $elem
.data( 'ooui-infused', true ); // prevent loops
769 data
.id
= id
; // implicit
770 infusedChildren
= [];
771 data
= OO
.copy( data
, null, function deserialize( value
) {
773 if ( OO
.isPlainObject( value
) ) {
775 infused
= OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, domPromise
);
776 infusedChildren
.push( infused
);
777 // Flatten the structure
778 infusedChildren
.push
.apply( infusedChildren
, infused
.$element
.data( 'ooui-infused-children' ) || [] );
779 infused
.$element
.removeData( 'ooui-infused-children' );
782 if ( value
.html
!== undefined ) {
783 return new OO
.ui
.HtmlSnippet( value
.html
);
787 // allow widgets to reuse parts of the DOM
788 data
= cls
.static.reusePreInfuseDOM( $elem
[ 0 ], data
);
789 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
790 state
= cls
.static.gatherPreInfuseState( $elem
[ 0 ], data
);
792 // eslint-disable-next-line new-cap
793 obj
= new cls( data
);
794 // now replace old DOM with this new DOM.
796 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
797 // so only mutate the DOM if we need to.
798 if ( $elem
[ 0 ] !== obj
.$element
[ 0 ] ) {
799 $elem
.replaceWith( obj
.$element
);
800 // This element is now gone from the DOM, but if anyone is holding a reference to it,
801 // let's allow them to OO.ui.infuse() it and do what they expect, see T105828.
802 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
803 $elem
[ 0 ].oouiInfused
= obj
.$element
;
807 obj
.$element
.data( 'ooui-infused', obj
);
808 obj
.$element
.data( 'ooui-infused-children', infusedChildren
);
809 // set the 'data-ooui' attribute so we can identify infused widgets
810 obj
.$element
.attr( 'data-ooui', '' );
811 // restore dynamic state after the new element is inserted into DOM
812 domPromise
.done( obj
.restorePreInfuseState
.bind( obj
, state
) );
817 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
819 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
820 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
821 * constructor, which will be given the enhanced config.
824 * @param {HTMLElement} node
825 * @param {Object} config
828 OO
.ui
.Element
.static.reusePreInfuseDOM = function ( node
, config
) {
833 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of an HTML DOM node
834 * (and its children) that represent an Element of the same class and the given configuration,
835 * generated by the PHP implementation.
837 * This method is called just before `node` is detached from the DOM. The return value of this
838 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
839 * is inserted into DOM to replace `node`.
842 * @param {HTMLElement} node
843 * @param {Object} config
846 OO
.ui
.Element
.static.gatherPreInfuseState = function () {
851 * Get a jQuery function within a specific document.
854 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
855 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
857 * @return {Function} Bound jQuery function
859 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
860 function wrapper( selector
) {
861 return $( selector
, wrapper
.context
);
864 wrapper
.context
= this.getDocument( context
);
867 wrapper
.$iframe
= $iframe
;
874 * Get the document of an element.
877 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
878 * @return {HTMLDocument|null} Document object
880 OO
.ui
.Element
.static.getDocument = function ( obj
) {
881 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
882 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
883 // Empty jQuery selections might have a context
890 ( obj
.nodeType
=== Node
.DOCUMENT_NODE
&& obj
) ||
895 * Get the window of an element or document.
898 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
899 * @return {Window} Window object
901 OO
.ui
.Element
.static.getWindow = function ( obj
) {
902 var doc
= this.getDocument( obj
);
903 return doc
.defaultView
;
907 * Get the direction of an element or document.
910 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
911 * @return {string} Text direction, either 'ltr' or 'rtl'
913 OO
.ui
.Element
.static.getDir = function ( obj
) {
916 if ( obj
instanceof jQuery
) {
919 isDoc
= obj
.nodeType
=== Node
.DOCUMENT_NODE
;
920 isWin
= obj
.document
!== undefined;
921 if ( isDoc
|| isWin
) {
927 return $( obj
).css( 'direction' );
931 * Get the offset between two frames.
933 * TODO: Make this function not use recursion.
936 * @param {Window} from Window of the child frame
937 * @param {Window} [to=window] Window of the parent frame
938 * @param {Object} [offset] Offset to start with, used internally
939 * @return {Object} Offset object, containing left and top properties
941 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
942 var i
, len
, frames
, frame
, rect
;
948 offset
= { top
: 0, left
: 0 };
950 if ( from.parent
=== from ) {
954 // Get iframe element
955 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
956 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
957 if ( frames
[ i
].contentWindow
=== from ) {
963 // Recursively accumulate offset values
965 rect
= frame
.getBoundingClientRect();
966 offset
.left
+= rect
.left
;
967 offset
.top
+= rect
.top
;
969 this.getFrameOffset( from.parent
, offset
);
976 * Get the offset between two elements.
978 * The two elements may be in a different frame, but in that case the frame $element is in must
979 * be contained in the frame $anchor is in.
982 * @param {jQuery} $element Element whose position to get
983 * @param {jQuery} $anchor Element to get $element's position relative to
984 * @return {Object} Translated position coordinates, containing top and left properties
986 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
987 var iframe
, iframePos
,
988 pos
= $element
.offset(),
989 anchorPos
= $anchor
.offset(),
990 elementDocument
= this.getDocument( $element
),
991 anchorDocument
= this.getDocument( $anchor
);
993 // If $element isn't in the same document as $anchor, traverse up
994 while ( elementDocument
!== anchorDocument
) {
995 iframe
= elementDocument
.defaultView
.frameElement
;
997 throw new Error( '$element frame is not contained in $anchor frame' );
999 iframePos
= $( iframe
).offset();
1000 pos
.left
+= iframePos
.left
;
1001 pos
.top
+= iframePos
.top
;
1002 elementDocument
= iframe
.ownerDocument
;
1004 pos
.left
-= anchorPos
.left
;
1005 pos
.top
-= anchorPos
.top
;
1010 * Get element border sizes.
1013 * @param {HTMLElement} el Element to measure
1014 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1016 OO
.ui
.Element
.static.getBorders = function ( el
) {
1017 var doc
= el
.ownerDocument
,
1018 win
= doc
.defaultView
,
1019 style
= win
.getComputedStyle( el
, null ),
1021 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
1022 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
1023 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
1024 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
1035 * Get dimensions of an element or window.
1038 * @param {HTMLElement|Window} el Element to measure
1039 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1041 OO
.ui
.Element
.static.getDimensions = function ( el
) {
1043 doc
= el
.ownerDocument
|| el
.document
,
1044 win
= doc
.defaultView
;
1046 if ( win
=== el
|| el
=== doc
.documentElement
) {
1049 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
1051 top
: $win
.scrollTop(),
1052 left
: $win
.scrollLeft()
1054 scrollbar
: { right
: 0, bottom
: 0 },
1058 bottom
: $win
.innerHeight(),
1059 right
: $win
.innerWidth()
1065 borders
: this.getBorders( el
),
1067 top
: $el
.scrollTop(),
1068 left
: $el
.scrollLeft()
1071 right
: $el
.innerWidth() - el
.clientWidth
,
1072 bottom
: $el
.innerHeight() - el
.clientHeight
1074 rect
: el
.getBoundingClientRect()
1080 * Get the number of pixels that an element's content is scrolled to the left.
1082 * Adapted from <https://github.com/othree/jquery.rtl-scroll-type>.
1083 * Original code copyright 2012 Wei-Ko Kao, licensed under the MIT License.
1085 * This function smooths out browser inconsistencies (nicely described in the README at
1086 * <https://github.com/othree/jquery.rtl-scroll-type>) and produces a result consistent
1087 * with Firefox's 'scrollLeft', which seems the sanest.
1091 * @param {HTMLElement|Window} el Element to measure
1092 * @return {number} Scroll position from the left.
1093 * If the element's direction is LTR, this is a positive number between `0` (initial scroll position)
1094 * and `el.scrollWidth - el.clientWidth` (furthest possible scroll position).
1095 * If the element's direction is RTL, this is a negative number between `0` (initial scroll position)
1096 * and `-el.scrollWidth + el.clientWidth` (furthest possible scroll position).
1098 OO
.ui
.Element
.static.getScrollLeft
= ( function () {
1099 var rtlScrollType
= null;
1102 var $definer
= $( '<div dir="rtl" style="font-size: 14px; width: 1px; height: 1px; position: absolute; top: -1000px; overflow: scroll">A</div>' ),
1103 definer
= $definer
[ 0 ];
1105 $definer
.appendTo( 'body' );
1106 if ( definer
.scrollLeft
> 0 ) {
1108 rtlScrollType
= 'default';
1110 definer
.scrollLeft
= 1;
1111 if ( definer
.scrollLeft
=== 0 ) {
1112 // Firefox, old Opera
1113 rtlScrollType
= 'negative';
1115 // Internet Explorer, Edge
1116 rtlScrollType
= 'reverse';
1122 return function getScrollLeft( el
) {
1123 var isRoot
= el
.window
=== el
||
1124 el
=== el
.ownerDocument
.body
||
1125 el
=== el
.ownerDocument
.documentElement
,
1126 scrollLeft
= isRoot
? $( window
).scrollLeft() : el
.scrollLeft
,
1127 // All browsers use the correct scroll type ('negative') on the root, so don't
1128 // do any fixups when looking at the root element
1129 direction
= isRoot
? 'ltr' : $( el
).css( 'direction' );
1131 if ( direction
=== 'rtl' ) {
1132 if ( rtlScrollType
=== null ) {
1135 if ( rtlScrollType
=== 'reverse' ) {
1136 scrollLeft
= -scrollLeft
;
1137 } else if ( rtlScrollType
=== 'default' ) {
1138 scrollLeft
= scrollLeft
- el
.scrollWidth
+ el
.clientWidth
;
1147 * Get the root scrollable element of given element's document.
1149 * On Blink-based browsers (Chrome etc.), `document.documentElement` can't be used to get or set
1150 * the scrollTop property; instead we have to use `document.body`. Changing and testing the value
1151 * lets us use 'body' or 'documentElement' based on what is working.
1153 * https://code.google.com/p/chromium/issues/detail?id=303131
1156 * @param {HTMLElement} el Element to find root scrollable parent for
1157 * @return {HTMLElement} Scrollable parent, `document.body` or `document.documentElement`
1158 * depending on browser
1160 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1161 var scrollTop
, body
;
1163 if ( OO
.ui
.scrollableElement
=== undefined ) {
1164 body
= el
.ownerDocument
.body
;
1165 scrollTop
= body
.scrollTop
;
1168 // In some browsers (observed in Chrome 56 on Linux Mint 18.1),
1169 // body.scrollTop doesn't become exactly 1, but a fractional value like 0.76
1170 if ( Math
.round( body
.scrollTop
) === 1 ) {
1171 body
.scrollTop
= scrollTop
;
1172 OO
.ui
.scrollableElement
= 'body';
1174 OO
.ui
.scrollableElement
= 'documentElement';
1178 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1182 * Get closest scrollable container.
1184 * Traverses up until either a scrollable element or the root is reached, in which case the root
1185 * scrollable element will be returned (see #getRootScrollableElement).
1188 * @param {HTMLElement} el Element to find scrollable container for
1189 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1190 * @return {HTMLElement} Closest scrollable container
1192 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1194 // Browsers do not correctly return the computed value of 'overflow' when 'overflow-x' and
1195 // 'overflow-y' have different values, so we need to check the separate properties.
1196 props
= [ 'overflow-x', 'overflow-y' ],
1197 $parent
= $( el
).parent();
1199 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1200 props
= [ 'overflow-' + dimension
];
1203 // Special case for the document root (which doesn't really have any scrollable container, since
1204 // it is the ultimate scrollable container, but this is probably saner than null or exception)
1205 if ( $( el
).is( 'html, body' ) ) {
1206 return this.getRootScrollableElement( el
);
1209 while ( $parent
.length
) {
1210 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1211 return $parent
[ 0 ];
1215 val
= $parent
.css( props
[ i
] );
1216 // We assume that elements with 'overflow' (in any direction) set to 'hidden' will never be
1217 // scrolled in that direction, but they can actually be scrolled programatically. The user can
1218 // unintentionally perform a scroll in such case even if the application doesn't scroll
1219 // programatically, e.g. when jumping to an anchor, or when using built-in find functionality.
1220 // This could cause funny issues...
1221 if ( val
=== 'auto' || val
=== 'scroll' ) {
1222 return $parent
[ 0 ];
1225 $parent
= $parent
.parent();
1227 // The element is unattached... return something mostly sane
1228 return this.getRootScrollableElement( el
);
1232 * Scroll element into view.
1235 * @param {HTMLElement} el Element to scroll into view
1236 * @param {Object} [config] Configuration options
1237 * @param {string} [config.duration='fast'] jQuery animation duration value
1238 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1239 * to scroll in both directions
1240 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1242 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1243 var position
, animations
, container
, $container
, elementDimensions
, containerDimensions
, $window
,
1244 deferred
= $.Deferred();
1246 // Configuration initialization
1247 config
= config
|| {};
1250 container
= this.getClosestScrollableContainer( el
, config
.direction
);
1251 $container
= $( container
);
1252 elementDimensions
= this.getDimensions( el
);
1253 containerDimensions
= this.getDimensions( container
);
1254 $window
= $( this.getWindow( el
) );
1256 // Compute the element's position relative to the container
1257 if ( $container
.is( 'html, body' ) ) {
1258 // If the scrollable container is the root, this is easy
1260 top
: elementDimensions
.rect
.top
,
1261 bottom
: $window
.innerHeight() - elementDimensions
.rect
.bottom
,
1262 left
: elementDimensions
.rect
.left
,
1263 right
: $window
.innerWidth() - elementDimensions
.rect
.right
1266 // Otherwise, we have to subtract el's coordinates from container's coordinates
1268 top
: elementDimensions
.rect
.top
- ( containerDimensions
.rect
.top
+ containerDimensions
.borders
.top
),
1269 bottom
: containerDimensions
.rect
.bottom
- containerDimensions
.borders
.bottom
- containerDimensions
.scrollbar
.bottom
- elementDimensions
.rect
.bottom
,
1270 left
: elementDimensions
.rect
.left
- ( containerDimensions
.rect
.left
+ containerDimensions
.borders
.left
),
1271 right
: containerDimensions
.rect
.right
- containerDimensions
.borders
.right
- containerDimensions
.scrollbar
.right
- elementDimensions
.rect
.right
1275 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1276 if ( position
.top
< 0 ) {
1277 animations
.scrollTop
= containerDimensions
.scroll
.top
+ position
.top
;
1278 } else if ( position
.top
> 0 && position
.bottom
< 0 ) {
1279 animations
.scrollTop
= containerDimensions
.scroll
.top
+ Math
.min( position
.top
, -position
.bottom
);
1282 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1283 if ( position
.left
< 0 ) {
1284 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ position
.left
;
1285 } else if ( position
.left
> 0 && position
.right
< 0 ) {
1286 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ Math
.min( position
.left
, -position
.right
);
1289 if ( !$.isEmptyObject( animations
) ) {
1290 $container
.stop( true ).animate( animations
, config
.duration
=== undefined ? 'fast' : config
.duration
);
1291 $container
.queue( function ( next
) {
1298 return deferred
.promise();
1302 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1303 * and reserve space for them, because it probably doesn't.
1305 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1306 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1307 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1308 * and then reattach (or show) them back.
1311 * @param {HTMLElement} el Element to reconsider the scrollbars on
1313 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1314 var i
, len
, scrollLeft
, scrollTop
, nodes
= [];
1315 // Save scroll position
1316 scrollLeft
= el
.scrollLeft
;
1317 scrollTop
= el
.scrollTop
;
1318 // Detach all children
1319 while ( el
.firstChild
) {
1320 nodes
.push( el
.firstChild
);
1321 el
.removeChild( el
.firstChild
);
1324 void el
.offsetHeight
;
1325 // Reattach all children
1326 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1327 el
.appendChild( nodes
[ i
] );
1329 // Restore scroll position (no-op if scrollbars disappeared)
1330 el
.scrollLeft
= scrollLeft
;
1331 el
.scrollTop
= scrollTop
;
1337 * Toggle visibility of an element.
1339 * @param {boolean} [show] Make element visible, omit to toggle visibility
1343 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1344 show
= show
=== undefined ? !this.visible
: !!show
;
1346 if ( show
!== this.isVisible() ) {
1347 this.visible
= show
;
1348 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1349 this.emit( 'toggle', show
);
1356 * Check if element is visible.
1358 * @return {boolean} element is visible
1360 OO
.ui
.Element
.prototype.isVisible = function () {
1361 return this.visible
;
1367 * @return {Mixed} Element data
1369 OO
.ui
.Element
.prototype.getData = function () {
1376 * @param {Mixed} data Element data
1379 OO
.ui
.Element
.prototype.setData = function ( data
) {
1385 * Set the element has an 'id' attribute.
1387 * @param {string} id
1390 OO
.ui
.Element
.prototype.setElementId = function ( id
) {
1391 this.elementId
= id
;
1392 this.$element
.attr( 'id', id
);
1397 * Ensure that the element has an 'id' attribute, setting it to an unique value if it's missing,
1398 * and return its value.
1402 OO
.ui
.Element
.prototype.getElementId = function () {
1403 if ( this.elementId
=== null ) {
1404 this.setElementId( OO
.ui
.generateElementId() );
1406 return this.elementId
;
1410 * Check if element supports one or more methods.
1412 * @param {string|string[]} methods Method or list of methods to check
1413 * @return {boolean} All methods are supported
1415 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1419 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1420 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1421 if ( $.isFunction( this[ methods
[ i
] ] ) ) {
1426 return methods
.length
=== support
;
1430 * Update the theme-provided classes.
1432 * @localdoc This is called in element mixins and widget classes any time state changes.
1433 * Updating is debounced, minimizing overhead of changing multiple attributes and
1434 * guaranteeing that theme updates do not occur within an element's constructor
1436 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1437 OO
.ui
.theme
.queueUpdateElementClasses( this );
1441 * Get the HTML tag name.
1443 * Override this method to base the result on instance information.
1445 * @return {string} HTML tag name
1447 OO
.ui
.Element
.prototype.getTagName = function () {
1448 return this.constructor.static.tagName
;
1452 * Check if the element is attached to the DOM
1454 * @return {boolean} The element is attached to the DOM
1456 OO
.ui
.Element
.prototype.isElementAttached = function () {
1457 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1461 * Get the DOM document.
1463 * @return {HTMLDocument} Document object
1465 OO
.ui
.Element
.prototype.getElementDocument = function () {
1466 // Don't cache this in other ways either because subclasses could can change this.$element
1467 return OO
.ui
.Element
.static.getDocument( this.$element
);
1471 * Get the DOM window.
1473 * @return {Window} Window object
1475 OO
.ui
.Element
.prototype.getElementWindow = function () {
1476 return OO
.ui
.Element
.static.getWindow( this.$element
);
1480 * Get closest scrollable container.
1482 * @return {HTMLElement} Closest scrollable container
1484 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1485 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1489 * Get group element is in.
1491 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1493 OO
.ui
.Element
.prototype.getElementGroup = function () {
1494 return this.elementGroup
;
1498 * Set group element is in.
1500 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1503 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1504 this.elementGroup
= group
;
1509 * Scroll element into view.
1511 * @param {Object} [config] Configuration options
1512 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1514 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1516 !this.isElementAttached() ||
1517 !this.isVisible() ||
1518 ( this.getElementGroup() && !this.getElementGroup().isVisible() )
1520 return $.Deferred().resolve();
1522 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1526 * Restore the pre-infusion dynamic state for this widget.
1528 * This method is called after #$element has been inserted into DOM. The parameter is the return
1529 * value of #gatherPreInfuseState.
1532 * @param {Object} state
1534 OO
.ui
.Element
.prototype.restorePreInfuseState = function () {
1538 * Wraps an HTML snippet for use with configuration values which default
1539 * to strings. This bypasses the default html-escaping done to string
1545 * @param {string} [content] HTML content
1547 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
1549 this.content
= content
;
1554 OO
.initClass( OO
.ui
.HtmlSnippet
);
1561 * @return {string} Unchanged HTML snippet.
1563 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
1564 return this.content
;
1568 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1569 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1570 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1571 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1572 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1576 * @extends OO.ui.Element
1577 * @mixins OO.EventEmitter
1580 * @param {Object} [config] Configuration options
1582 OO
.ui
.Layout
= function OoUiLayout( config
) {
1583 // Configuration initialization
1584 config
= config
|| {};
1586 // Parent constructor
1587 OO
.ui
.Layout
.parent
.call( this, config
);
1589 // Mixin constructors
1590 OO
.EventEmitter
.call( this );
1593 this.$element
.addClass( 'oo-ui-layout' );
1598 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1599 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1602 * Widgets are compositions of one or more OOjs UI elements that users can both view
1603 * and interact with. All widgets can be configured and modified via a standard API,
1604 * and their state can change dynamically according to a model.
1608 * @extends OO.ui.Element
1609 * @mixins OO.EventEmitter
1612 * @param {Object} [config] Configuration options
1613 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1614 * appearance reflects this state.
1616 OO
.ui
.Widget
= function OoUiWidget( config
) {
1617 // Initialize config
1618 config
= $.extend( { disabled
: false }, config
);
1620 // Parent constructor
1621 OO
.ui
.Widget
.parent
.call( this, config
);
1623 // Mixin constructors
1624 OO
.EventEmitter
.call( this );
1627 this.disabled
= null;
1628 this.wasDisabled
= null;
1631 this.$element
.addClass( 'oo-ui-widget' );
1632 this.setDisabled( !!config
.disabled
);
1637 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1638 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1645 * A 'disable' event is emitted when the disabled state of the widget changes
1646 * (i.e. on disable **and** enable).
1648 * @param {boolean} disabled Widget is disabled
1654 * A 'toggle' event is emitted when the visibility of the widget changes.
1656 * @param {boolean} visible Widget is visible
1662 * Check if the widget is disabled.
1664 * @return {boolean} Widget is disabled
1666 OO
.ui
.Widget
.prototype.isDisabled = function () {
1667 return this.disabled
;
1671 * Set the 'disabled' state of the widget.
1673 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1675 * @param {boolean} disabled Disable widget
1678 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
1681 this.disabled
= !!disabled
;
1682 isDisabled
= this.isDisabled();
1683 if ( isDisabled
!== this.wasDisabled
) {
1684 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
1685 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
1686 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
1687 this.emit( 'disable', isDisabled
);
1688 this.updateThemeClasses();
1690 this.wasDisabled
= isDisabled
;
1696 * Update the disabled state, in case of changes in parent widget.
1700 OO
.ui
.Widget
.prototype.updateDisabled = function () {
1701 this.setDisabled( this.disabled
);
1706 * Get an ID of a labelable node which is part of this widget, if any, to be used for `<label for>`
1709 * If this function returns null, the widget should have a meaningful #simulateLabelClick method
1712 * @return {string|null} The ID of the labelable element
1714 OO
.ui
.Widget
.prototype.getInputId = function () {
1719 * Simulate the behavior of clicking on a label (a HTML `<label>` element) bound to this input.
1720 * HTML only allows `<label>` to act on specific "labelable" elements; complex widgets might need to
1721 * override this method to provide intuitive, accessible behavior.
1723 * By default, this does nothing. OO.ui.mixin.TabIndexedElement overrides it for focusable widgets.
1724 * Individual widgets may override it too.
1726 * This method is called by OO.ui.LabelWidget and OO.ui.FieldLayout. It should not be called
1729 OO
.ui
.Widget
.prototype.simulateLabelClick = function () {
1740 OO
.ui
.Theme
= function OoUiTheme() {
1741 this.elementClassesQueue
= [];
1742 this.debouncedUpdateQueuedElementClasses
= OO
.ui
.debounce( this.updateQueuedElementClasses
);
1747 OO
.initClass( OO
.ui
.Theme
);
1752 * Get a list of classes to be applied to a widget.
1754 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
1755 * otherwise state transitions will not work properly.
1757 * @param {OO.ui.Element} element Element for which to get classes
1758 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1760 OO
.ui
.Theme
.prototype.getElementClasses = function () {
1761 return { on
: [], off
: [] };
1765 * Update CSS classes provided by the theme.
1767 * For elements with theme logic hooks, this should be called any time there's a state change.
1769 * @param {OO.ui.Element} element Element for which to update classes
1771 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
1772 var $elements
= $( [] ),
1773 classes
= this.getElementClasses( element
);
1775 if ( element
.$icon
) {
1776 $elements
= $elements
.add( element
.$icon
);
1778 if ( element
.$indicator
) {
1779 $elements
= $elements
.add( element
.$indicator
);
1783 .removeClass( classes
.off
.join( ' ' ) )
1784 .addClass( classes
.on
.join( ' ' ) );
1790 OO
.ui
.Theme
.prototype.updateQueuedElementClasses = function () {
1792 for ( i
= 0; i
< this.elementClassesQueue
.length
; i
++ ) {
1793 this.updateElementClasses( this.elementClassesQueue
[ i
] );
1796 this.elementClassesQueue
= [];
1800 * Queue #updateElementClasses to be called for this element.
1802 * @localdoc QUnit tests override this method to directly call #queueUpdateElementClasses,
1803 * to make them synchronous.
1805 * @param {OO.ui.Element} element Element for which to update classes
1807 OO
.ui
.Theme
.prototype.queueUpdateElementClasses = function ( element
) {
1808 // Keep items in the queue unique. Use lastIndexOf to start checking from the end because that's
1809 // the most common case (this method is often called repeatedly for the same element).
1810 if ( this.elementClassesQueue
.lastIndexOf( element
) !== -1 ) {
1813 this.elementClassesQueue
.push( element
);
1814 this.debouncedUpdateQueuedElementClasses();
1818 * Get the transition duration in milliseconds for dialogs opening/closing
1820 * The dialog should be fully rendered this many milliseconds after the
1821 * ready process has executed.
1823 * @return {number} Transition duration in milliseconds
1825 OO
.ui
.Theme
.prototype.getDialogTransitionDuration = function () {
1830 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
1831 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
1832 * order in which users will navigate through the focusable elements via the "tab" key.
1835 * // TabIndexedElement is mixed into the ButtonWidget class
1836 * // to provide a tabIndex property.
1837 * var button1 = new OO.ui.ButtonWidget( {
1841 * var button2 = new OO.ui.ButtonWidget( {
1845 * var button3 = new OO.ui.ButtonWidget( {
1849 * var button4 = new OO.ui.ButtonWidget( {
1853 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
1859 * @param {Object} [config] Configuration options
1860 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
1861 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
1862 * functionality will be applied to it instead.
1863 * @cfg {string|number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
1864 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
1865 * to remove the element from the tab-navigation flow.
1867 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
1868 // Configuration initialization
1869 config
= $.extend( { tabIndex
: 0 }, config
);
1872 this.$tabIndexed
= null;
1873 this.tabIndex
= null;
1876 this.connect( this, { disable
: 'onTabIndexedElementDisable' } );
1879 this.setTabIndex( config
.tabIndex
);
1880 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
1885 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
1890 * Set the element that should use the tabindex functionality.
1892 * This method is used to retarget a tabindex mixin so that its functionality applies
1893 * to the specified element. If an element is currently using the functionality, the mixin’s
1894 * effect on that element is removed before the new element is set up.
1896 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
1899 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
1900 var tabIndex
= this.tabIndex
;
1901 // Remove attributes from old $tabIndexed
1902 this.setTabIndex( null );
1903 // Force update of new $tabIndexed
1904 this.$tabIndexed
= $tabIndexed
;
1905 this.tabIndex
= tabIndex
;
1906 return this.updateTabIndex();
1910 * Set the value of the tabindex.
1912 * @param {string|number|null} tabIndex Tabindex value, or `null` for no tabindex
1915 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
1916 tabIndex
= /^-?\d+$/.test( tabIndex
) ? Number( tabIndex
) : null;
1918 if ( this.tabIndex
!== tabIndex
) {
1919 this.tabIndex
= tabIndex
;
1920 this.updateTabIndex();
1927 * Update the `tabindex` attribute, in case of changes to tab index or
1933 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
1934 if ( this.$tabIndexed
) {
1935 if ( this.tabIndex
!== null ) {
1936 // Do not index over disabled elements
1937 this.$tabIndexed
.attr( {
1938 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
1939 // Support: ChromeVox and NVDA
1940 // These do not seem to inherit aria-disabled from parent elements
1941 'aria-disabled': this.isDisabled().toString()
1944 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
1951 * Handle disable events.
1954 * @param {boolean} disabled Element is disabled
1956 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
1957 this.updateTabIndex();
1961 * Get the value of the tabindex.
1963 * @return {number|null} Tabindex value
1965 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
1966 return this.tabIndex
;
1970 * Get an ID of a focusable element of this widget, if any, to be used for `<label for>` value.
1972 * If the element already has an ID then that is returned, otherwise unique ID is
1973 * generated, set on the element, and returned.
1975 * @return {string|null} The ID of the focusable element
1977 OO
.ui
.mixin
.TabIndexedElement
.prototype.getInputId = function () {
1980 if ( !this.$tabIndexed
) {
1983 if ( !this.isLabelableNode( this.$tabIndexed
) ) {
1987 id
= this.$tabIndexed
.attr( 'id' );
1988 if ( id
=== undefined ) {
1989 id
= OO
.ui
.generateElementId();
1990 this.$tabIndexed
.attr( 'id', id
);
1997 * Whether the node is 'labelable' according to the HTML spec
1998 * (i.e., whether it can be interacted with through a `<label for="…">`).
1999 * See: <https://html.spec.whatwg.org/multipage/forms.html#category-label>.
2002 * @param {jQuery} $node
2005 OO
.ui
.mixin
.TabIndexedElement
.prototype.isLabelableNode = function ( $node
) {
2007 labelableTags
= [ 'button', 'meter', 'output', 'progress', 'select', 'textarea' ],
2008 tagName
= $node
.prop( 'tagName' ).toLowerCase();
2010 if ( tagName
=== 'input' && $node
.attr( 'type' ) !== 'hidden' ) {
2013 if ( labelableTags
.indexOf( tagName
) !== -1 ) {
2020 * Focus this element.
2024 OO
.ui
.mixin
.TabIndexedElement
.prototype.focus = function () {
2025 if ( !this.isDisabled() ) {
2026 this.$tabIndexed
.focus();
2032 * Blur this element.
2036 OO
.ui
.mixin
.TabIndexedElement
.prototype.blur = function () {
2037 this.$tabIndexed
.blur();
2042 * @inheritdoc OO.ui.Widget
2044 OO
.ui
.mixin
.TabIndexedElement
.prototype.simulateLabelClick = function () {
2049 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
2050 * interface element that can be configured with access keys for accessibility.
2051 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
2053 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
2059 * @param {Object} [config] Configuration options
2060 * @cfg {jQuery} [$button] The button element created by the class.
2061 * If this configuration is omitted, the button element will use a generated `<a>`.
2062 * @cfg {boolean} [framed=true] Render the button with a frame
2064 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
2065 // Configuration initialization
2066 config
= config
|| {};
2069 this.$button
= null;
2071 this.active
= config
.active
!== undefined && config
.active
;
2072 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
2073 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
2074 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
2075 this.onKeyUpHandler
= this.onKeyUp
.bind( this );
2076 this.onClickHandler
= this.onClick
.bind( this );
2077 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
2080 this.$element
.addClass( 'oo-ui-buttonElement' );
2081 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
2082 this.setButtonElement( config
.$button
|| $( '<a>' ) );
2087 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
2089 /* Static Properties */
2092 * Cancel mouse down events.
2094 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
2095 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
2096 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
2101 * @property {boolean}
2103 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
2108 * A 'click' event is emitted when the button element is clicked.
2116 * Set the button element.
2118 * This method is used to retarget a button mixin so that its functionality applies to
2119 * the specified button element instead of the one created by the class. If a button element
2120 * is already set, the method will remove the mixin’s effect on that element.
2122 * @param {jQuery} $button Element to use as button
2124 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
2125 if ( this.$button
) {
2127 .removeClass( 'oo-ui-buttonElement-button' )
2128 .removeAttr( 'role accesskey' )
2130 mousedown
: this.onMouseDownHandler
,
2131 keydown
: this.onKeyDownHandler
,
2132 click
: this.onClickHandler
,
2133 keypress
: this.onKeyPressHandler
2137 this.$button
= $button
2138 .addClass( 'oo-ui-buttonElement-button' )
2140 mousedown
: this.onMouseDownHandler
,
2141 keydown
: this.onKeyDownHandler
,
2142 click
: this.onClickHandler
,
2143 keypress
: this.onKeyPressHandler
2146 // Add `role="button"` on `<a>` elements, where it's needed
2147 // `toUppercase()` is added for XHTML documents
2148 if ( this.$button
.prop( 'tagName' ).toUpperCase() === 'A' ) {
2149 this.$button
.attr( 'role', 'button' );
2154 * Handles mouse down events.
2157 * @param {jQuery.Event} e Mouse down event
2159 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
2160 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
2163 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
2164 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
2165 // reliably remove the pressed class
2166 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
2167 // Prevent change of focus unless specifically configured otherwise
2168 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
2174 * Handles mouse up events.
2177 * @param {MouseEvent} e Mouse up event
2179 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp = function ( e
) {
2180 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
2183 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
2184 // Stop listening for mouseup, since we only needed this once
2185 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
2189 * Handles mouse click events.
2192 * @param {jQuery.Event} e Mouse click event
2195 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
2196 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
2197 if ( this.emit( 'click' ) ) {
2204 * Handles key down events.
2207 * @param {jQuery.Event} e Key down event
2209 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
2210 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2213 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
2214 // Run the keyup handler no matter where the key is when the button is let go, so we can
2215 // reliably remove the pressed class
2216 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler
, true );
2220 * Handles key up events.
2223 * @param {KeyboardEvent} e Key up event
2225 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyUp = function ( e
) {
2226 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2229 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
2230 // Stop listening for keyup, since we only needed this once
2231 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler
, true );
2235 * Handles key press events.
2238 * @param {jQuery.Event} e Key press event
2241 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
2242 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
2243 if ( this.emit( 'click' ) ) {
2250 * Check if button has a frame.
2252 * @return {boolean} Button is framed
2254 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
2259 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
2261 * @param {boolean} [framed] Make button framed, omit to toggle
2264 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
2265 framed
= framed
=== undefined ? !this.framed
: !!framed
;
2266 if ( framed
!== this.framed
) {
2267 this.framed
= framed
;
2269 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
2270 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
2271 this.updateThemeClasses();
2278 * Set the button's active state.
2280 * The active state can be set on:
2282 * - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected
2283 * - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on
2284 * - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page
2287 * @param {boolean} value Make button active
2290 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
2291 this.active
= !!value
;
2292 this.$element
.toggleClass( 'oo-ui-buttonElement-active', this.active
);
2293 this.updateThemeClasses();
2298 * Check if the button is active
2301 * @return {boolean} The button is active
2303 OO
.ui
.mixin
.ButtonElement
.prototype.isActive = function () {
2308 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
2309 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
2310 * items from the group is done through the interface the class provides.
2311 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2313 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
2316 * @mixins OO.EmitterList
2320 * @param {Object} [config] Configuration options
2321 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
2322 * is omitted, the group element will use a generated `<div>`.
2324 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
2325 // Configuration initialization
2326 config
= config
|| {};
2328 // Mixin constructors
2329 OO
.EmitterList
.call( this, config
);
2335 this.setGroupElement( config
.$group
|| $( '<div>' ) );
2340 OO
.mixinClass( OO
.ui
.mixin
.GroupElement
, OO
.EmitterList
);
2347 * A change event is emitted when the set of selected items changes.
2349 * @param {OO.ui.Element[]} items Items currently in the group
2355 * Set the group element.
2357 * If an element is already set, items will be moved to the new element.
2359 * @param {jQuery} $group Element to use as group
2361 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
2364 this.$group
= $group
;
2365 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2366 this.$group
.append( this.items
[ i
].$element
);
2371 * Get an item by its data.
2373 * Only the first item with matching data will be returned. To return all matching items,
2374 * use the #getItemsFromData method.
2376 * @param {Object} data Item data to search for
2377 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2379 OO
.ui
.mixin
.GroupElement
.prototype.getItemFromData = function ( data
) {
2381 hash
= OO
.getHash( data
);
2383 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2384 item
= this.items
[ i
];
2385 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2394 * Get items by their data.
2396 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
2398 * @param {Object} data Item data to search for
2399 * @return {OO.ui.Element[]} Items with equivalent data
2401 OO
.ui
.mixin
.GroupElement
.prototype.getItemsFromData = function ( data
) {
2403 hash
= OO
.getHash( data
),
2406 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2407 item
= this.items
[ i
];
2408 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2417 * Add items to the group.
2419 * Items will be added to the end of the group array unless the optional `index` parameter specifies
2420 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
2422 * @param {OO.ui.Element[]} items An array of items to add to the group
2423 * @param {number} [index] Index of the insertion point
2426 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
2428 OO
.EmitterList
.prototype.addItems
.call( this, items
, index
);
2430 this.emit( 'change', this.getItems() );
2437 OO
.ui
.mixin
.GroupElement
.prototype.moveItem = function ( items
, newIndex
) {
2438 // insertItemElements expects this.items to not have been modified yet, so call before the mixin
2439 this.insertItemElements( items
, newIndex
);
2442 newIndex
= OO
.EmitterList
.prototype.moveItem
.call( this, items
, newIndex
);
2450 OO
.ui
.mixin
.GroupElement
.prototype.insertItem = function ( item
, index
) {
2451 item
.setElementGroup( this );
2452 this.insertItemElements( item
, index
);
2455 index
= OO
.EmitterList
.prototype.insertItem
.call( this, item
, index
);
2461 * Insert elements into the group
2464 * @param {OO.ui.Element} itemWidget Item to insert
2465 * @param {number} index Insertion index
2467 OO
.ui
.mixin
.GroupElement
.prototype.insertItemElements = function ( itemWidget
, index
) {
2468 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
2469 this.$group
.append( itemWidget
.$element
);
2470 } else if ( index
=== 0 ) {
2471 this.$group
.prepend( itemWidget
.$element
);
2473 this.items
[ index
].$element
.before( itemWidget
.$element
);
2478 * Remove the specified items from a group.
2480 * Removed items are detached (not removed) from the DOM so that they may be reused.
2481 * To remove all items from a group, you may wish to use the #clearItems method instead.
2483 * @param {OO.ui.Element[]} items An array of items to remove
2486 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
2487 var i
, len
, item
, index
;
2489 // Remove specific items elements
2490 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
2492 index
= this.items
.indexOf( item
);
2493 if ( index
!== -1 ) {
2494 item
.setElementGroup( null );
2495 item
.$element
.detach();
2500 OO
.EmitterList
.prototype.removeItems
.call( this, items
);
2502 this.emit( 'change', this.getItems() );
2507 * Clear all items from the group.
2509 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2510 * To remove only a subset of items from a group, use the #removeItems method.
2514 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
2517 // Remove all item elements
2518 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2519 this.items
[ i
].setElementGroup( null );
2520 this.items
[ i
].$element
.detach();
2524 OO
.EmitterList
.prototype.clearItems
.call( this );
2526 this.emit( 'change', this.getItems() );
2531 * IconElement is often mixed into other classes to generate an icon.
2532 * Icons are graphics, about the size of normal text. They are used to aid the user
2533 * in locating a control or to convey information in a space-efficient way. See the
2534 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
2535 * included in the library.
2537 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2543 * @param {Object} [config] Configuration options
2544 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2545 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2546 * the icon element be set to an existing icon instead of the one generated by this class, set a
2547 * value using a jQuery selection. For example:
2549 * // Use a <div> tag instead of a <span>
2551 * // Use an existing icon element instead of the one generated by the class
2552 * $icon: this.$element
2553 * // Use an icon element from a child widget
2554 * $icon: this.childwidget.$element
2555 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
2556 * symbolic names. A map is used for i18n purposes and contains a `default` icon
2557 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
2558 * by the user's language.
2560 * Example of an i18n map:
2562 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2563 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
2564 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2565 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
2566 * text. The icon title is displayed when users move the mouse over the icon.
2568 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
2569 // Configuration initialization
2570 config
= config
|| {};
2575 this.iconTitle
= null;
2578 this.setIcon( config
.icon
|| this.constructor.static.icon
);
2579 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
2580 this.setIconElement( config
.$icon
|| $( '<span>' ) );
2585 OO
.initClass( OO
.ui
.mixin
.IconElement
);
2587 /* Static Properties */
2590 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
2591 * for i18n purposes and contains a `default` icon name and additional names keyed by
2592 * language code. The `default` name is used when no icon is keyed by the user's language.
2594 * Example of an i18n map:
2596 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2598 * Note: the static property will be overridden if the #icon configuration is used.
2602 * @property {Object|string}
2604 OO
.ui
.mixin
.IconElement
.static.icon
= null;
2607 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2608 * function that returns title text, or `null` for no title.
2610 * The static property will be overridden if the #iconTitle configuration is used.
2614 * @property {string|Function|null}
2616 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
2621 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2622 * applies to the specified icon element instead of the one created by the class. If an icon
2623 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2624 * and mixin methods will no longer affect the element.
2626 * @param {jQuery} $icon Element to use as icon
2628 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
2631 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
2632 .removeAttr( 'title' );
2636 .addClass( 'oo-ui-iconElement-icon' )
2637 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
2638 if ( this.iconTitle
!== null ) {
2639 this.$icon
.attr( 'title', this.iconTitle
);
2642 this.updateThemeClasses();
2646 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
2647 * The icon parameter can also be set to a map of icon names. See the #icon config setting
2650 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
2651 * by language code, or `null` to remove the icon.
2654 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
2655 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
2656 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
2658 if ( this.icon
!== icon
) {
2660 if ( this.icon
!== null ) {
2661 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
2663 if ( icon
!== null ) {
2664 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
2670 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
2671 this.updateThemeClasses();
2677 * Set the icon title. Use `null` to remove the title.
2679 * @param {string|Function|null} iconTitle A text string used as the icon title,
2680 * a function that returns title text, or `null` for no title.
2683 OO
.ui
.mixin
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
2685 ( typeof iconTitle
=== 'function' || ( typeof iconTitle
=== 'string' && iconTitle
.length
) ) ?
2686 OO
.ui
.resolveMsg( iconTitle
) : null;
2688 if ( this.iconTitle
!== iconTitle
) {
2689 this.iconTitle
= iconTitle
;
2691 if ( this.iconTitle
!== null ) {
2692 this.$icon
.attr( 'title', iconTitle
);
2694 this.$icon
.removeAttr( 'title' );
2703 * Get the symbolic name of the icon.
2705 * @return {string} Icon name
2707 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
2712 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
2714 * @return {string} Icon title text
2716 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
2717 return this.iconTitle
;
2721 * IndicatorElement is often mixed into other classes to generate an indicator.
2722 * Indicators are small graphics that are generally used in two ways:
2724 * - To draw attention to the status of an item. For example, an indicator might be
2725 * used to show that an item in a list has errors that need to be resolved.
2726 * - To clarify the function of a control that acts in an exceptional way (a button
2727 * that opens a menu instead of performing an action directly, for example).
2729 * For a list of indicators included in the library, please see the
2730 * [OOjs UI documentation on MediaWiki] [1].
2732 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2738 * @param {Object} [config] Configuration options
2739 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
2740 * configuration is omitted, the indicator element will use a generated `<span>`.
2741 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2742 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
2744 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2745 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
2746 * or a function that returns title text. The indicator title is displayed when users move
2747 * the mouse over the indicator.
2749 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
2750 // Configuration initialization
2751 config
= config
|| {};
2754 this.$indicator
= null;
2755 this.indicator
= null;
2756 this.indicatorTitle
= null;
2759 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
2760 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
2761 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
2766 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
2768 /* Static Properties */
2771 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2772 * The static property will be overridden if the #indicator configuration is used.
2776 * @property {string|null}
2778 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
2781 * A text string used as the indicator title, a function that returns title text, or `null`
2782 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
2786 * @property {string|Function|null}
2788 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
2793 * Set the indicator element.
2795 * If an element is already set, it will be cleaned up before setting up the new element.
2797 * @param {jQuery} $indicator Element to use as indicator
2799 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
2800 if ( this.$indicator
) {
2802 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
2803 .removeAttr( 'title' );
2806 this.$indicator
= $indicator
2807 .addClass( 'oo-ui-indicatorElement-indicator' )
2808 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
2809 if ( this.indicatorTitle
!== null ) {
2810 this.$indicator
.attr( 'title', this.indicatorTitle
);
2813 this.updateThemeClasses();
2817 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
2819 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
2822 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
2823 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
2825 if ( this.indicator
!== indicator
) {
2826 if ( this.$indicator
) {
2827 if ( this.indicator
!== null ) {
2828 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
2830 if ( indicator
!== null ) {
2831 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
2834 this.indicator
= indicator
;
2837 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
2838 this.updateThemeClasses();
2844 * Set the indicator title.
2846 * The title is displayed when a user moves the mouse over the indicator.
2848 * @param {string|Function|null} indicatorTitle Indicator title text, a function that returns text, or
2849 * `null` for no indicator title
2852 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
2854 ( typeof indicatorTitle
=== 'function' || ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ) ?
2855 OO
.ui
.resolveMsg( indicatorTitle
) : null;
2857 if ( this.indicatorTitle
!== indicatorTitle
) {
2858 this.indicatorTitle
= indicatorTitle
;
2859 if ( this.$indicator
) {
2860 if ( this.indicatorTitle
!== null ) {
2861 this.$indicator
.attr( 'title', indicatorTitle
);
2863 this.$indicator
.removeAttr( 'title' );
2872 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2874 * @return {string} Symbolic name of indicator
2876 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
2877 return this.indicator
;
2881 * Get the indicator title.
2883 * The title is displayed when a user moves the mouse over the indicator.
2885 * @return {string} Indicator title text
2887 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
2888 return this.indicatorTitle
;
2892 * LabelElement is often mixed into other classes to generate a label, which
2893 * helps identify the function of an interface element.
2894 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
2896 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2902 * @param {Object} [config] Configuration options
2903 * @cfg {jQuery} [$label] The label element created by the class. If this
2904 * configuration is omitted, the label element will use a generated `<span>`.
2905 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
2906 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
2907 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
2908 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2910 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
2911 // Configuration initialization
2912 config
= config
|| {};
2919 this.setLabel( config
.label
|| this.constructor.static.label
);
2920 this.setLabelElement( config
.$label
|| $( '<span>' ) );
2925 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
2930 * @event labelChange
2931 * @param {string} value
2934 /* Static Properties */
2937 * The label text. The label can be specified as a plaintext string, a function that will
2938 * produce a string in the future, or `null` for no label. The static value will
2939 * be overridden if a label is specified with the #label config option.
2943 * @property {string|Function|null}
2945 OO
.ui
.mixin
.LabelElement
.static.label
= null;
2947 /* Static methods */
2950 * Highlight the first occurrence of the query in the given text
2952 * @param {string} text Text
2953 * @param {string} query Query to find
2954 * @return {jQuery} Text with the first match of the query
2955 * sub-string wrapped in highlighted span
2957 OO
.ui
.mixin
.LabelElement
.static.highlightQuery = function ( text
, query
) {
2958 var $result
= $( '<span>' ),
2959 offset
= text
.toLowerCase().indexOf( query
.toLowerCase() );
2961 if ( !query
.length
|| offset
=== -1 ) {
2962 return $result
.text( text
);
2965 document
.createTextNode( text
.slice( 0, offset
) ),
2967 .addClass( 'oo-ui-labelElement-label-highlight' )
2968 .text( text
.slice( offset
, offset
+ query
.length
) ),
2969 document
.createTextNode( text
.slice( offset
+ query
.length
) )
2971 return $result
.contents();
2977 * Set the label element.
2979 * If an element is already set, it will be cleaned up before setting up the new element.
2981 * @param {jQuery} $label Element to use as label
2983 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
2984 if ( this.$label
) {
2985 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
2988 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
2989 this.setLabelContent( this.label
);
2995 * An empty string will result in the label being hidden. A string containing only whitespace will
2996 * be converted to a single ` `.
2998 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
2999 * text; or null for no label
3002 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
3003 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
3004 label
= ( ( typeof label
=== 'string' || label
instanceof jQuery
) && label
.length
) || ( label
instanceof OO
.ui
.HtmlSnippet
&& label
.toString().length
) ? label
: null;
3006 if ( this.label
!== label
) {
3007 if ( this.$label
) {
3008 this.setLabelContent( label
);
3011 this.emit( 'labelChange' );
3014 this.$element
.toggleClass( 'oo-ui-labelElement', !!this.label
);
3020 * Set the label as plain text with a highlighted query
3022 * @param {string} text Text label to set
3023 * @param {string} query Substring of text to highlight
3026 OO
.ui
.mixin
.LabelElement
.prototype.setHighlightedQuery = function ( text
, query
) {
3027 return this.setLabel( this.constructor.static.highlightQuery( text
, query
) );
3033 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
3034 * text; or null for no label
3036 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
3041 * Set the content of the label.
3043 * Do not call this method until after the label element has been set by #setLabelElement.
3046 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
3047 * text; or null for no label
3049 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
3050 if ( typeof label
=== 'string' ) {
3051 if ( label
.match( /^\s*$/ ) ) {
3052 // Convert whitespace only string to a single non-breaking space
3053 this.$label
.html( ' ' );
3055 this.$label
.text( label
);
3057 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
3058 this.$label
.html( label
.toString() );
3059 } else if ( label
instanceof jQuery
) {
3060 this.$label
.empty().append( label
);
3062 this.$label
.empty();
3067 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
3068 * additional functionality to an element created by another class. The class provides
3069 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
3070 * which are used to customize the look and feel of a widget to better describe its
3071 * importance and functionality.
3073 * The library currently contains the following styling flags for general use:
3075 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
3076 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
3077 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
3079 * The flags affect the appearance of the buttons:
3082 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
3083 * var button1 = new OO.ui.ButtonWidget( {
3084 * label: 'Constructive',
3085 * flags: 'constructive'
3087 * var button2 = new OO.ui.ButtonWidget( {
3088 * label: 'Destructive',
3089 * flags: 'destructive'
3091 * var button3 = new OO.ui.ButtonWidget( {
3092 * label: 'Progressive',
3093 * flags: 'progressive'
3095 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
3097 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
3098 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
3100 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
3106 * @param {Object} [config] Configuration options
3107 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
3108 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
3109 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
3110 * @cfg {jQuery} [$flagged] The flagged element. By default,
3111 * the flagged functionality is applied to the element created by the class ($element).
3112 * If a different element is specified, the flagged functionality will be applied to it instead.
3114 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
3115 // Configuration initialization
3116 config
= config
|| {};
3120 this.$flagged
= null;
3123 this.setFlags( config
.flags
);
3124 this.setFlaggedElement( config
.$flagged
|| this.$element
);
3131 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
3132 * parameter contains the name of each modified flag and indicates whether it was
3135 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
3136 * that the flag was added, `false` that the flag was removed.
3142 * Set the flagged element.
3144 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
3145 * If an element is already set, the method will remove the mixin’s effect on that element.
3147 * @param {jQuery} $flagged Element that should be flagged
3149 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
3150 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
3151 return 'oo-ui-flaggedElement-' + flag
;
3154 if ( this.$flagged
) {
3155 this.$flagged
.removeClass( classNames
);
3158 this.$flagged
= $flagged
.addClass( classNames
);
3162 * Check if the specified flag is set.
3164 * @param {string} flag Name of flag
3165 * @return {boolean} The flag is set
3167 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
3168 // This may be called before the constructor, thus before this.flags is set
3169 return this.flags
&& ( flag
in this.flags
);
3173 * Get the names of all flags set.
3175 * @return {string[]} Flag names
3177 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
3178 // This may be called before the constructor, thus before this.flags is set
3179 return Object
.keys( this.flags
|| {} );
3188 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
3189 var flag
, className
,
3192 classPrefix
= 'oo-ui-flaggedElement-';
3194 for ( flag
in this.flags
) {
3195 className
= classPrefix
+ flag
;
3196 changes
[ flag
] = false;
3197 delete this.flags
[ flag
];
3198 remove
.push( className
);
3201 if ( this.$flagged
) {
3202 this.$flagged
.removeClass( remove
.join( ' ' ) );
3205 this.updateThemeClasses();
3206 this.emit( 'flag', changes
);
3212 * Add one or more flags.
3214 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
3215 * or an object keyed by flag name with a boolean value that indicates whether the flag should
3216 * be added (`true`) or removed (`false`).
3220 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
3221 var i
, len
, flag
, className
,
3225 classPrefix
= 'oo-ui-flaggedElement-';
3227 if ( typeof flags
=== 'string' ) {
3228 className
= classPrefix
+ flags
;
3230 if ( !this.flags
[ flags
] ) {
3231 this.flags
[ flags
] = true;
3232 add
.push( className
);
3234 } else if ( Array
.isArray( flags
) ) {
3235 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
3237 className
= classPrefix
+ flag
;
3239 if ( !this.flags
[ flag
] ) {
3240 changes
[ flag
] = true;
3241 this.flags
[ flag
] = true;
3242 add
.push( className
);
3245 } else if ( OO
.isPlainObject( flags
) ) {
3246 for ( flag
in flags
) {
3247 className
= classPrefix
+ flag
;
3248 if ( flags
[ flag
] ) {
3250 if ( !this.flags
[ flag
] ) {
3251 changes
[ flag
] = true;
3252 this.flags
[ flag
] = true;
3253 add
.push( className
);
3257 if ( this.flags
[ flag
] ) {
3258 changes
[ flag
] = false;
3259 delete this.flags
[ flag
];
3260 remove
.push( className
);
3266 if ( this.$flagged
) {
3268 .addClass( add
.join( ' ' ) )
3269 .removeClass( remove
.join( ' ' ) );
3272 this.updateThemeClasses();
3273 this.emit( 'flag', changes
);
3279 * TitledElement is mixed into other classes to provide a `title` attribute.
3280 * Titles are rendered by the browser and are made visible when the user moves
3281 * the mouse over the element. Titles are not visible on touch devices.
3284 * // TitledElement provides a 'title' attribute to the
3285 * // ButtonWidget class
3286 * var button = new OO.ui.ButtonWidget( {
3287 * label: 'Button with Title',
3288 * title: 'I am a button'
3290 * $( 'body' ).append( button.$element );
3296 * @param {Object} [config] Configuration options
3297 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
3298 * If this config is omitted, the title functionality is applied to $element, the
3299 * element created by the class.
3300 * @cfg {string|Function} [title] The title text or a function that returns text. If
3301 * this config is omitted, the value of the {@link #static-title static title} property is used.
3303 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
3304 // Configuration initialization
3305 config
= config
|| {};
3308 this.$titled
= null;
3312 this.setTitle( config
.title
!== undefined ? config
.title
: this.constructor.static.title
);
3313 this.setTitledElement( config
.$titled
|| this.$element
);
3318 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
3320 /* Static Properties */
3323 * The title text, a function that returns text, or `null` for no title. The value of the static property
3324 * is overridden if the #title config option is used.
3328 * @property {string|Function|null}
3330 OO
.ui
.mixin
.TitledElement
.static.title
= null;
3335 * Set the titled element.
3337 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
3338 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
3340 * @param {jQuery} $titled Element that should use the 'titled' functionality
3342 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
3343 if ( this.$titled
) {
3344 this.$titled
.removeAttr( 'title' );
3347 this.$titled
= $titled
;
3356 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
3359 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
3360 title
= typeof title
=== 'function' ? OO
.ui
.resolveMsg( title
) : title
;
3361 title
= ( typeof title
=== 'string' && title
.length
) ? title
: null;
3363 if ( this.title
!== title
) {
3372 * Update the title attribute, in case of changes to title or accessKey.
3377 OO
.ui
.mixin
.TitledElement
.prototype.updateTitle = function () {
3378 var title
= this.getTitle();
3379 if ( this.$titled
) {
3380 if ( title
!== null ) {
3381 // Only if this is an AccessKeyedElement
3382 if ( this.formatTitleWithAccessKey
) {
3383 title
= this.formatTitleWithAccessKey( title
);
3385 this.$titled
.attr( 'title', title
);
3387 this.$titled
.removeAttr( 'title' );
3396 * @return {string} Title string
3398 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
3403 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
3404 * Accesskeys allow an user to go to a specific element by using
3405 * a shortcut combination of a browser specific keys + the key
3409 * // AccessKeyedElement provides an 'accesskey' attribute to the
3410 * // ButtonWidget class
3411 * var button = new OO.ui.ButtonWidget( {
3412 * label: 'Button with Accesskey',
3415 * $( 'body' ).append( button.$element );
3421 * @param {Object} [config] Configuration options
3422 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3423 * If this config is omitted, the accesskey functionality is applied to $element, the
3424 * element created by the class.
3425 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3426 * this config is omitted, no accesskey will be added.
3428 OO
.ui
.mixin
.AccessKeyedElement
= function OoUiMixinAccessKeyedElement( config
) {
3429 // Configuration initialization
3430 config
= config
|| {};
3433 this.$accessKeyed
= null;
3434 this.accessKey
= null;
3437 this.setAccessKey( config
.accessKey
|| null );
3438 this.setAccessKeyedElement( config
.$accessKeyed
|| this.$element
);
3440 // If this is also a TitledElement and it initialized before we did, we may have
3441 // to update the title with the access key
3442 if ( this.updateTitle
) {
3449 OO
.initClass( OO
.ui
.mixin
.AccessKeyedElement
);
3451 /* Static Properties */
3454 * The access key, a function that returns a key, or `null` for no accesskey.
3458 * @property {string|Function|null}
3460 OO
.ui
.mixin
.AccessKeyedElement
.static.accessKey
= null;
3465 * Set the accesskeyed element.
3467 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
3468 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
3470 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
3472 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKeyedElement = function ( $accessKeyed
) {
3473 if ( this.$accessKeyed
) {
3474 this.$accessKeyed
.removeAttr( 'accesskey' );
3477 this.$accessKeyed
= $accessKeyed
;
3478 if ( this.accessKey
) {
3479 this.$accessKeyed
.attr( 'accesskey', this.accessKey
);
3486 * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no accesskey
3489 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKey = function ( accessKey
) {
3490 accessKey
= typeof accessKey
=== 'string' ? OO
.ui
.resolveMsg( accessKey
) : null;
3492 if ( this.accessKey
!== accessKey
) {
3493 if ( this.$accessKeyed
) {
3494 if ( accessKey
!== null ) {
3495 this.$accessKeyed
.attr( 'accesskey', accessKey
);
3497 this.$accessKeyed
.removeAttr( 'accesskey' );
3500 this.accessKey
= accessKey
;
3502 // Only if this is a TitledElement
3503 if ( this.updateTitle
) {
3514 * @return {string} accessKey string
3516 OO
.ui
.mixin
.AccessKeyedElement
.prototype.getAccessKey = function () {
3517 return this.accessKey
;
3521 * Add information about the access key to the element's tooltip label.
3522 * (This is only public for hacky usage in FieldLayout.)
3524 * @param {string} title Tooltip label for `title` attribute
3527 OO
.ui
.mixin
.AccessKeyedElement
.prototype.formatTitleWithAccessKey = function ( title
) {
3530 if ( !this.$accessKeyed
) {
3531 // Not initialized yet; the constructor will call updateTitle() which will rerun this function
3534 // Use jquery.accessKeyLabel if available to show modifiers, otherwise just display the single key
3535 if ( $.fn
.updateTooltipAccessKeys
&& $.fn
.updateTooltipAccessKeys
.getAccessKeyLabel
) {
3536 accessKey
= $.fn
.updateTooltipAccessKeys
.getAccessKeyLabel( this.$accessKeyed
[ 0 ] );
3538 accessKey
= this.getAccessKey();
3541 title
+= ' [' + accessKey
+ ']';
3547 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3548 * feels, and functionality can be customized via the class’s configuration options
3549 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
3552 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
3555 * // A button widget
3556 * var button = new OO.ui.ButtonWidget( {
3557 * label: 'Button with Icon',
3559 * iconTitle: 'Remove'
3561 * $( 'body' ).append( button.$element );
3563 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3566 * @extends OO.ui.Widget
3567 * @mixins OO.ui.mixin.ButtonElement
3568 * @mixins OO.ui.mixin.IconElement
3569 * @mixins OO.ui.mixin.IndicatorElement
3570 * @mixins OO.ui.mixin.LabelElement
3571 * @mixins OO.ui.mixin.TitledElement
3572 * @mixins OO.ui.mixin.FlaggedElement
3573 * @mixins OO.ui.mixin.TabIndexedElement
3574 * @mixins OO.ui.mixin.AccessKeyedElement
3577 * @param {Object} [config] Configuration options
3578 * @cfg {boolean} [active=false] Whether button should be shown as active
3579 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3580 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3581 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3583 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
3584 // Configuration initialization
3585 config
= config
|| {};
3587 // Parent constructor
3588 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
3590 // Mixin constructors
3591 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
3592 OO
.ui
.mixin
.IconElement
.call( this, config
);
3593 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
3594 OO
.ui
.mixin
.LabelElement
.call( this, config
);
3595 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
3596 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
3597 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
3598 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$button
} ) );
3603 this.noFollow
= false;
3606 this.connect( this, { disable
: 'onDisable' } );
3609 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
3611 .addClass( 'oo-ui-buttonWidget' )
3612 .append( this.$button
);
3613 this.setActive( config
.active
);
3614 this.setHref( config
.href
);
3615 this.setTarget( config
.target
);
3616 this.setNoFollow( config
.noFollow
);
3621 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
3622 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
3623 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
3624 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
3625 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
3626 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
3627 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
3628 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
3629 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
3631 /* Static Properties */
3637 OO
.ui
.ButtonWidget
.static.cancelButtonMouseDownEvents
= false;
3643 OO
.ui
.ButtonWidget
.static.tagName
= 'span';
3648 * Get hyperlink location.
3650 * @return {string} Hyperlink location
3652 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
3657 * Get hyperlink target.
3659 * @return {string} Hyperlink target
3661 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
3666 * Get search engine traversal hint.
3668 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3670 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
3671 return this.noFollow
;
3675 * Set hyperlink location.
3677 * @param {string|null} href Hyperlink location, null to remove
3679 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
3680 href
= typeof href
=== 'string' ? href
: null;
3681 if ( href
!== null && !OO
.ui
.isSafeUrl( href
) ) {
3685 if ( href
!== this.href
) {
3694 * Update the `href` attribute, in case of changes to href or
3700 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
3701 if ( this.href
!== null && !this.isDisabled() ) {
3702 this.$button
.attr( 'href', this.href
);
3704 this.$button
.removeAttr( 'href' );
3711 * Handle disable events.
3714 * @param {boolean} disabled Element is disabled
3716 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
3721 * Set hyperlink target.
3723 * @param {string|null} target Hyperlink target, null to remove
3725 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
3726 target
= typeof target
=== 'string' ? target
: null;
3728 if ( target
!== this.target
) {
3729 this.target
= target
;
3730 if ( target
!== null ) {
3731 this.$button
.attr( 'target', target
);
3733 this.$button
.removeAttr( 'target' );
3741 * Set search engine traversal hint.
3743 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3745 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
3746 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
3748 if ( noFollow
!== this.noFollow
) {
3749 this.noFollow
= noFollow
;
3751 this.$button
.attr( 'rel', 'nofollow' );
3753 this.$button
.removeAttr( 'rel' );
3760 // Override method visibility hints from ButtonElement
3771 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3772 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3773 * removed, and cleared from the group.
3776 * // Example: A ButtonGroupWidget with two buttons
3777 * var button1 = new OO.ui.PopupButtonWidget( {
3778 * label: 'Select a category',
3781 * $content: $( '<p>List of categories...</p>' ),
3786 * var button2 = new OO.ui.ButtonWidget( {
3789 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
3790 * items: [button1, button2]
3792 * $( 'body' ).append( buttonGroup.$element );
3795 * @extends OO.ui.Widget
3796 * @mixins OO.ui.mixin.GroupElement
3799 * @param {Object} [config] Configuration options
3800 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
3802 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
3803 // Configuration initialization
3804 config
= config
|| {};
3806 // Parent constructor
3807 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
3809 // Mixin constructors
3810 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
3813 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
3814 if ( Array
.isArray( config
.items
) ) {
3815 this.addItems( config
.items
);
3821 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
3822 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
3824 /* Static Properties */
3830 OO
.ui
.ButtonGroupWidget
.static.tagName
= 'span';
3839 OO
.ui
.ButtonGroupWidget
.prototype.focus = function () {
3840 if ( !this.isDisabled() ) {
3841 if ( this.items
[ 0 ] ) {
3842 this.items
[ 0 ].focus();
3851 OO
.ui
.ButtonGroupWidget
.prototype.simulateLabelClick = function () {
3856 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
3857 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
3858 * for a list of icons included in the library.
3861 * // An icon widget with a label
3862 * var myIcon = new OO.ui.IconWidget( {
3866 * // Create a label.
3867 * var iconLabel = new OO.ui.LabelWidget( {
3870 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
3872 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
3875 * @extends OO.ui.Widget
3876 * @mixins OO.ui.mixin.IconElement
3877 * @mixins OO.ui.mixin.TitledElement
3878 * @mixins OO.ui.mixin.FlaggedElement
3881 * @param {Object} [config] Configuration options
3883 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
3884 // Configuration initialization
3885 config
= config
|| {};
3887 // Parent constructor
3888 OO
.ui
.IconWidget
.parent
.call( this, config
);
3890 // Mixin constructors
3891 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
3892 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
3893 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
3896 this.$element
.addClass( 'oo-ui-iconWidget' );
3901 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
3902 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
3903 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
3904 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
3906 /* Static Properties */
3912 OO
.ui
.IconWidget
.static.tagName
= 'span';
3915 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
3916 * attention to the status of an item or to clarify the function of a control. For a list of
3917 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
3920 * // Example of an indicator widget
3921 * var indicator1 = new OO.ui.IndicatorWidget( {
3922 * indicator: 'alert'
3925 * // Create a fieldset layout to add a label
3926 * var fieldset = new OO.ui.FieldsetLayout();
3927 * fieldset.addItems( [
3928 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
3930 * $( 'body' ).append( fieldset.$element );
3932 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3935 * @extends OO.ui.Widget
3936 * @mixins OO.ui.mixin.IndicatorElement
3937 * @mixins OO.ui.mixin.TitledElement
3940 * @param {Object} [config] Configuration options
3942 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
3943 // Configuration initialization
3944 config
= config
|| {};
3946 // Parent constructor
3947 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
3949 // Mixin constructors
3950 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
3951 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
3954 this.$element
.addClass( 'oo-ui-indicatorWidget' );
3959 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
3960 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
3961 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
3963 /* Static Properties */
3969 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
3972 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
3973 * be configured with a `label` option that is set to a string, a label node, or a function:
3975 * - String: a plaintext string
3976 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
3977 * label that includes a link or special styling, such as a gray color or additional graphical elements.
3978 * - Function: a function that will produce a string in the future. Functions are used
3979 * in cases where the value of the label is not currently defined.
3981 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
3982 * will come into focus when the label is clicked.
3985 * // Examples of LabelWidgets
3986 * var label1 = new OO.ui.LabelWidget( {
3987 * label: 'plaintext label'
3989 * var label2 = new OO.ui.LabelWidget( {
3990 * label: $( '<a href="default.html">jQuery label</a>' )
3992 * // Create a fieldset layout with fields for each example
3993 * var fieldset = new OO.ui.FieldsetLayout();
3994 * fieldset.addItems( [
3995 * new OO.ui.FieldLayout( label1 ),
3996 * new OO.ui.FieldLayout( label2 )
3998 * $( 'body' ).append( fieldset.$element );
4001 * @extends OO.ui.Widget
4002 * @mixins OO.ui.mixin.LabelElement
4003 * @mixins OO.ui.mixin.TitledElement
4006 * @param {Object} [config] Configuration options
4007 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
4008 * Clicking the label will focus the specified input field.
4010 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
4011 // Configuration initialization
4012 config
= config
|| {};
4014 // Parent constructor
4015 OO
.ui
.LabelWidget
.parent
.call( this, config
);
4017 // Mixin constructors
4018 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
4019 OO
.ui
.mixin
.TitledElement
.call( this, config
);
4022 this.input
= config
.input
;
4026 if ( this.input
.getInputId() ) {
4027 this.$element
.attr( 'for', this.input
.getInputId() );
4029 this.$label
.on( 'click', function () {
4030 this.input
.simulateLabelClick();
4035 this.$element
.addClass( 'oo-ui-labelWidget' );
4040 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
4041 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
4042 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
4044 /* Static Properties */
4050 OO
.ui
.LabelWidget
.static.tagName
= 'label';
4053 * PendingElement is a mixin that is used to create elements that notify users that something is happening
4054 * and that they should wait before proceeding. The pending state is visually represented with a pending
4055 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
4056 * field of a {@link OO.ui.TextInputWidget text input widget}.
4058 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
4059 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
4060 * in process dialogs.
4063 * function MessageDialog( config ) {
4064 * MessageDialog.parent.call( this, config );
4066 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
4068 * MessageDialog.static.name = 'myMessageDialog';
4069 * MessageDialog.static.actions = [
4070 * { action: 'save', label: 'Done', flags: 'primary' },
4071 * { label: 'Cancel', flags: 'safe' }
4074 * MessageDialog.prototype.initialize = function () {
4075 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
4076 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
4077 * this.content.$element.append( '<p>Click the \'Done\' action widget to see its pending state. Note that action widgets can be marked pending in message dialogs but not process dialogs.</p>' );
4078 * this.$body.append( this.content.$element );
4080 * MessageDialog.prototype.getBodyHeight = function () {
4083 * MessageDialog.prototype.getActionProcess = function ( action ) {
4084 * var dialog = this;
4085 * if ( action === 'save' ) {
4086 * dialog.getActions().get({actions: 'save'})[0].pushPending();
4087 * return new OO.ui.Process()
4089 * .next( function () {
4090 * dialog.getActions().get({actions: 'save'})[0].popPending();
4093 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
4096 * var windowManager = new OO.ui.WindowManager();
4097 * $( 'body' ).append( windowManager.$element );
4099 * var dialog = new MessageDialog();
4100 * windowManager.addWindows( [ dialog ] );
4101 * windowManager.openWindow( dialog );
4107 * @param {Object} [config] Configuration options
4108 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
4110 OO
.ui
.mixin
.PendingElement
= function OoUiMixinPendingElement( config
) {
4111 // Configuration initialization
4112 config
= config
|| {};
4116 this.$pending
= null;
4119 this.setPendingElement( config
.$pending
|| this.$element
);
4124 OO
.initClass( OO
.ui
.mixin
.PendingElement
);
4129 * Set the pending element (and clean up any existing one).
4131 * @param {jQuery} $pending The element to set to pending.
4133 OO
.ui
.mixin
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
4134 if ( this.$pending
) {
4135 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
4138 this.$pending
= $pending
;
4139 if ( this.pending
> 0 ) {
4140 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
4145 * Check if an element is pending.
4147 * @return {boolean} Element is pending
4149 OO
.ui
.mixin
.PendingElement
.prototype.isPending = function () {
4150 return !!this.pending
;
4154 * Increase the pending counter. The pending state will remain active until the counter is zero
4155 * (i.e., the number of calls to #pushPending and #popPending is the same).
4159 OO
.ui
.mixin
.PendingElement
.prototype.pushPending = function () {
4160 if ( this.pending
=== 0 ) {
4161 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
4162 this.updateThemeClasses();
4170 * Decrease the pending counter. The pending state will remain active until the counter is zero
4171 * (i.e., the number of calls to #pushPending and #popPending is the same).
4175 OO
.ui
.mixin
.PendingElement
.prototype.popPending = function () {
4176 if ( this.pending
=== 1 ) {
4177 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
4178 this.updateThemeClasses();
4180 this.pending
= Math
.max( 0, this.pending
- 1 );
4186 * Element that will stick adjacent to a specified container, even when it is inserted elsewhere
4187 * in the document (for example, in an OO.ui.Window's $overlay).
4189 * The elements's position is automatically calculated and maintained when window is resized or the
4190 * page is scrolled. If you reposition the container manually, you have to call #position to make
4191 * sure the element is still placed correctly.
4193 * As positioning is only possible when both the element and the container are attached to the DOM
4194 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
4195 * the #toggle method to display a floating popup, for example.
4201 * @param {Object} [config] Configuration options
4202 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
4203 * @cfg {jQuery} [$floatableContainer] Node to position adjacent to
4204 * @cfg {string} [verticalPosition='below'] Where to position $floatable vertically:
4205 * 'below': Directly below $floatableContainer, aligning f's top edge with fC's bottom edge
4206 * 'above': Directly above $floatableContainer, aligning f's bottom edge with fC's top edge
4207 * 'top': Align the top edge with $floatableContainer's top edge
4208 * 'bottom': Align the bottom edge with $floatableContainer's bottom edge
4209 * 'center': Vertically align the center with $floatableContainer's center
4210 * @cfg {string} [horizontalPosition='start'] Where to position $floatable horizontally:
4211 * 'before': Directly before $floatableContainer, aligning f's end edge with fC's start edge
4212 * 'after': Directly after $floatableContainer, algining f's start edge with fC's end edge
4213 * 'start': Align the start (left in LTR, right in RTL) edge with $floatableContainer's start edge
4214 * 'end': Align the end (right in LTR, left in RTL) edge with $floatableContainer's end edge
4215 * 'center': Horizontally align the center with $floatableContainer's center
4216 * @cfg {boolean} [hideWhenOutOfView=true] Whether to hide the floatable element if the container
4219 OO
.ui
.mixin
.FloatableElement
= function OoUiMixinFloatableElement( config
) {
4220 // Configuration initialization
4221 config
= config
|| {};
4224 this.$floatable
= null;
4225 this.$floatableContainer
= null;
4226 this.$floatableWindow
= null;
4227 this.$floatableClosestScrollable
= null;
4228 this.onFloatableScrollHandler
= this.position
.bind( this );
4229 this.onFloatableWindowResizeHandler
= this.position
.bind( this );
4232 this.setFloatableContainer( config
.$floatableContainer
);
4233 this.setFloatableElement( config
.$floatable
|| this.$element
);
4234 this.setVerticalPosition( config
.verticalPosition
|| 'below' );
4235 this.setHorizontalPosition( config
.horizontalPosition
|| 'start' );
4236 this.hideWhenOutOfView
= config
.hideWhenOutOfView
=== undefined ? true : !!config
.hideWhenOutOfView
;
4242 * Set floatable element.
4244 * If an element is already set, it will be cleaned up before setting up the new element.
4246 * @param {jQuery} $floatable Element to make floatable
4248 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableElement = function ( $floatable
) {
4249 if ( this.$floatable
) {
4250 this.$floatable
.removeClass( 'oo-ui-floatableElement-floatable' );
4251 this.$floatable
.css( { left
: '', top
: '' } );
4254 this.$floatable
= $floatable
.addClass( 'oo-ui-floatableElement-floatable' );
4259 * Set floatable container.
4261 * The element will be positioned relative to the specified container.
4263 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
4265 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableContainer = function ( $floatableContainer
) {
4266 this.$floatableContainer
= $floatableContainer
;
4267 if ( this.$floatable
) {
4273 * Change how the element is positioned vertically.
4275 * @param {string} position 'below', 'above', 'top', 'bottom' or 'center'
4277 OO
.ui
.mixin
.FloatableElement
.prototype.setVerticalPosition = function ( position
) {
4278 if ( [ 'below', 'above', 'top', 'bottom', 'center' ].indexOf( position
) === -1 ) {
4279 throw new Error( 'Invalid value for vertical position: ' + position
);
4281 if ( this.verticalPosition
!== position
) {
4282 this.verticalPosition
= position
;
4283 if ( this.$floatable
) {
4290 * Change how the element is positioned horizontally.
4292 * @param {string} position 'before', 'after', 'start', 'end' or 'center'
4294 OO
.ui
.mixin
.FloatableElement
.prototype.setHorizontalPosition = function ( position
) {
4295 if ( [ 'before', 'after', 'start', 'end', 'center' ].indexOf( position
) === -1 ) {
4296 throw new Error( 'Invalid value for horizontal position: ' + position
);
4298 if ( this.horizontalPosition
!== position
) {
4299 this.horizontalPosition
= position
;
4300 if ( this.$floatable
) {
4307 * Toggle positioning.
4309 * Do not turn positioning on until after the element is attached to the DOM and visible.
4311 * @param {boolean} [positioning] Enable positioning, omit to toggle
4314 OO
.ui
.mixin
.FloatableElement
.prototype.togglePositioning = function ( positioning
) {
4315 var closestScrollableOfContainer
;
4317 if ( !this.$floatable
|| !this.$floatableContainer
) {
4321 positioning
= positioning
=== undefined ? !this.positioning
: !!positioning
;
4323 if ( positioning
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4324 OO
.ui
.warnDeprecation( 'FloatableElement#togglePositioning: Before calling this method, the element must be attached to the DOM.' );
4325 this.warnedUnattached
= true;
4328 if ( this.positioning
!== positioning
) {
4329 this.positioning
= positioning
;
4331 this.needsCustomPosition
=
4332 this.verticalPostion
!== 'below' ||
4333 this.horizontalPosition
!== 'start' ||
4334 !OO
.ui
.contains( this.$floatableContainer
[ 0 ], this.$floatable
[ 0 ] );
4336 closestScrollableOfContainer
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatableContainer
[ 0 ] );
4337 // If the scrollable is the root, we have to listen to scroll events
4338 // on the window because of browser inconsistencies.
4339 if ( $( closestScrollableOfContainer
).is( 'html, body' ) ) {
4340 closestScrollableOfContainer
= OO
.ui
.Element
.static.getWindow( closestScrollableOfContainer
);
4343 if ( positioning
) {
4344 this.$floatableWindow
= $( this.getElementWindow() );
4345 this.$floatableWindow
.on( 'resize', this.onFloatableWindowResizeHandler
);
4347 this.$floatableClosestScrollable
= $( closestScrollableOfContainer
);
4348 this.$floatableClosestScrollable
.on( 'scroll', this.onFloatableScrollHandler
);
4350 // Initial position after visible
4353 if ( this.$floatableWindow
) {
4354 this.$floatableWindow
.off( 'resize', this.onFloatableWindowResizeHandler
);
4355 this.$floatableWindow
= null;
4358 if ( this.$floatableClosestScrollable
) {
4359 this.$floatableClosestScrollable
.off( 'scroll', this.onFloatableScrollHandler
);
4360 this.$floatableClosestScrollable
= null;
4363 this.$floatable
.css( { left
: '', right
: '', top
: '' } );
4371 * Check whether the bottom edge of the given element is within the viewport of the given container.
4374 * @param {jQuery} $element
4375 * @param {jQuery} $container
4378 OO
.ui
.mixin
.FloatableElement
.prototype.isElementInViewport = function ( $element
, $container
) {
4379 var elemRect
, contRect
, topEdgeInBounds
, bottomEdgeInBounds
, leftEdgeInBounds
, rightEdgeInBounds
,
4380 startEdgeInBounds
, endEdgeInBounds
,
4381 direction
= $element
.css( 'direction' );
4383 elemRect
= $element
[ 0 ].getBoundingClientRect();
4384 if ( $container
[ 0 ] === window
) {
4388 right
: document
.documentElement
.clientWidth
,
4389 bottom
: document
.documentElement
.clientHeight
4392 contRect
= $container
[ 0 ].getBoundingClientRect();
4395 topEdgeInBounds
= elemRect
.top
>= contRect
.top
&& elemRect
.top
<= contRect
.bottom
;
4396 bottomEdgeInBounds
= elemRect
.bottom
>= contRect
.top
&& elemRect
.bottom
<= contRect
.bottom
;
4397 leftEdgeInBounds
= elemRect
.left
>= contRect
.left
&& elemRect
.left
<= contRect
.right
;
4398 rightEdgeInBounds
= elemRect
.right
>= contRect
.left
&& elemRect
.right
<= contRect
.right
;
4399 if ( direction
=== 'rtl' ) {
4400 startEdgeInBounds
= rightEdgeInBounds
;
4401 endEdgeInBounds
= leftEdgeInBounds
;
4403 startEdgeInBounds
= leftEdgeInBounds
;
4404 endEdgeInBounds
= rightEdgeInBounds
;
4407 if ( this.verticalPosition
=== 'below' && !bottomEdgeInBounds
) {
4410 if ( this.verticalPosition
=== 'above' && !topEdgeInBounds
) {
4413 if ( this.horizontalPosition
=== 'before' && !startEdgeInBounds
) {
4416 if ( this.horizontalPosition
=== 'after' && !endEdgeInBounds
) {
4420 // The other positioning values are all about being inside the container,
4421 // so in those cases all we care about is that any part of the container is visible.
4422 return elemRect
.top
<= contRect
.bottom
&& elemRect
.bottom
>= contRect
.top
&&
4423 elemRect
.left
<= contRect
.right
&& elemRect
.right
>= contRect
.left
;
4427 * Position the floatable below its container.
4429 * This should only be done when both of them are attached to the DOM and visible.
4433 OO
.ui
.mixin
.FloatableElement
.prototype.position = function () {
4434 if ( !this.positioning
) {
4439 // To continue, some things need to be true:
4440 // The element must actually be in the DOM
4441 this.isElementAttached() && (
4442 // The closest scrollable is the current window
4443 this.$floatableClosestScrollable
[ 0 ] === this.getElementWindow() ||
4444 // OR is an element in the element's DOM
4445 $.contains( this.getElementDocument(), this.$floatableClosestScrollable
[ 0 ] )
4448 // Abort early if important parts of the widget are no longer attached to the DOM
4452 if ( this.hideWhenOutOfView
&& !this.isElementInViewport( this.$floatableContainer
, this.$floatableClosestScrollable
) ) {
4453 this.$floatable
.addClass( 'oo-ui-element-hidden' );
4456 this.$floatable
.removeClass( 'oo-ui-element-hidden' );
4459 if ( !this.needsCustomPosition
) {
4463 this.$floatable
.css( this.computePosition() );
4465 // We updated the position, so re-evaluate the clipping state.
4466 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
4467 // will not notice the need to update itself.)
4468 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
4469 // it not listen to the right events in the right places?
4478 * Compute how #$floatable should be positioned based on the position of #$floatableContainer
4479 * and the positioning settings. This is a helper for #position that shouldn't be called directly,
4480 * but may be overridden by subclasses if they want to change or add to the positioning logic.
4482 * @return {Object} New position to apply with .css(). Keys are 'top', 'left', 'bottom' and 'right'.
4484 OO
.ui
.mixin
.FloatableElement
.prototype.computePosition = function () {
4485 var isBody
, scrollableX
, scrollableY
, containerPos
,
4486 horizScrollbarHeight
, vertScrollbarWidth
, scrollTop
, scrollLeft
,
4487 newPos
= { top
: '', left
: '', bottom
: '', right
: '' },
4488 direction
= this.$floatableContainer
.css( 'direction' ),
4489 $offsetParent
= this.$floatable
.offsetParent();
4491 if ( $offsetParent
.is( 'html' ) ) {
4492 // The innerHeight/Width and clientHeight/Width calculations don't work well on the
4493 // <html> element, but they do work on the <body>
4494 $offsetParent
= $( $offsetParent
[ 0 ].ownerDocument
.body
);
4496 isBody
= $offsetParent
.is( 'body' );
4497 scrollableX
= $offsetParent
.css( 'overflow-x' ) === 'scroll' || $offsetParent
.css( 'overflow-x' ) === 'auto';
4498 scrollableY
= $offsetParent
.css( 'overflow-y' ) === 'scroll' || $offsetParent
.css( 'overflow-y' ) === 'auto';
4500 vertScrollbarWidth
= $offsetParent
.innerWidth() - $offsetParent
.prop( 'clientWidth' );
4501 horizScrollbarHeight
= $offsetParent
.innerHeight() - $offsetParent
.prop( 'clientHeight' );
4502 // We don't need to compute and add scrollTop and scrollLeft if the scrollable container is the body,
4503 // or if it isn't scrollable
4504 scrollTop
= scrollableY
&& !isBody
? $offsetParent
.scrollTop() : 0;
4505 scrollLeft
= scrollableX
&& !isBody
? OO
.ui
.Element
.static.getScrollLeft( $offsetParent
[ 0 ] ) : 0;
4507 // Avoid passing the <body> to getRelativePosition(), because it won't return what we expect
4508 // if the <body> has a margin
4509 containerPos
= isBody
?
4510 this.$floatableContainer
.offset() :
4511 OO
.ui
.Element
.static.getRelativePosition( this.$floatableContainer
, $offsetParent
);
4512 containerPos
.bottom
= containerPos
.top
+ this.$floatableContainer
.outerHeight();
4513 containerPos
.right
= containerPos
.left
+ this.$floatableContainer
.outerWidth();
4514 containerPos
.start
= direction
=== 'rtl' ? containerPos
.right
: containerPos
.left
;
4515 containerPos
.end
= direction
=== 'rtl' ? containerPos
.left
: containerPos
.right
;
4517 if ( this.verticalPosition
=== 'below' ) {
4518 newPos
.top
= containerPos
.bottom
;
4519 } else if ( this.verticalPosition
=== 'above' ) {
4520 newPos
.bottom
= $offsetParent
.outerHeight() - containerPos
.top
;
4521 } else if ( this.verticalPosition
=== 'top' ) {
4522 newPos
.top
= containerPos
.top
;
4523 } else if ( this.verticalPosition
=== 'bottom' ) {
4524 newPos
.bottom
= $offsetParent
.outerHeight() - containerPos
.bottom
;
4525 } else if ( this.verticalPosition
=== 'center' ) {
4526 newPos
.top
= containerPos
.top
+
4527 ( this.$floatableContainer
.height() - this.$floatable
.height() ) / 2;
4530 if ( this.horizontalPosition
=== 'before' ) {
4531 newPos
.end
= containerPos
.start
;
4532 } else if ( this.horizontalPosition
=== 'after' ) {
4533 newPos
.start
= containerPos
.end
;
4534 } else if ( this.horizontalPosition
=== 'start' ) {
4535 newPos
.start
= containerPos
.start
;
4536 } else if ( this.horizontalPosition
=== 'end' ) {
4537 newPos
.end
= containerPos
.end
;
4538 } else if ( this.horizontalPosition
=== 'center' ) {
4539 newPos
.left
= containerPos
.left
+
4540 ( this.$floatableContainer
.width() - this.$floatable
.width() ) / 2;
4543 if ( newPos
.start
!== undefined ) {
4544 if ( direction
=== 'rtl' ) {
4545 newPos
.right
= ( isBody
? $( $offsetParent
[ 0 ].ownerDocument
.documentElement
) : $offsetParent
).outerWidth() - newPos
.start
;
4547 newPos
.left
= newPos
.start
;
4549 delete newPos
.start
;
4551 if ( newPos
.end
!== undefined ) {
4552 if ( direction
=== 'rtl' ) {
4553 newPos
.left
= newPos
.end
;
4555 newPos
.right
= ( isBody
? $( $offsetParent
[ 0 ].ownerDocument
.documentElement
) : $offsetParent
).outerWidth() - newPos
.end
;
4560 // Account for scroll position
4561 if ( newPos
.top
!== '' ) {
4562 newPos
.top
+= scrollTop
;
4564 if ( newPos
.bottom
!== '' ) {
4565 newPos
.bottom
-= scrollTop
;
4567 if ( newPos
.left
!== '' ) {
4568 newPos
.left
+= scrollLeft
;
4570 if ( newPos
.right
!== '' ) {
4571 newPos
.right
-= scrollLeft
;
4574 // Account for scrollbar gutter
4575 if ( newPos
.bottom
!== '' ) {
4576 newPos
.bottom
-= horizScrollbarHeight
;
4578 if ( direction
=== 'rtl' ) {
4579 if ( newPos
.left
!== '' ) {
4580 newPos
.left
-= vertScrollbarWidth
;
4583 if ( newPos
.right
!== '' ) {
4584 newPos
.right
-= vertScrollbarWidth
;
4592 * Element that can be automatically clipped to visible boundaries.
4594 * Whenever the element's natural height changes, you have to call
4595 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
4596 * clipping correctly.
4598 * The dimensions of #$clippableContainer will be compared to the boundaries of the
4599 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
4600 * then #$clippable will be given a fixed reduced height and/or width and will be made
4601 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
4602 * but you can build a static footer by setting #$clippableContainer to an element that contains
4603 * #$clippable and the footer.
4609 * @param {Object} [config] Configuration options
4610 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
4611 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
4612 * omit to use #$clippable
4614 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
4615 // Configuration initialization
4616 config
= config
|| {};
4619 this.$clippable
= null;
4620 this.$clippableContainer
= null;
4621 this.clipping
= false;
4622 this.clippedHorizontally
= false;
4623 this.clippedVertically
= false;
4624 this.$clippableScrollableContainer
= null;
4625 this.$clippableScroller
= null;
4626 this.$clippableWindow
= null;
4627 this.idealWidth
= null;
4628 this.idealHeight
= null;
4629 this.onClippableScrollHandler
= this.clip
.bind( this );
4630 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
4633 if ( config
.$clippableContainer
) {
4634 this.setClippableContainer( config
.$clippableContainer
);
4636 this.setClippableElement( config
.$clippable
|| this.$element
);
4642 * Set clippable element.
4644 * If an element is already set, it will be cleaned up before setting up the new element.
4646 * @param {jQuery} $clippable Element to make clippable
4648 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
4649 if ( this.$clippable
) {
4650 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
4651 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
4652 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4655 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
4660 * Set clippable container.
4662 * This is the container that will be measured when deciding whether to clip. When clipping,
4663 * #$clippable will be resized in order to keep the clippable container fully visible.
4665 * If the clippable container is unset, #$clippable will be used.
4667 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
4669 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableContainer = function ( $clippableContainer
) {
4670 this.$clippableContainer
= $clippableContainer
;
4671 if ( this.$clippable
) {
4679 * Do not turn clipping on until after the element is attached to the DOM and visible.
4681 * @param {boolean} [clipping] Enable clipping, omit to toggle
4684 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
4685 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
4687 if ( clipping
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4688 OO
.ui
.warnDeprecation( 'ClippableElement#toggleClipping: Before calling this method, the element must be attached to the DOM.' );
4689 this.warnedUnattached
= true;
4692 if ( this.clipping
!== clipping
) {
4693 this.clipping
= clipping
;
4695 this.$clippableScrollableContainer
= $( this.getClosestScrollableElementContainer() );
4696 // If the clippable container is the root, we have to listen to scroll events and check
4697 // jQuery.scrollTop on the window because of browser inconsistencies
4698 this.$clippableScroller
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
4699 $( OO
.ui
.Element
.static.getWindow( this.$clippableScrollableContainer
) ) :
4700 this.$clippableScrollableContainer
;
4701 this.$clippableScroller
.on( 'scroll', this.onClippableScrollHandler
);
4702 this.$clippableWindow
= $( this.getElementWindow() )
4703 .on( 'resize', this.onClippableWindowResizeHandler
);
4704 // Initial clip after visible
4707 this.$clippable
.css( {
4715 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4717 this.$clippableScrollableContainer
= null;
4718 this.$clippableScroller
.off( 'scroll', this.onClippableScrollHandler
);
4719 this.$clippableScroller
= null;
4720 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
4721 this.$clippableWindow
= null;
4729 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4731 * @return {boolean} Element will be clipped to the visible area
4733 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
4734 return this.clipping
;
4738 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
4740 * @return {boolean} Part of the element is being clipped
4742 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
4743 return this.clippedHorizontally
|| this.clippedVertically
;
4747 * Check if the right of the element is being clipped by the nearest scrollable container.
4749 * @return {boolean} Part of the element is being clipped
4751 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
4752 return this.clippedHorizontally
;
4756 * Check if the bottom of the element is being clipped by the nearest scrollable container.
4758 * @return {boolean} Part of the element is being clipped
4760 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
4761 return this.clippedVertically
;
4765 * Set the ideal size. These are the dimensions #$clippable will have when it's not being clipped.
4767 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
4768 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
4770 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
4771 this.idealWidth
= width
;
4772 this.idealHeight
= height
;
4774 if ( !this.clipping
) {
4775 // Update dimensions
4776 this.$clippable
.css( { width
: width
, height
: height
} );
4778 // While clipping, idealWidth and idealHeight are not considered
4782 * Clip element to visible boundaries and allow scrolling when needed. You should call this method
4783 * when the element's natural height changes.
4785 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
4786 * overlapped by, the visible area of the nearest scrollable container.
4788 * Because calling clip() when the natural height changes isn't always possible, we also set
4789 * max-height when the element isn't being clipped. This means that if the element tries to grow
4790 * beyond the edge, something reasonable will happen before clip() is called.
4794 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
4795 var $container
, extraHeight
, extraWidth
, ccOffset
,
4796 $scrollableContainer
, scOffset
, scHeight
, scWidth
,
4797 ccWidth
, scrollerIsWindow
, scrollTop
, scrollLeft
,
4798 desiredWidth
, desiredHeight
, allotedWidth
, allotedHeight
,
4799 naturalWidth
, naturalHeight
, clipWidth
, clipHeight
,
4800 buffer
= 7; // Chosen by fair dice roll
4802 if ( !this.clipping
) {
4803 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
4807 $container
= this.$clippableContainer
|| this.$clippable
;
4808 extraHeight
= $container
.outerHeight() - this.$clippable
.outerHeight();
4809 extraWidth
= $container
.outerWidth() - this.$clippable
.outerWidth();
4810 ccOffset
= $container
.offset();
4811 if ( this.$clippableScrollableContainer
.is( 'html, body' ) ) {
4812 $scrollableContainer
= this.$clippableWindow
;
4813 scOffset
= { top
: 0, left
: 0 };
4815 $scrollableContainer
= this.$clippableScrollableContainer
;
4816 scOffset
= $scrollableContainer
.offset();
4818 scHeight
= $scrollableContainer
.innerHeight() - buffer
;
4819 scWidth
= $scrollableContainer
.innerWidth() - buffer
;
4820 ccWidth
= $container
.outerWidth() + buffer
;
4821 scrollerIsWindow
= this.$clippableScroller
[ 0 ] === this.$clippableWindow
[ 0 ];
4822 scrollTop
= scrollerIsWindow
? this.$clippableScroller
.scrollTop() : 0;
4823 scrollLeft
= scrollerIsWindow
? this.$clippableScroller
.scrollLeft() : 0;
4824 desiredWidth
= ccOffset
.left
< 0 ?
4825 ccWidth
+ ccOffset
.left
:
4826 ( scOffset
.left
+ scrollLeft
+ scWidth
) - ccOffset
.left
;
4827 desiredHeight
= ( scOffset
.top
+ scrollTop
+ scHeight
) - ccOffset
.top
;
4828 // It should never be desirable to exceed the dimensions of the browser viewport... right?
4829 desiredWidth
= Math
.min( desiredWidth
, document
.documentElement
.clientWidth
);
4830 desiredHeight
= Math
.min( desiredHeight
, document
.documentElement
.clientHeight
);
4831 allotedWidth
= Math
.ceil( desiredWidth
- extraWidth
);
4832 allotedHeight
= Math
.ceil( desiredHeight
- extraHeight
);
4833 naturalWidth
= this.$clippable
.prop( 'scrollWidth' );
4834 naturalHeight
= this.$clippable
.prop( 'scrollHeight' );
4835 clipWidth
= allotedWidth
< naturalWidth
;
4836 clipHeight
= allotedHeight
< naturalHeight
;
4839 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. See T157672.
4840 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
4841 this.$clippable
.css( 'overflowX', 'scroll' );
4842 void this.$clippable
[ 0 ].offsetHeight
; // Force reflow
4843 this.$clippable
.css( {
4844 width
: Math
.max( 0, allotedWidth
),
4848 this.$clippable
.css( {
4850 width
: this.idealWidth
|| '',
4851 maxWidth
: Math
.max( 0, allotedWidth
)
4855 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. See T157672.
4856 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
4857 this.$clippable
.css( 'overflowY', 'scroll' );
4858 void this.$clippable
[ 0 ].offsetHeight
; // Force reflow
4859 this.$clippable
.css( {
4860 height
: Math
.max( 0, allotedHeight
),
4864 this.$clippable
.css( {
4866 height
: this.idealHeight
|| '',
4867 maxHeight
: Math
.max( 0, allotedHeight
)
4871 // If we stopped clipping in at least one of the dimensions
4872 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
4873 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4876 this.clippedHorizontally
= clipWidth
;
4877 this.clippedVertically
= clipHeight
;
4883 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
4884 * By default, each popup has an anchor that points toward its origin.
4885 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
4887 * Unlike most widgets, PopupWidget is initially hidden and must be shown by calling #toggle.
4890 * // A popup widget.
4891 * var popup = new OO.ui.PopupWidget( {
4892 * $content: $( '<p>Hi there!</p>' ),
4897 * $( 'body' ).append( popup.$element );
4898 * // To display the popup, toggle the visibility to 'true'.
4899 * popup.toggle( true );
4901 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
4904 * @extends OO.ui.Widget
4905 * @mixins OO.ui.mixin.LabelElement
4906 * @mixins OO.ui.mixin.ClippableElement
4907 * @mixins OO.ui.mixin.FloatableElement
4910 * @param {Object} [config] Configuration options
4911 * @cfg {number} [width=320] Width of popup in pixels
4912 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
4913 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
4914 * @cfg {string} [position='below'] Where to position the popup relative to $floatableContainer
4915 * 'above': Put popup above $floatableContainer; anchor points down to the horizontal center
4916 * of $floatableContainer
4917 * 'below': Put popup below $floatableContainer; anchor points up to the horizontal center
4918 * of $floatableContainer
4919 * 'before': Put popup to the left (LTR) / right (RTL) of $floatableContainer; anchor points
4920 * endwards (right/left) to the vertical center of $floatableContainer
4921 * 'after': Put popup to the right (LTR) / left (RTL) of $floatableContainer; anchor points
4922 * startwards (left/right) to the vertical center of $floatableContainer
4923 * @cfg {string} [align='center'] How to align the popup to $floatableContainer
4924 * 'forwards': If position is above/below, move the popup as far endwards (right in LTR, left in RTL)
4925 * as possible while still keeping the anchor within the popup;
4926 * if position is before/after, move the popup as far downwards as possible.
4927 * 'backwards': If position is above/below, move the popup as far startwards (left in LTR, right in RTL)
4928 * as possible while still keeping the anchor within the popup;
4929 * if position in before/after, move the popup as far upwards as possible.
4930 * 'center': Horizontally (if position is above/below) or vertically (before/after) align the center
4931 * of the popup with the center of $floatableContainer.
4932 * 'force-left': Alias for 'forwards' in LTR and 'backwards' in RTL
4933 * 'force-right': Alias for 'backwards' in RTL and 'forwards' in LTR
4934 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
4935 * See the [OOjs UI docs on MediaWiki][3] for an example.
4936 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
4937 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
4938 * @cfg {jQuery} [$content] Content to append to the popup's body
4939 * @cfg {jQuery} [$footer] Content to append to the popup's footer
4940 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
4941 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
4942 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
4944 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
4945 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
4947 * @cfg {boolean} [padded=false] Add padding to the popup's body
4949 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
4950 // Configuration initialization
4951 config
= config
|| {};
4953 // Parent constructor
4954 OO
.ui
.PopupWidget
.parent
.call( this, config
);
4956 // Properties (must be set before ClippableElement constructor call)
4957 this.$body
= $( '<div>' );
4958 this.$popup
= $( '<div>' );
4960 // Mixin constructors
4961 OO
.ui
.mixin
.LabelElement
.call( this, config
);
4962 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, {
4963 $clippable
: this.$body
,
4964 $clippableContainer
: this.$popup
4966 OO
.ui
.mixin
.FloatableElement
.call( this, config
);
4969 this.$anchor
= $( '<div>' );
4970 // If undefined, will be computed lazily in computePosition()
4971 this.$container
= config
.$container
;
4972 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
4973 this.autoClose
= !!config
.autoClose
;
4974 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
4975 this.transitionTimeout
= null;
4976 this.anchored
= false;
4977 this.width
= config
.width
!== undefined ? config
.width
: 320;
4978 this.height
= config
.height
!== undefined ? config
.height
: null;
4979 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
4980 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
4983 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
4984 this.setAlignment( config
.align
|| 'center' );
4985 this.setPosition( config
.position
|| 'below' );
4986 this.$body
.addClass( 'oo-ui-popupWidget-body' );
4987 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
4989 .addClass( 'oo-ui-popupWidget-popup' )
4990 .append( this.$body
);
4992 .addClass( 'oo-ui-popupWidget' )
4993 .append( this.$popup
, this.$anchor
);
4994 // Move content, which was added to #$element by OO.ui.Widget, to the body
4995 // FIXME This is gross, we should use '$body' or something for the config
4996 if ( config
.$content
instanceof jQuery
) {
4997 this.$body
.append( config
.$content
);
5000 if ( config
.padded
) {
5001 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
5004 if ( config
.head
) {
5005 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
5006 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
5007 this.$head
= $( '<div>' )
5008 .addClass( 'oo-ui-popupWidget-head' )
5009 .append( this.$label
, this.closeButton
.$element
);
5010 this.$popup
.prepend( this.$head
);
5013 if ( config
.$footer
) {
5014 this.$footer
= $( '<div>' )
5015 .addClass( 'oo-ui-popupWidget-footer' )
5016 .append( config
.$footer
);
5017 this.$popup
.append( this.$footer
);
5020 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
5021 // that reference properties not initialized at that time of parent class construction
5022 // TODO: Find a better way to handle post-constructor setup
5023 this.visible
= false;
5024 this.$element
.addClass( 'oo-ui-element-hidden' );
5029 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
5030 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
5031 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
5032 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.FloatableElement
);
5039 * The popup is ready: it is visible and has been positioned and clipped.
5045 * Handles mouse down events.
5048 * @param {MouseEvent} e Mouse down event
5050 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
5053 !OO
.ui
.contains( this.$element
.add( this.$autoCloseIgnore
).get(), e
.target
, true )
5055 this.toggle( false );
5060 * Bind mouse down listener.
5064 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
5065 // Capture clicks outside popup
5066 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler
, true );
5070 * Handles close button click events.
5074 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
5075 if ( this.isVisible() ) {
5076 this.toggle( false );
5081 * Unbind mouse down listener.
5085 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
5086 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler
, true );
5090 * Handles key down events.
5093 * @param {KeyboardEvent} e Key down event
5095 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
5097 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
5100 this.toggle( false );
5102 e
.stopPropagation();
5107 * Bind key down listener.
5111 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
5112 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
5116 * Unbind key down listener.
5120 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
5121 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
5125 * Show, hide, or toggle the visibility of the anchor.
5127 * @param {boolean} [show] Show anchor, omit to toggle
5129 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
5130 show
= show
=== undefined ? !this.anchored
: !!show
;
5132 if ( this.anchored
!== show
) {
5134 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
5135 this.$element
.addClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5137 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
5138 this.$element
.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5140 this.anchored
= show
;
5144 * Change which edge the anchor appears on.
5146 * @param {string} edge 'top', 'bottom', 'start' or 'end'
5148 OO
.ui
.PopupWidget
.prototype.setAnchorEdge = function ( edge
) {
5149 if ( [ 'top', 'bottom', 'start', 'end' ].indexOf( edge
) === -1 ) {
5150 throw new Error( 'Invalid value for edge: ' + edge
);
5152 if ( this.anchorEdge
!== null ) {
5153 this.$element
.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5155 this.anchorEdge
= edge
;
5156 if ( this.anchored
) {
5157 this.$element
.addClass( 'oo-ui-popupWidget-anchored-' + edge
);
5162 * Check if the anchor is visible.
5164 * @return {boolean} Anchor is visible
5166 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
5167 return this.anchored
;
5171 * Toggle visibility of the popup. The popup is initially hidden and must be shown by calling
5172 * `.toggle( true )` after its #$element is attached to the DOM.
5174 * Do not show the popup while it is not attached to the DOM. The calculations required to display
5175 * it in the right place and with the right dimensions only work correctly while it is attached.
5176 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
5177 * strictly enforced, so currently it only generates a warning in the browser console.
5182 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
5184 show
= show
=== undefined ? !this.isVisible() : !!show
;
5186 change
= show
!== this.isVisible();
5188 if ( show
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
5189 OO
.ui
.warnDeprecation( 'PopupWidget#toggle: Before calling this method, the popup must be attached to the DOM.' );
5190 this.warnedUnattached
= true;
5192 if ( show
&& !this.$floatableContainer
&& this.isElementAttached() ) {
5193 // Fall back to the parent node if the floatableContainer is not set
5194 this.setFloatableContainer( this.$element
.parent() );
5198 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
5201 this.togglePositioning( show
&& !!this.$floatableContainer
);
5204 if ( this.autoClose
) {
5205 this.bindMouseDownListener();
5206 this.bindKeyDownListener();
5208 this.updateDimensions();
5209 this.toggleClipping( true );
5210 this.emit( 'ready' );
5212 this.toggleClipping( false );
5213 if ( this.autoClose
) {
5214 this.unbindMouseDownListener();
5215 this.unbindKeyDownListener();
5224 * Set the size of the popup.
5226 * Changing the size may also change the popup's position depending on the alignment.
5228 * @param {number} width Width in pixels
5229 * @param {number} height Height in pixels
5230 * @param {boolean} [transition=false] Use a smooth transition
5233 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
5235 this.height
= height
!== undefined ? height
: null;
5236 if ( this.isVisible() ) {
5237 this.updateDimensions( transition
);
5242 * Update the size and position.
5244 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
5245 * be called automatically.
5247 * @param {boolean} [transition=false] Use a smooth transition
5250 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
5253 // Prevent transition from being interrupted
5254 clearTimeout( this.transitionTimeout
);
5256 // Enable transition
5257 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
5263 // Prevent transitioning after transition is complete
5264 this.transitionTimeout
= setTimeout( function () {
5265 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
5268 // Prevent transitioning immediately
5269 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
5276 OO
.ui
.PopupWidget
.prototype.computePosition = function () {
5277 var direction
, align
, vertical
, start
, end
, near
, far
, sizeProp
, popupSize
, anchorSize
, anchorPos
,
5278 anchorOffset
, anchorMargin
, parentPosition
, positionProp
, positionAdjustment
, floatablePos
,
5279 offsetParentPos
, containerPos
,
5281 anchorCss
= { left
: '', right
: '', top
: '', bottom
: '' },
5284 'force-left': 'backwards',
5285 'force-right': 'forwards'
5288 'force-left': 'forwards',
5289 'force-right': 'backwards'
5301 backwards
: this.anchored
? 'before' : 'end'
5309 if ( !this.$container
) {
5310 // Lazy-initialize $container if not specified in constructor
5311 this.$container
= $( this.getClosestScrollableElementContainer() );
5313 direction
= this.$container
.css( 'direction' );
5315 // Set height and width before we do anything else, since it might cause our measurements
5316 // to change (e.g. due to scrollbars appearing or disappearing), and it also affects centering
5319 height
: this.height
!== null ? this.height
: 'auto'
5322 align
= alignMap
[ direction
][ this.align
] || this.align
;
5323 // If the popup is positioned before or after, then the anchor positioning is vertical, otherwise horizontal
5324 vertical
= this.popupPosition
=== 'before' || this.popupPosition
=== 'after';
5325 start
= vertical
? 'top' : ( direction
=== 'rtl' ? 'right' : 'left' );
5326 end
= vertical
? 'bottom' : ( direction
=== 'rtl' ? 'left' : 'right' );
5327 near
= vertical
? 'top' : 'left';
5328 far
= vertical
? 'bottom' : 'right';
5329 sizeProp
= vertical
? 'Height' : 'Width';
5330 popupSize
= vertical
? ( this.height
|| this.$popup
.height() ) : this.width
;
5332 this.setAnchorEdge( anchorEdgeMap
[ this.popupPosition
] );
5333 this.horizontalPosition
= vertical
? this.popupPosition
: hPosMap
[ align
];
5334 this.verticalPosition
= vertical
? vPosMap
[ align
] : this.popupPosition
;
5337 parentPosition
= OO
.ui
.mixin
.FloatableElement
.prototype.computePosition
.call( this );
5338 // Find out which property FloatableElement used for positioning, and adjust that value
5339 positionProp
= vertical
?
5340 ( parentPosition
.top
!== '' ? 'top' : 'bottom' ) :
5341 ( parentPosition
.left
!== '' ? 'left' : 'right' );
5343 // Figure out where the near and far edges of the popup and $floatableContainer are
5344 floatablePos
= this.$floatableContainer
.offset();
5345 floatablePos
[ far
] = floatablePos
[ near
] + this.$floatableContainer
[ 'outer' + sizeProp
]();
5346 // Measure where the offsetParent is and compute our position based on that and parentPosition
5347 offsetParentPos
= this.$element
.offsetParent().offset();
5349 if ( positionProp
=== near
) {
5350 popupPos
[ near
] = offsetParentPos
[ near
] + parentPosition
[ near
];
5351 popupPos
[ far
] = popupPos
[ near
] + popupSize
;
5353 popupPos
[ far
] = offsetParentPos
[ near
] +
5354 this.$element
.offsetParent()[ 'inner' + sizeProp
]() - parentPosition
[ far
];
5355 popupPos
[ near
] = popupPos
[ far
] - popupSize
;
5358 if ( this.anchored
) {
5359 // Position the anchor (which is positioned relative to the popup) to point to $floatableContainer
5360 anchorPos
= ( floatablePos
[ start
] + floatablePos
[ end
] ) / 2;
5361 anchorOffset
= ( start
=== far
? -1 : 1 ) * ( anchorPos
- popupPos
[ start
] );
5363 // If the anchor is less than 2*anchorSize from either edge, move the popup to make more space
5364 // this.$anchor.width()/height() returns 0 because of the CSS trickery we use, so use scrollWidth/Height
5365 anchorSize
= this.$anchor
[ 0 ][ 'scroll' + sizeProp
];
5366 anchorMargin
= parseFloat( this.$anchor
.css( 'margin-' + start
) );
5367 if ( anchorOffset
+ anchorMargin
< 2 * anchorSize
) {
5368 // Not enough space for the anchor on the start side; pull the popup startwards
5369 positionAdjustment
= ( positionProp
=== start
? -1 : 1 ) *
5370 ( 2 * anchorSize
- ( anchorOffset
+ anchorMargin
) );
5371 } else if ( anchorOffset
+ anchorMargin
> popupSize
- 2 * anchorSize
) {
5372 // Not enough space for the anchor on the end side; pull the popup endwards
5373 positionAdjustment
= ( positionProp
=== end
? -1 : 1 ) *
5374 ( anchorOffset
+ anchorMargin
- ( popupSize
- 2 * anchorSize
) );
5376 positionAdjustment
= 0;
5379 positionAdjustment
= 0;
5382 // Check if the popup will go beyond the edge of this.$container
5383 containerPos
= this.$container
.offset();
5384 containerPos
[ far
] = containerPos
[ near
] + this.$container
[ 'inner' + sizeProp
]();
5385 // Take into account how much the popup will move because of the adjustments we're going to make
5386 popupPos
[ near
] += ( positionProp
=== near
? 1 : -1 ) * positionAdjustment
;
5387 popupPos
[ far
] += ( positionProp
=== near
? 1 : -1 ) * positionAdjustment
;
5388 if ( containerPos
[ near
] + this.containerPadding
> popupPos
[ near
] ) {
5389 // Popup goes beyond the near (left/top) edge, move it to the right/bottom
5390 positionAdjustment
+= ( positionProp
=== near
? 1 : -1 ) *
5391 ( containerPos
[ near
] + this.containerPadding
- popupPos
[ near
] );
5392 } else if ( containerPos
[ far
] - this.containerPadding
< popupPos
[ far
] ) {
5393 // Popup goes beyond the far (right/bottom) edge, move it to the left/top
5394 positionAdjustment
+= ( positionProp
=== far
? 1 : -1 ) *
5395 ( popupPos
[ far
] - ( containerPos
[ far
] - this.containerPadding
) );
5398 if ( this.anchored
) {
5399 // Adjust anchorOffset for positionAdjustment
5400 anchorOffset
+= ( positionProp
=== start
? -1 : 1 ) * positionAdjustment
;
5402 // Position the anchor
5403 anchorCss
[ start
] = anchorOffset
;
5404 this.$anchor
.css( anchorCss
);
5407 // Move the popup if needed
5408 parentPosition
[ positionProp
] += positionAdjustment
;
5410 return parentPosition
;
5414 * Set popup alignment
5416 * @param {string} [align=center] Alignment of the popup, `center`, `force-left`, `force-right`,
5417 * `backwards` or `forwards`.
5419 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
5420 // Validate alignment
5421 if ( [ 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
5424 this.align
= 'center';
5430 * Get popup alignment
5432 * @return {string} Alignment of the popup, `center`, `force-left`, `force-right`,
5433 * `backwards` or `forwards`.
5435 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
5440 * Change the positioning of the popup.
5442 * @param {string} position 'above', 'below', 'before' or 'after'
5444 OO
.ui
.PopupWidget
.prototype.setPosition = function ( position
) {
5445 if ( [ 'above', 'below', 'before', 'after' ].indexOf( position
) === -1 ) {
5448 this.popupPosition
= position
;
5453 * Get popup positioning.
5455 * @return {string} 'above', 'below', 'before' or 'after'
5457 OO
.ui
.PopupWidget
.prototype.getPosition = function () {
5458 return this.popupPosition
;
5462 * Get an ID of the body element, this can be used as the
5463 * `aria-describedby` attribute for an input field.
5465 * @return {string} The ID of the body element
5467 OO
.ui
.PopupWidget
.prototype.getBodyId = function () {
5468 var id
= this.$body
.attr( 'id' );
5469 if ( id
=== undefined ) {
5470 id
= OO
.ui
.generateElementId();
5471 this.$body
.attr( 'id', id
);
5477 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5478 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5479 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5480 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5486 * @param {Object} [config] Configuration options
5487 * @cfg {Object} [popup] Configuration to pass to popup
5488 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5490 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
5491 // Configuration initialization
5492 config
= config
|| {};
5495 this.popup
= new OO
.ui
.PopupWidget( $.extend(
5498 $floatableContainer
: this.$element
5502 $autoCloseIgnore
: this.$element
.add( config
.popup
&& config
.popup
.$autoCloseIgnore
)
5512 * @return {OO.ui.PopupWidget} Popup widget
5514 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
5519 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
5520 * which is used to display additional information or options.
5523 * // Example of a popup button.
5524 * var popupButton = new OO.ui.PopupButtonWidget( {
5525 * label: 'Popup button with options',
5528 * $content: $( '<p>Additional options here.</p>' ),
5530 * align: 'force-left'
5533 * // Append the button to the DOM.
5534 * $( 'body' ).append( popupButton.$element );
5537 * @extends OO.ui.ButtonWidget
5538 * @mixins OO.ui.mixin.PopupElement
5541 * @param {Object} [config] Configuration options
5542 * @cfg {jQuery} [$overlay] Render the popup into a separate layer. This configuration is useful in cases where
5543 * the expanded popup is larger than its containing `<div>`. The specified overlay layer is usually on top of the
5544 * containing `<div>` and has a larger area. By default, the popup uses relative positioning.
5545 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
5547 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
5548 // Configuration initialization
5549 config
= config
|| {};
5551 // Parent constructor
5552 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
5554 // Mixin constructors
5555 OO
.ui
.mixin
.PopupElement
.call( this, config
);
5558 this.$overlay
= config
.$overlay
|| this.$element
;
5561 this.connect( this, { click
: 'onAction' } );
5565 .addClass( 'oo-ui-popupButtonWidget' )
5566 .attr( 'aria-haspopup', 'true' );
5568 .addClass( 'oo-ui-popupButtonWidget-popup' )
5569 .toggleClass( 'oo-ui-popupButtonWidget-framed-popup', this.isFramed() )
5570 .toggleClass( 'oo-ui-popupButtonWidget-frameless-popup', !this.isFramed() );
5571 this.$overlay
.append( this.popup
.$element
);
5576 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
5577 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
5582 * Handle the button action being triggered.
5586 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
5587 this.popup
.toggle();
5591 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
5593 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
5598 * @mixins OO.ui.mixin.GroupElement
5601 * @param {Object} [config] Configuration options
5603 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
5604 // Mixin constructors
5605 OO
.ui
.mixin
.GroupElement
.call( this, config
);
5610 OO
.mixinClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
5615 * Set the disabled state of the widget.
5617 * This will also update the disabled state of child widgets.
5619 * @param {boolean} disabled Disable widget
5622 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
5626 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
5627 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
5629 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
5631 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5632 this.items
[ i
].updateDisabled();
5640 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
5642 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
5643 * allows bidirectional communication.
5645 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
5653 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
5660 * Check if widget is disabled.
5662 * Checks parent if present, making disabled state inheritable.
5664 * @return {boolean} Widget is disabled
5666 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
5667 return this.disabled
||
5668 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
5672 * Set group element is in.
5674 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
5677 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
5679 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
5680 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
5682 // Initialize item disabled states
5683 this.updateDisabled();
5689 * OptionWidgets are special elements that can be selected and configured with data. The
5690 * data is often unique for each option, but it does not have to be. OptionWidgets are used
5691 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
5692 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
5694 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5697 * @extends OO.ui.Widget
5698 * @mixins OO.ui.mixin.ItemWidget
5699 * @mixins OO.ui.mixin.LabelElement
5700 * @mixins OO.ui.mixin.FlaggedElement
5701 * @mixins OO.ui.mixin.AccessKeyedElement
5704 * @param {Object} [config] Configuration options
5706 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
5707 // Configuration initialization
5708 config
= config
|| {};
5710 // Parent constructor
5711 OO
.ui
.OptionWidget
.parent
.call( this, config
);
5713 // Mixin constructors
5714 OO
.ui
.mixin
.ItemWidget
.call( this );
5715 OO
.ui
.mixin
.LabelElement
.call( this, config
);
5716 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
5717 OO
.ui
.mixin
.AccessKeyedElement
.call( this, config
);
5720 this.selected
= false;
5721 this.highlighted
= false;
5722 this.pressed
= false;
5726 .data( 'oo-ui-optionWidget', this )
5727 // Allow programmatic focussing (and by accesskey), but not tabbing
5728 .attr( 'tabindex', '-1' )
5729 .attr( 'role', 'option' )
5730 .attr( 'aria-selected', 'false' )
5731 .addClass( 'oo-ui-optionWidget' )
5732 .append( this.$label
);
5737 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
5738 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
5739 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
5740 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
5741 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
5743 /* Static Properties */
5746 * Whether this option can be selected. See #setSelected.
5750 * @property {boolean}
5752 OO
.ui
.OptionWidget
.static.selectable
= true;
5755 * Whether this option can be highlighted. See #setHighlighted.
5759 * @property {boolean}
5761 OO
.ui
.OptionWidget
.static.highlightable
= true;
5764 * Whether this option can be pressed. See #setPressed.
5768 * @property {boolean}
5770 OO
.ui
.OptionWidget
.static.pressable
= true;
5773 * Whether this option will be scrolled into view when it is selected.
5777 * @property {boolean}
5779 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
5784 * Check if the option can be selected.
5786 * @return {boolean} Item is selectable
5788 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
5789 return this.constructor.static.selectable
&& !this.isDisabled() && this.isVisible();
5793 * Check if the option can be highlighted. A highlight indicates that the option
5794 * may be selected when a user presses enter or clicks. Disabled items cannot
5797 * @return {boolean} Item is highlightable
5799 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
5800 return this.constructor.static.highlightable
&& !this.isDisabled() && this.isVisible();
5804 * Check if the option can be pressed. The pressed state occurs when a user mouses
5805 * down on an item, but has not yet let go of the mouse.
5807 * @return {boolean} Item is pressable
5809 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
5810 return this.constructor.static.pressable
&& !this.isDisabled() && this.isVisible();
5814 * Check if the option is selected.
5816 * @return {boolean} Item is selected
5818 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
5819 return this.selected
;
5823 * Check if the option is highlighted. A highlight indicates that the
5824 * item may be selected when a user presses enter or clicks.
5826 * @return {boolean} Item is highlighted
5828 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
5829 return this.highlighted
;
5833 * Check if the option is pressed. The pressed state occurs when a user mouses
5834 * down on an item, but has not yet let go of the mouse. The item may appear
5835 * selected, but it will not be selected until the user releases the mouse.
5837 * @return {boolean} Item is pressed
5839 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
5840 return this.pressed
;
5844 * Set the option’s selected state. In general, all modifications to the selection
5845 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
5846 * method instead of this method.
5848 * @param {boolean} [state=false] Select option
5851 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
5852 if ( this.constructor.static.selectable
) {
5853 this.selected
= !!state
;
5855 .toggleClass( 'oo-ui-optionWidget-selected', state
)
5856 .attr( 'aria-selected', state
.toString() );
5857 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
5858 this.scrollElementIntoView();
5860 this.updateThemeClasses();
5866 * Set the option’s highlighted state. In general, all programmatic
5867 * modifications to the highlight should be handled by the
5868 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
5869 * method instead of this method.
5871 * @param {boolean} [state=false] Highlight option
5874 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
5875 if ( this.constructor.static.highlightable
) {
5876 this.highlighted
= !!state
;
5877 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
5878 this.updateThemeClasses();
5884 * Set the option’s pressed state. In general, all
5885 * programmatic modifications to the pressed state should be handled by the
5886 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
5887 * method instead of this method.
5889 * @param {boolean} [state=false] Press option
5892 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
5893 if ( this.constructor.static.pressable
) {
5894 this.pressed
= !!state
;
5895 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
5896 this.updateThemeClasses();
5902 * Get text to match search strings against.
5904 * The default implementation returns the label text, but subclasses
5905 * can override this to provide more complex behavior.
5907 * @return {string|boolean} String to match search string against
5909 OO
.ui
.OptionWidget
.prototype.getMatchText = function () {
5910 var label
= this.getLabel();
5911 return typeof label
=== 'string' ? label
: this.$label
.text();
5915 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
5916 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
5917 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
5920 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
5921 * information, please see the [OOjs UI documentation on MediaWiki][1].
5924 * // Example of a select widget with three options
5925 * var select = new OO.ui.SelectWidget( {
5927 * new OO.ui.OptionWidget( {
5929 * label: 'Option One',
5931 * new OO.ui.OptionWidget( {
5933 * label: 'Option Two',
5935 * new OO.ui.OptionWidget( {
5937 * label: 'Option Three',
5941 * $( 'body' ).append( select.$element );
5943 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5947 * @extends OO.ui.Widget
5948 * @mixins OO.ui.mixin.GroupWidget
5951 * @param {Object} [config] Configuration options
5952 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
5953 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
5954 * the [OOjs UI documentation on MediaWiki] [2] for examples.
5955 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5957 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
5958 // Configuration initialization
5959 config
= config
|| {};
5961 // Parent constructor
5962 OO
.ui
.SelectWidget
.parent
.call( this, config
);
5964 // Mixin constructors
5965 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
5968 this.pressed
= false;
5969 this.selecting
= null;
5970 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
5971 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
5972 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
5973 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
5974 this.keyPressBuffer
= '';
5975 this.keyPressBufferTimer
= null;
5976 this.blockMouseOverEvents
= 0;
5979 this.connect( this, {
5983 focusin
: this.onFocus
.bind( this ),
5984 mousedown
: this.onMouseDown
.bind( this ),
5985 mouseover
: this.onMouseOver
.bind( this ),
5986 mouseleave
: this.onMouseLeave
.bind( this )
5991 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
5992 .attr( 'role', 'listbox' );
5993 this.setFocusOwner( this.$element
);
5994 if ( Array
.isArray( config
.items
) ) {
5995 this.addItems( config
.items
);
6001 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
6002 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
6009 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
6011 * @param {OO.ui.OptionWidget|null} item Highlighted item
6017 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
6018 * pressed state of an option.
6020 * @param {OO.ui.OptionWidget|null} item Pressed item
6026 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
6028 * @param {OO.ui.OptionWidget|null} item Selected item
6033 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
6034 * @param {OO.ui.OptionWidget} item Chosen item
6040 * An `add` event is emitted when options are added to the select with the #addItems method.
6042 * @param {OO.ui.OptionWidget[]} items Added items
6043 * @param {number} index Index of insertion point
6049 * A `remove` event is emitted when options are removed from the select with the #clearItems
6050 * or #removeItems methods.
6052 * @param {OO.ui.OptionWidget[]} items Removed items
6058 * Handle focus events
6061 * @param {jQuery.Event} event
6063 OO
.ui
.SelectWidget
.prototype.onFocus = function ( event
) {
6065 if ( event
.target
=== this.$element
[ 0 ] ) {
6066 // This widget was focussed, e.g. by the user tabbing to it.
6067 // The styles for focus state depend on one of the items being selected.
6068 if ( !this.getSelectedItem() ) {
6069 item
= this.getFirstSelectableItem();
6072 // One of the options got focussed (and the event bubbled up here).
6073 // They can't be tabbed to, but they can be activated using accesskeys.
6074 item
= this.getTargetItem( event
);
6078 if ( item
.constructor.static.highlightable
) {
6079 this.highlightItem( item
);
6081 this.selectItem( item
);
6085 if ( event
.target
!== this.$element
[ 0 ] ) {
6086 this.$focusOwner
.focus();
6091 * Handle mouse down events.
6094 * @param {jQuery.Event} e Mouse down event
6096 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
6099 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
6100 this.togglePressed( true );
6101 item
= this.getTargetItem( e
);
6102 if ( item
&& item
.isSelectable() ) {
6103 this.pressItem( item
);
6104 this.selecting
= item
;
6105 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
6106 this.getElementDocument().addEventListener( 'mousemove', this.onMouseMoveHandler
, true );
6113 * Handle mouse up events.
6116 * @param {MouseEvent} e Mouse up event
6118 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
6121 this.togglePressed( false );
6122 if ( !this.selecting
) {
6123 item
= this.getTargetItem( e
);
6124 if ( item
&& item
.isSelectable() ) {
6125 this.selecting
= item
;
6128 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
&& this.selecting
) {
6129 this.pressItem( null );
6130 this.chooseItem( this.selecting
);
6131 this.selecting
= null;
6134 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
6135 this.getElementDocument().removeEventListener( 'mousemove', this.onMouseMoveHandler
, true );
6141 * Handle mouse move events.
6144 * @param {MouseEvent} e Mouse move event
6146 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
6149 if ( !this.isDisabled() && this.pressed
) {
6150 item
= this.getTargetItem( e
);
6151 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
6152 this.pressItem( item
);
6153 this.selecting
= item
;
6159 * Handle mouse over events.
6162 * @param {jQuery.Event} e Mouse over event
6164 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
6166 if ( this.blockMouseOverEvents
) {
6169 if ( !this.isDisabled() ) {
6170 item
= this.getTargetItem( e
);
6171 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
6177 * Handle mouse leave events.
6180 * @param {jQuery.Event} e Mouse over event
6182 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
6183 if ( !this.isDisabled() ) {
6184 this.highlightItem( null );
6190 * Handle key down events.
6193 * @param {KeyboardEvent} e Key down event
6195 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
6198 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
6200 if ( !this.isDisabled() && this.isVisible() ) {
6201 switch ( e
.keyCode
) {
6202 case OO
.ui
.Keys
.ENTER
:
6203 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
6204 // Was only highlighted, now let's select it. No-op if already selected.
6205 this.chooseItem( currentItem
);
6210 case OO
.ui
.Keys
.LEFT
:
6211 this.clearKeyPressBuffer();
6212 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
6215 case OO
.ui
.Keys
.DOWN
:
6216 case OO
.ui
.Keys
.RIGHT
:
6217 this.clearKeyPressBuffer();
6218 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
6221 case OO
.ui
.Keys
.ESCAPE
:
6222 case OO
.ui
.Keys
.TAB
:
6223 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
6224 currentItem
.setHighlighted( false );
6226 this.unbindKeyDownListener();
6227 this.unbindKeyPressListener();
6228 // Don't prevent tabbing away / defocusing
6234 if ( nextItem
.constructor.static.highlightable
) {
6235 this.highlightItem( nextItem
);
6237 this.chooseItem( nextItem
);
6239 this.scrollItemIntoView( nextItem
);
6244 e
.stopPropagation();
6250 * Bind key down listener.
6254 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
6255 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler
, true );
6259 * Unbind key down listener.
6263 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
6264 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler
, true );
6268 * Scroll item into view, preventing spurious mouse highlight actions from happening.
6270 * @param {OO.ui.OptionWidget} item Item to scroll into view
6272 OO
.ui
.SelectWidget
.prototype.scrollItemIntoView = function ( item
) {
6274 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling
6275 // and around 100-150 ms after it is finished.
6276 this.blockMouseOverEvents
++;
6277 item
.scrollElementIntoView().done( function () {
6278 setTimeout( function () {
6279 widget
.blockMouseOverEvents
--;
6285 * Clear the key-press buffer
6289 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
6290 if ( this.keyPressBufferTimer
) {
6291 clearTimeout( this.keyPressBufferTimer
);
6292 this.keyPressBufferTimer
= null;
6294 this.keyPressBuffer
= '';
6298 * Handle key press events.
6301 * @param {KeyboardEvent} e Key press event
6303 OO
.ui
.SelectWidget
.prototype.onKeyPress = function ( e
) {
6304 var c
, filter
, item
;
6306 if ( !e
.charCode
) {
6307 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
6308 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
6313 if ( String
.fromCodePoint
) {
6314 c
= String
.fromCodePoint( e
.charCode
);
6316 c
= String
.fromCharCode( e
.charCode
);
6319 if ( this.keyPressBufferTimer
) {
6320 clearTimeout( this.keyPressBufferTimer
);
6322 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
6324 item
= this.getHighlightedItem() || this.getSelectedItem();
6326 if ( this.keyPressBuffer
=== c
) {
6327 // Common (if weird) special case: typing "xxxx" will cycle through all
6328 // the items beginning with "x".
6330 item
= this.getRelativeSelectableItem( item
, 1 );
6333 this.keyPressBuffer
+= c
;
6336 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
6337 if ( !item
|| !filter( item
) ) {
6338 item
= this.getRelativeSelectableItem( item
, 1, filter
);
6341 if ( this.isVisible() && item
.constructor.static.highlightable
) {
6342 this.highlightItem( item
);
6344 this.chooseItem( item
);
6346 this.scrollItemIntoView( item
);
6350 e
.stopPropagation();
6354 * Get a matcher for the specific string
6357 * @param {string} s String to match against items
6358 * @param {boolean} [exact=false] Only accept exact matches
6359 * @return {Function} function ( OO.ui.OptionWidget ) => boolean
6361 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
, exact
) {
6364 if ( s
.normalize
) {
6367 s
= exact
? s
.trim() : s
.replace( /^\s+/, '' );
6368 re
= '^\\s*' + s
.replace( /([\\{}()|.?*+\-^$[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
6372 re
= new RegExp( re
, 'i' );
6373 return function ( item
) {
6374 var matchText
= item
.getMatchText();
6375 if ( matchText
.normalize
) {
6376 matchText
= matchText
.normalize();
6378 return re
.test( matchText
);
6383 * Bind key press listener.
6387 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
6388 this.getElementWindow().addEventListener( 'keypress', this.onKeyPressHandler
, true );
6392 * Unbind key down listener.
6394 * If you override this, be sure to call this.clearKeyPressBuffer() from your
6399 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
6400 this.getElementWindow().removeEventListener( 'keypress', this.onKeyPressHandler
, true );
6401 this.clearKeyPressBuffer();
6405 * Visibility change handler
6408 * @param {boolean} visible
6410 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
6412 this.clearKeyPressBuffer();
6417 * Get the closest item to a jQuery.Event.
6420 * @param {jQuery.Event} e
6421 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
6423 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
6424 return $( e
.target
).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
6428 * Get selected item.
6430 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
6432 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
6435 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6436 if ( this.items
[ i
].isSelected() ) {
6437 return this.items
[ i
];
6444 * Get highlighted item.
6446 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
6448 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
6451 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6452 if ( this.items
[ i
].isHighlighted() ) {
6453 return this.items
[ i
];
6460 * Toggle pressed state.
6462 * Press is a state that occurs when a user mouses down on an item, but
6463 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
6464 * until the user releases the mouse.
6466 * @param {boolean} pressed An option is being pressed
6468 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
6469 if ( pressed
=== undefined ) {
6470 pressed
= !this.pressed
;
6472 if ( pressed
!== this.pressed
) {
6474 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
6475 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
6476 this.pressed
= pressed
;
6481 * Highlight an option. If the `item` param is omitted, no options will be highlighted
6482 * and any existing highlight will be removed. The highlight is mutually exclusive.
6484 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
6488 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
6489 var i
, len
, highlighted
,
6492 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6493 highlighted
= this.items
[ i
] === item
;
6494 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
6495 this.items
[ i
].setHighlighted( highlighted
);
6501 this.$focusOwner
.attr( 'aria-activedescendant', item
.getElementId() );
6503 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
6505 this.emit( 'highlight', item
);
6512 * Fetch an item by its label.
6514 * @param {string} label Label of the item to select.
6515 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
6516 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
6518 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
6520 len
= this.items
.length
,
6521 filter
= this.getItemMatcher( label
, true );
6523 for ( i
= 0; i
< len
; i
++ ) {
6524 item
= this.items
[ i
];
6525 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
6532 filter
= this.getItemMatcher( label
, false );
6533 for ( i
= 0; i
< len
; i
++ ) {
6534 item
= this.items
[ i
];
6535 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
6551 * Programmatically select an option by its label. If the item does not exist,
6552 * all options will be deselected.
6554 * @param {string} [label] Label of the item to select.
6555 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
6559 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
6560 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
6561 if ( label
=== undefined || !itemFromLabel
) {
6562 return this.selectItem();
6564 return this.selectItem( itemFromLabel
);
6568 * Programmatically select an option by its data. If the `data` parameter is omitted,
6569 * or if the item does not exist, all options will be deselected.
6571 * @param {Object|string} [data] Value of the item to select, omit to deselect all
6575 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
6576 var itemFromData
= this.getItemFromData( data
);
6577 if ( data
=== undefined || !itemFromData
) {
6578 return this.selectItem();
6580 return this.selectItem( itemFromData
);
6584 * Programmatically select an option by its reference. If the `item` parameter is omitted,
6585 * all options will be deselected.
6587 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
6591 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
6592 var i
, len
, selected
,
6595 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6596 selected
= this.items
[ i
] === item
;
6597 if ( this.items
[ i
].isSelected() !== selected
) {
6598 this.items
[ i
].setSelected( selected
);
6603 if ( item
&& !item
.constructor.static.highlightable
) {
6605 this.$focusOwner
.attr( 'aria-activedescendant', item
.getElementId() );
6607 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
6610 this.emit( 'select', item
);
6619 * Press is a state that occurs when a user mouses down on an item, but has not
6620 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
6621 * releases the mouse.
6623 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
6627 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
6628 var i
, len
, pressed
,
6631 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6632 pressed
= this.items
[ i
] === item
;
6633 if ( this.items
[ i
].isPressed() !== pressed
) {
6634 this.items
[ i
].setPressed( pressed
);
6639 this.emit( 'press', item
);
6648 * Note that ‘choose’ should never be modified programmatically. A user can choose
6649 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
6650 * use the #selectItem method.
6652 * This method is identical to #selectItem, but may vary in subclasses that take additional action
6653 * when users choose an item with the keyboard or mouse.
6655 * @param {OO.ui.OptionWidget} item Item to choose
6659 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
6661 this.selectItem( item
);
6662 this.emit( 'choose', item
);
6669 * Get an option by its position relative to the specified item (or to the start of the option array,
6670 * if item is `null`). The direction in which to search through the option array is specified with a
6671 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
6672 * `null` if there are no options in the array.
6674 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
6675 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
6676 * @param {Function} [filter] Only consider items for which this function returns
6677 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
6678 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
6680 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
, filter
) {
6681 var currentIndex
, nextIndex
, i
,
6682 increase
= direction
> 0 ? 1 : -1,
6683 len
= this.items
.length
;
6685 if ( item
instanceof OO
.ui
.OptionWidget
) {
6686 currentIndex
= this.items
.indexOf( item
);
6687 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
6689 // If no item is selected and moving forward, start at the beginning.
6690 // If moving backward, start at the end.
6691 nextIndex
= direction
> 0 ? 0 : len
- 1;
6694 for ( i
= 0; i
< len
; i
++ ) {
6695 item
= this.items
[ nextIndex
];
6697 item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() &&
6698 ( !filter
|| filter( item
) )
6702 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
6708 * Get the next selectable item or `null` if there are no selectable items.
6709 * Disabled options and menu-section markers and breaks are not selectable.
6711 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
6713 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
6714 return this.getRelativeSelectableItem( null, 1 );
6718 * Add an array of options to the select. Optionally, an index number can be used to
6719 * specify an insertion point.
6721 * @param {OO.ui.OptionWidget[]} items Items to add
6722 * @param {number} [index] Index to insert items after
6726 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
6728 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
6730 // Always provide an index, even if it was omitted
6731 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
6737 * Remove the specified array of options from the select. Options will be detached
6738 * from the DOM, not removed, so they can be reused later. To remove all options from
6739 * the select, you may wish to use the #clearItems method instead.
6741 * @param {OO.ui.OptionWidget[]} items Items to remove
6745 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
6748 // Deselect items being removed
6749 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
6751 if ( item
.isSelected() ) {
6752 this.selectItem( null );
6757 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
6759 this.emit( 'remove', items
);
6765 * Clear all options from the select. Options will be detached from the DOM, not removed,
6766 * so that they can be reused later. To remove a subset of options from the select, use
6767 * the #removeItems method.
6772 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
6773 var items
= this.items
.slice();
6776 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
6779 this.selectItem( null );
6781 this.emit( 'remove', items
);
6787 * Set the DOM element which has focus while the user is interacting with this SelectWidget.
6789 * Currently this is just used to set `aria-activedescendant` on it.
6792 * @param {jQuery} $focusOwner
6794 OO
.ui
.SelectWidget
.prototype.setFocusOwner = function ( $focusOwner
) {
6795 this.$focusOwner
= $focusOwner
;
6799 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
6800 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
6801 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
6802 * options. For more information about options and selects, please see the
6803 * [OOjs UI documentation on MediaWiki][1].
6806 * // Decorated options in a select widget
6807 * var select = new OO.ui.SelectWidget( {
6809 * new OO.ui.DecoratedOptionWidget( {
6811 * label: 'Option with icon',
6814 * new OO.ui.DecoratedOptionWidget( {
6816 * label: 'Option with indicator',
6821 * $( 'body' ).append( select.$element );
6823 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6826 * @extends OO.ui.OptionWidget
6827 * @mixins OO.ui.mixin.IconElement
6828 * @mixins OO.ui.mixin.IndicatorElement
6831 * @param {Object} [config] Configuration options
6833 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
6834 // Parent constructor
6835 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
6837 // Mixin constructors
6838 OO
.ui
.mixin
.IconElement
.call( this, config
);
6839 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
6843 .addClass( 'oo-ui-decoratedOptionWidget' )
6844 .prepend( this.$icon
)
6845 .append( this.$indicator
);
6850 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
6851 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
6852 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
6855 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
6856 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
6857 * the [OOjs UI documentation on MediaWiki] [1] for more information.
6859 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
6862 * @extends OO.ui.DecoratedOptionWidget
6865 * @param {Object} [config] Configuration options
6867 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
6868 // Parent constructor
6869 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
6872 this.$element
.addClass( 'oo-ui-menuOptionWidget' );
6877 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
6879 /* Static Properties */
6885 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
6888 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
6889 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
6892 * var myDropdown = new OO.ui.DropdownWidget( {
6895 * new OO.ui.MenuSectionOptionWidget( {
6898 * new OO.ui.MenuOptionWidget( {
6900 * label: 'Welsh Corgi'
6902 * new OO.ui.MenuOptionWidget( {
6904 * label: 'Standard Poodle'
6906 * new OO.ui.MenuSectionOptionWidget( {
6909 * new OO.ui.MenuOptionWidget( {
6916 * $( 'body' ).append( myDropdown.$element );
6919 * @extends OO.ui.DecoratedOptionWidget
6922 * @param {Object} [config] Configuration options
6924 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
6925 // Parent constructor
6926 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
6929 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' )
6930 .removeAttr( 'role aria-selected' );
6935 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
6937 /* Static Properties */
6943 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
6949 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
6952 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
6953 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
6954 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
6955 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
6956 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
6957 * and customized to be opened, closed, and displayed as needed.
6959 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
6960 * mouse outside the menu.
6962 * Menus also have support for keyboard interaction:
6964 * - Enter/Return key: choose and select a menu option
6965 * - Up-arrow key: highlight the previous menu option
6966 * - Down-arrow key: highlight the next menu option
6967 * - Esc key: hide the menu
6969 * Unlike most widgets, MenuSelectWidget is initially hidden and must be shown by calling #toggle.
6971 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
6972 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6975 * @extends OO.ui.SelectWidget
6976 * @mixins OO.ui.mixin.ClippableElement
6977 * @mixins OO.ui.mixin.FloatableElement
6980 * @param {Object} [config] Configuration options
6981 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
6982 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
6983 * and {@link OO.ui.mixin.LookupElement LookupElement}
6984 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
6985 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiselectWidget CapsuleMultiselectWidget}
6986 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
6987 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
6988 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
6989 * that button, unless the button (or its parent widget) is passed in here.
6990 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
6991 * @cfg {jQuery} [$autoCloseIgnore] If these elements are clicked, don't auto-hide the menu.
6992 * @cfg {boolean} [hideOnChoose=true] Hide the menu when the user chooses an option.
6993 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
6994 * @cfg {boolean} [highlightOnFilter] Highlight the first result when filtering
6995 * @cfg {number} [width] Width of the menu
6997 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
6998 // Configuration initialization
6999 config
= config
|| {};
7001 // Parent constructor
7002 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
7004 // Mixin constructors
7005 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
7006 OO
.ui
.mixin
.FloatableElement
.call( this, config
);
7009 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
7010 this.hideOnChoose
= config
.hideOnChoose
=== undefined || !!config
.hideOnChoose
;
7011 this.filterFromInput
= !!config
.filterFromInput
;
7012 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
7013 this.$widget
= config
.widget
? config
.widget
.$element
: null;
7014 this.$autoCloseIgnore
= config
.$autoCloseIgnore
|| $( [] );
7015 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
7016 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
7017 this.highlightOnFilter
= !!config
.highlightOnFilter
;
7018 this.width
= config
.width
;
7021 this.$element
.addClass( 'oo-ui-menuSelectWidget' );
7022 if ( config
.widget
) {
7023 this.setFocusOwner( config
.widget
.$tabIndexed
);
7026 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
7027 // that reference properties not initialized at that time of parent class construction
7028 // TODO: Find a better way to handle post-constructor setup
7029 this.visible
= false;
7030 this.$element
.addClass( 'oo-ui-element-hidden' );
7035 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
7036 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
7037 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.FloatableElement
);
7044 * The menu is ready: it is visible and has been positioned and clipped.
7050 * Handles document mouse down events.
7053 * @param {MouseEvent} e Mouse down event
7055 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
7059 this.$element
.add( this.$widget
).add( this.$autoCloseIgnore
).get(),
7064 this.toggle( false );
7071 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
7072 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
7074 if ( !this.isDisabled() && this.isVisible() ) {
7075 switch ( e
.keyCode
) {
7076 case OO
.ui
.Keys
.LEFT
:
7077 case OO
.ui
.Keys
.RIGHT
:
7078 // Do nothing if a text field is associated, arrow keys will be handled natively
7079 if ( !this.$input
) {
7080 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
7083 case OO
.ui
.Keys
.ESCAPE
:
7084 case OO
.ui
.Keys
.TAB
:
7085 if ( currentItem
) {
7086 currentItem
.setHighlighted( false );
7088 this.toggle( false );
7089 // Don't prevent tabbing away, prevent defocusing
7090 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
7092 e
.stopPropagation();
7096 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
7103 * Update menu item visibility and clipping after input changes (if filterFromInput is enabled)
7104 * or after items were added/removed (always).
7108 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
7109 var i
, item
, visible
, section
, sectionEmpty
, filter
, exactFilter
,
7110 firstItemFound
= false,
7112 len
= this.items
.length
,
7113 showAll
= !this.isVisible(),
7116 if ( this.$input
&& this.filterFromInput
) {
7117 filter
= showAll
? null : this.getItemMatcher( this.$input
.val() );
7118 exactFilter
= this.getItemMatcher( this.$input
.val(), true );
7120 // Hide non-matching options, and also hide section headers if all options
7121 // in their section are hidden.
7122 for ( i
= 0; i
< len
; i
++ ) {
7123 item
= this.items
[ i
];
7124 if ( item
instanceof OO
.ui
.MenuSectionOptionWidget
) {
7126 // If the previous section was empty, hide its header
7127 section
.toggle( showAll
|| !sectionEmpty
);
7130 sectionEmpty
= true;
7131 } else if ( item
instanceof OO
.ui
.OptionWidget
) {
7132 visible
= showAll
|| filter( item
);
7133 exactMatch
= exactMatch
|| exactFilter( item
);
7134 anyVisible
= anyVisible
|| visible
;
7135 sectionEmpty
= sectionEmpty
&& !visible
;
7136 item
.toggle( visible
);
7137 if ( this.highlightOnFilter
&& visible
&& !firstItemFound
) {
7138 // Highlight the first item in the list
7139 this.highlightItem( item
);
7140 firstItemFound
= true;
7144 // Process the final section
7146 section
.toggle( showAll
|| !sectionEmpty
);
7149 if ( anyVisible
&& this.items
.length
&& !exactMatch
) {
7150 this.scrollItemIntoView( this.items
[ 0 ] );
7153 this.$element
.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible
);
7156 // Reevaluate clipping
7163 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
7164 if ( this.$input
) {
7165 this.$input
.on( 'keydown', this.onKeyDownHandler
);
7167 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyDownListener
.call( this );
7174 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
7175 if ( this.$input
) {
7176 this.$input
.off( 'keydown', this.onKeyDownHandler
);
7178 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyDownListener
.call( this );
7185 OO
.ui
.MenuSelectWidget
.prototype.bindKeyPressListener = function () {
7186 if ( this.$input
) {
7187 if ( this.filterFromInput
) {
7188 this.$input
.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
7189 this.updateItemVisibility();
7192 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyPressListener
.call( this );
7199 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyPressListener = function () {
7200 if ( this.$input
) {
7201 if ( this.filterFromInput
) {
7202 this.$input
.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
7203 this.updateItemVisibility();
7206 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyPressListener
.call( this );
7213 * When a user chooses an item, the menu is closed, unless the hideOnChoose config option is set to false.
7215 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
7216 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
7218 * @param {OO.ui.OptionWidget} item Item to choose
7221 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
7222 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
7223 if ( this.hideOnChoose
) {
7224 this.toggle( false );
7232 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
7234 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
7236 this.updateItemVisibility();
7244 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
7246 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
7248 this.updateItemVisibility();
7256 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
7258 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
7260 this.updateItemVisibility();
7266 * Toggle visibility of the menu. The menu is initially hidden and must be shown by calling
7267 * `.toggle( true )` after its #$element is attached to the DOM.
7269 * Do not show the menu while it is not attached to the DOM. The calculations required to display
7270 * it in the right place and with the right dimensions only work correctly while it is attached.
7271 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
7272 * strictly enforced, so currently it only generates a warning in the browser console.
7277 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
7280 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
7281 change
= visible
!== this.isVisible();
7283 if ( visible
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
7284 OO
.ui
.warnDeprecation( 'MenuSelectWidget#toggle: Before calling this method, the menu must be attached to the DOM.' );
7285 this.warnedUnattached
= true;
7288 if ( change
&& visible
&& ( this.width
|| this.$floatableContainer
) ) {
7289 this.setIdealSize( this.width
|| this.$floatableContainer
.width() );
7293 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
7297 this.bindKeyDownListener();
7298 this.bindKeyPressListener();
7300 this.togglePositioning( !!this.$floatableContainer
);
7301 this.toggleClipping( true );
7303 this.$focusOwner
.attr( 'aria-expanded', 'true' );
7305 if ( this.getSelectedItem() ) {
7306 this.$focusOwner
.attr( 'aria-activedescendant', this.getSelectedItem().getElementId() );
7307 this.getSelectedItem().scrollElementIntoView( { duration
: 0 } );
7311 if ( this.autoHide
) {
7312 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
7315 this.emit( 'ready' );
7317 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
7318 this.unbindKeyDownListener();
7319 this.unbindKeyPressListener();
7320 this.$focusOwner
.attr( 'aria-expanded', 'false' );
7321 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
7322 this.togglePositioning( false );
7323 this.toggleClipping( false );
7331 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
7332 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
7333 * users can interact with it.
7335 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7336 * OO.ui.DropdownInputWidget instead.
7339 * // Example: A DropdownWidget with a menu that contains three options
7340 * var dropDown = new OO.ui.DropdownWidget( {
7341 * label: 'Dropdown menu: Select a menu option',
7344 * new OO.ui.MenuOptionWidget( {
7348 * new OO.ui.MenuOptionWidget( {
7352 * new OO.ui.MenuOptionWidget( {
7360 * $( 'body' ).append( dropDown.$element );
7362 * dropDown.getMenu().selectItemByData( 'b' );
7364 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
7366 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
7368 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
7371 * @extends OO.ui.Widget
7372 * @mixins OO.ui.mixin.IconElement
7373 * @mixins OO.ui.mixin.IndicatorElement
7374 * @mixins OO.ui.mixin.LabelElement
7375 * @mixins OO.ui.mixin.TitledElement
7376 * @mixins OO.ui.mixin.TabIndexedElement
7379 * @param {Object} [config] Configuration options
7380 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.MenuSelectWidget menu select widget}
7381 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
7382 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
7383 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
7384 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
7386 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
7387 // Configuration initialization
7388 config
= $.extend( { indicator
: 'down' }, config
);
7390 // Parent constructor
7391 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
7393 // Properties (must be set before TabIndexedElement constructor call)
7394 this.$handle
= this.$( '<span>' );
7395 this.$overlay
= config
.$overlay
|| this.$element
;
7397 // Mixin constructors
7398 OO
.ui
.mixin
.IconElement
.call( this, config
);
7399 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
7400 OO
.ui
.mixin
.LabelElement
.call( this, config
);
7401 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
7402 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
7405 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend( {
7407 $floatableContainer
: this.$element
7412 click
: this.onClick
.bind( this ),
7413 keydown
: this.onKeyDown
.bind( this ),
7414 // Hack? Handle type-to-search when menu is not expanded and not handling its own events
7415 keypress
: this.menu
.onKeyPressHandler
,
7416 blur
: this.menu
.clearKeyPressBuffer
.bind( this.menu
)
7418 this.menu
.connect( this, {
7419 select
: 'onMenuSelect',
7420 toggle
: 'onMenuToggle'
7425 .addClass( 'oo-ui-dropdownWidget-handle' )
7428 'aria-owns': this.menu
.getElementId(),
7429 'aria-autocomplete': 'list'
7431 .append( this.$icon
, this.$label
, this.$indicator
);
7433 .addClass( 'oo-ui-dropdownWidget' )
7434 .append( this.$handle
);
7435 this.$overlay
.append( this.menu
.$element
);
7440 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
7441 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
7442 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
7443 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
7444 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
7445 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
7452 * @return {OO.ui.MenuSelectWidget} Menu of widget
7454 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
7459 * Handles menu select events.
7462 * @param {OO.ui.MenuOptionWidget} item Selected menu item
7464 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
7468 this.setLabel( null );
7472 selectedLabel
= item
.getLabel();
7474 // If the label is a DOM element, clone it, because setLabel will append() it
7475 if ( selectedLabel
instanceof jQuery
) {
7476 selectedLabel
= selectedLabel
.clone();
7479 this.setLabel( selectedLabel
);
7483 * Handle menu toggle events.
7486 * @param {boolean} isVisible Menu toggle event
7488 OO
.ui
.DropdownWidget
.prototype.onMenuToggle = function ( isVisible
) {
7489 this.$element
.toggleClass( 'oo-ui-dropdownWidget-open', isVisible
);
7492 this.$element
.hasClass( 'oo-ui-dropdownWidget-open' ).toString()
7497 * Handle mouse click events.
7500 * @param {jQuery.Event} e Mouse click event
7502 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
7503 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
7510 * Handle key down events.
7513 * @param {jQuery.Event} e Key down event
7515 OO
.ui
.DropdownWidget
.prototype.onKeyDown = function ( e
) {
7517 !this.isDisabled() &&
7519 e
.which
=== OO
.ui
.Keys
.ENTER
||
7521 !this.menu
.isVisible() &&
7523 e
.which
=== OO
.ui
.Keys
.SPACE
||
7524 e
.which
=== OO
.ui
.Keys
.UP
||
7525 e
.which
=== OO
.ui
.Keys
.DOWN
7536 * RadioOptionWidget is an option widget that looks like a radio button.
7537 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
7538 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
7540 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
7543 * @extends OO.ui.OptionWidget
7546 * @param {Object} [config] Configuration options
7548 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
7549 // Configuration initialization
7550 config
= config
|| {};
7552 // Properties (must be done before parent constructor which calls #setDisabled)
7553 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
7555 // Parent constructor
7556 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
7559 // Remove implicit role, we're handling it ourselves
7560 this.radio
.$input
.attr( 'role', 'presentation' );
7562 .addClass( 'oo-ui-radioOptionWidget' )
7563 .attr( 'role', 'radio' )
7564 .attr( 'aria-checked', 'false' )
7565 .removeAttr( 'aria-selected' )
7566 .prepend( this.radio
.$element
);
7571 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
7573 /* Static Properties */
7579 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
7585 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
7591 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
7597 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
7604 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
7605 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
7607 this.radio
.setSelected( state
);
7609 .attr( 'aria-checked', state
.toString() )
7610 .removeAttr( 'aria-selected' );
7618 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
7619 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
7621 this.radio
.setDisabled( this.isDisabled() );
7627 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
7628 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
7629 * an interface for adding, removing and selecting options.
7630 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
7632 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7633 * OO.ui.RadioSelectInputWidget instead.
7636 * // A RadioSelectWidget with RadioOptions.
7637 * var option1 = new OO.ui.RadioOptionWidget( {
7639 * label: 'Selected radio option'
7642 * var option2 = new OO.ui.RadioOptionWidget( {
7644 * label: 'Unselected radio option'
7647 * var radioSelect=new OO.ui.RadioSelectWidget( {
7648 * items: [ option1, option2 ]
7651 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
7652 * radioSelect.selectItem( option1 );
7654 * $( 'body' ).append( radioSelect.$element );
7656 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
7660 * @extends OO.ui.SelectWidget
7661 * @mixins OO.ui.mixin.TabIndexedElement
7664 * @param {Object} [config] Configuration options
7666 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
7667 // Parent constructor
7668 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
7670 // Mixin constructors
7671 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
7675 focus
: this.bindKeyDownListener
.bind( this ),
7676 blur
: this.unbindKeyDownListener
.bind( this )
7681 .addClass( 'oo-ui-radioSelectWidget' )
7682 .attr( 'role', 'radiogroup' );
7687 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
7688 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
7691 * MultioptionWidgets are special elements that can be selected and configured with data. The
7692 * data is often unique for each option, but it does not have to be. MultioptionWidgets are used
7693 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
7694 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
7696 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Multioptions
7699 * @extends OO.ui.Widget
7700 * @mixins OO.ui.mixin.ItemWidget
7701 * @mixins OO.ui.mixin.LabelElement
7704 * @param {Object} [config] Configuration options
7705 * @cfg {boolean} [selected=false] Whether the option is initially selected
7707 OO
.ui
.MultioptionWidget
= function OoUiMultioptionWidget( config
) {
7708 // Configuration initialization
7709 config
= config
|| {};
7711 // Parent constructor
7712 OO
.ui
.MultioptionWidget
.parent
.call( this, config
);
7714 // Mixin constructors
7715 OO
.ui
.mixin
.ItemWidget
.call( this );
7716 OO
.ui
.mixin
.LabelElement
.call( this, config
);
7719 this.selected
= null;
7723 .addClass( 'oo-ui-multioptionWidget' )
7724 .append( this.$label
);
7725 this.setSelected( config
.selected
);
7730 OO
.inheritClass( OO
.ui
.MultioptionWidget
, OO
.ui
.Widget
);
7731 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.ItemWidget
);
7732 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.LabelElement
);
7739 * A change event is emitted when the selected state of the option changes.
7741 * @param {boolean} selected Whether the option is now selected
7747 * Check if the option is selected.
7749 * @return {boolean} Item is selected
7751 OO
.ui
.MultioptionWidget
.prototype.isSelected = function () {
7752 return this.selected
;
7756 * Set the option’s selected state. In general, all modifications to the selection
7757 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
7758 * method instead of this method.
7760 * @param {boolean} [state=false] Select option
7763 OO
.ui
.MultioptionWidget
.prototype.setSelected = function ( state
) {
7765 if ( this.selected
!== state
) {
7766 this.selected
= state
;
7767 this.emit( 'change', state
);
7768 this.$element
.toggleClass( 'oo-ui-multioptionWidget-selected', state
);
7774 * MultiselectWidget allows selecting multiple options from a list.
7776 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
7778 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
7782 * @extends OO.ui.Widget
7783 * @mixins OO.ui.mixin.GroupWidget
7786 * @param {Object} [config] Configuration options
7787 * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
7789 OO
.ui
.MultiselectWidget
= function OoUiMultiselectWidget( config
) {
7790 // Parent constructor
7791 OO
.ui
.MultiselectWidget
.parent
.call( this, config
);
7793 // Configuration initialization
7794 config
= config
|| {};
7796 // Mixin constructors
7797 OO
.ui
.mixin
.GroupWidget
.call( this, config
);
7800 this.aggregate( { change
: 'select' } );
7801 // This is mostly for compatibility with CapsuleMultiselectWidget... normally, 'change' is emitted
7802 // by GroupElement only when items are added/removed
7803 this.connect( this, { select
: [ 'emit', 'change' ] } );
7806 if ( config
.items
) {
7807 this.addItems( config
.items
);
7809 this.$group
.addClass( 'oo-ui-multiselectWidget-group' );
7810 this.$element
.addClass( 'oo-ui-multiselectWidget' )
7811 .append( this.$group
);
7816 OO
.inheritClass( OO
.ui
.MultiselectWidget
, OO
.ui
.Widget
);
7817 OO
.mixinClass( OO
.ui
.MultiselectWidget
, OO
.ui
.mixin
.GroupWidget
);
7824 * A change event is emitted when the set of items changes, or an item is selected or deselected.
7830 * A select event is emitted when an item is selected or deselected.
7836 * Get options that are selected.
7838 * @return {OO.ui.MultioptionWidget[]} Selected options
7840 OO
.ui
.MultiselectWidget
.prototype.getSelectedItems = function () {
7841 return this.items
.filter( function ( item
) {
7842 return item
.isSelected();
7847 * Get the data of options that are selected.
7849 * @return {Object[]|string[]} Values of selected options
7851 OO
.ui
.MultiselectWidget
.prototype.getSelectedItemsData = function () {
7852 return this.getSelectedItems().map( function ( item
) {
7858 * Select options by reference. Options not mentioned in the `items` array will be deselected.
7860 * @param {OO.ui.MultioptionWidget[]} items Items to select
7863 OO
.ui
.MultiselectWidget
.prototype.selectItems = function ( items
) {
7864 this.items
.forEach( function ( item
) {
7865 var selected
= items
.indexOf( item
) !== -1;
7866 item
.setSelected( selected
);
7872 * Select items by their data. Options not mentioned in the `datas` array will be deselected.
7874 * @param {Object[]|string[]} datas Values of items to select
7877 OO
.ui
.MultiselectWidget
.prototype.selectItemsByData = function ( datas
) {
7880 items
= datas
.map( function ( data
) {
7881 return widget
.getItemFromData( data
);
7883 this.selectItems( items
);
7888 * CheckboxMultioptionWidget is an option widget that looks like a checkbox.
7889 * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
7890 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
7892 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
7895 * @extends OO.ui.MultioptionWidget
7898 * @param {Object} [config] Configuration options
7900 OO
.ui
.CheckboxMultioptionWidget
= function OoUiCheckboxMultioptionWidget( config
) {
7901 // Configuration initialization
7902 config
= config
|| {};
7904 // Properties (must be done before parent constructor which calls #setDisabled)
7905 this.checkbox
= new OO
.ui
.CheckboxInputWidget();
7907 // Parent constructor
7908 OO
.ui
.CheckboxMultioptionWidget
.parent
.call( this, config
);
7911 this.checkbox
.on( 'change', this.onCheckboxChange
.bind( this ) );
7912 this.$element
.on( 'keydown', this.onKeyDown
.bind( this ) );
7916 .addClass( 'oo-ui-checkboxMultioptionWidget' )
7917 .prepend( this.checkbox
.$element
);
7922 OO
.inheritClass( OO
.ui
.CheckboxMultioptionWidget
, OO
.ui
.MultioptionWidget
);
7924 /* Static Properties */
7930 OO
.ui
.CheckboxMultioptionWidget
.static.tagName
= 'label';
7935 * Handle checkbox selected state change.
7939 OO
.ui
.CheckboxMultioptionWidget
.prototype.onCheckboxChange = function () {
7940 this.setSelected( this.checkbox
.isSelected() );
7946 OO
.ui
.CheckboxMultioptionWidget
.prototype.setSelected = function ( state
) {
7947 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setSelected
.call( this, state
);
7948 this.checkbox
.setSelected( state
);
7955 OO
.ui
.CheckboxMultioptionWidget
.prototype.setDisabled = function ( disabled
) {
7956 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
7957 this.checkbox
.setDisabled( this.isDisabled() );
7964 OO
.ui
.CheckboxMultioptionWidget
.prototype.focus = function () {
7965 this.checkbox
.focus();
7969 * Handle key down events.
7972 * @param {jQuery.Event} e
7974 OO
.ui
.CheckboxMultioptionWidget
.prototype.onKeyDown = function ( e
) {
7976 element
= this.getElementGroup(),
7979 if ( e
.keyCode
=== OO
.ui
.Keys
.LEFT
|| e
.keyCode
=== OO
.ui
.Keys
.UP
) {
7980 nextItem
= element
.getRelativeFocusableItem( this, -1 );
7981 } else if ( e
.keyCode
=== OO
.ui
.Keys
.RIGHT
|| e
.keyCode
=== OO
.ui
.Keys
.DOWN
) {
7982 nextItem
= element
.getRelativeFocusableItem( this, 1 );
7992 * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
7993 * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
7994 * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
7995 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
7997 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7998 * OO.ui.CheckboxMultiselectInputWidget instead.
8001 * // A CheckboxMultiselectWidget with CheckboxMultioptions.
8002 * var option1 = new OO.ui.CheckboxMultioptionWidget( {
8005 * label: 'Selected checkbox'
8008 * var option2 = new OO.ui.CheckboxMultioptionWidget( {
8010 * label: 'Unselected checkbox'
8013 * var multiselect=new OO.ui.CheckboxMultiselectWidget( {
8014 * items: [ option1, option2 ]
8017 * $( 'body' ).append( multiselect.$element );
8019 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
8022 * @extends OO.ui.MultiselectWidget
8025 * @param {Object} [config] Configuration options
8027 OO
.ui
.CheckboxMultiselectWidget
= function OoUiCheckboxMultiselectWidget( config
) {
8028 // Parent constructor
8029 OO
.ui
.CheckboxMultiselectWidget
.parent
.call( this, config
);
8032 this.$lastClicked
= null;
8035 this.$group
.on( 'click', this.onClick
.bind( this ) );
8039 .addClass( 'oo-ui-checkboxMultiselectWidget' );
8044 OO
.inheritClass( OO
.ui
.CheckboxMultiselectWidget
, OO
.ui
.MultiselectWidget
);
8049 * Get an option by its position relative to the specified item (or to the start of the option array,
8050 * if item is `null`). The direction in which to search through the option array is specified with a
8051 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
8052 * `null` if there are no options in the array.
8054 * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
8055 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
8056 * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items in the select
8058 OO
.ui
.CheckboxMultiselectWidget
.prototype.getRelativeFocusableItem = function ( item
, direction
) {
8059 var currentIndex
, nextIndex
, i
,
8060 increase
= direction
> 0 ? 1 : -1,
8061 len
= this.items
.length
;
8064 currentIndex
= this.items
.indexOf( item
);
8065 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
8067 // If no item is selected and moving forward, start at the beginning.
8068 // If moving backward, start at the end.
8069 nextIndex
= direction
> 0 ? 0 : len
- 1;
8072 for ( i
= 0; i
< len
; i
++ ) {
8073 item
= this.items
[ nextIndex
];
8074 if ( item
&& !item
.isDisabled() ) {
8077 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
8083 * Handle click events on checkboxes.
8085 * @param {jQuery.Event} e
8087 OO
.ui
.CheckboxMultiselectWidget
.prototype.onClick = function ( e
) {
8088 var $options
, lastClickedIndex
, nowClickedIndex
, i
, direction
, wasSelected
, items
,
8089 $lastClicked
= this.$lastClicked
,
8090 $nowClicked
= $( e
.target
).closest( '.oo-ui-checkboxMultioptionWidget' )
8091 .not( '.oo-ui-widget-disabled' );
8093 // Allow selecting multiple options at once by Shift-clicking them
8094 if ( $lastClicked
&& $nowClicked
.length
&& e
.shiftKey
) {
8095 $options
= this.$group
.find( '.oo-ui-checkboxMultioptionWidget' );
8096 lastClickedIndex
= $options
.index( $lastClicked
);
8097 nowClickedIndex
= $options
.index( $nowClicked
);
8098 // If it's the same item, either the user is being silly, or it's a fake event generated by the
8099 // browser. In either case we don't need custom handling.
8100 if ( nowClickedIndex
!== lastClickedIndex
) {
8102 wasSelected
= items
[ nowClickedIndex
].isSelected();
8103 direction
= nowClickedIndex
> lastClickedIndex
? 1 : -1;
8105 // This depends on the DOM order of the items and the order of the .items array being the same.
8106 for ( i
= lastClickedIndex
; i
!== nowClickedIndex
; i
+= direction
) {
8107 if ( !items
[ i
].isDisabled() ) {
8108 items
[ i
].setSelected( !wasSelected
);
8111 // For the now-clicked element, use immediate timeout to allow the browser to do its own
8112 // handling first, then set our value. The order in which events happen is different for
8113 // clicks on the <input> and on the <label> and there are additional fake clicks fired for
8114 // non-click actions that change the checkboxes.
8116 setTimeout( function () {
8117 if ( !items
[ nowClickedIndex
].isDisabled() ) {
8118 items
[ nowClickedIndex
].setSelected( !wasSelected
);
8124 if ( $nowClicked
.length
) {
8125 this.$lastClicked
= $nowClicked
;
8134 OO
.ui
.CheckboxMultiselectWidget
.prototype.focus = function () {
8136 if ( !this.isDisabled() ) {
8137 item
= this.getRelativeFocusableItem( null, 1 );
8148 OO
.ui
.CheckboxMultiselectWidget
.prototype.simulateLabelClick = function () {
8153 * FloatingMenuSelectWidget was a menu that would stick under a specified
8154 * container, even when it is inserted elsewhere in the document.
8155 * This functionality is now included in MenuSelectWidget, and FloatingMenuSelectWidget
8156 * is preserved for backwards-compatibility.
8159 * @extends OO.ui.MenuSelectWidget
8160 * @deprecated since v0.21.3, use MenuSelectWidget instead.
8163 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
8164 * Deprecated, omit this parameter and specify `$container` instead.
8165 * @param {Object} [config] Configuration options
8166 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
8168 OO
.ui
.FloatingMenuSelectWidget
= function OoUiFloatingMenuSelectWidget( inputWidget
, config
) {
8169 OO
.ui
.warnDeprecation( 'FloatingMenuSelectWidget is deprecated. Use the MenuSelectWidget instead.' );
8171 // Allow 'inputWidget' parameter and config for backwards compatibility
8172 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
8173 config
= inputWidget
;
8174 inputWidget
= config
.inputWidget
;
8177 // Configuration initialization
8178 config
= config
|| {};
8181 this.inputWidget
= inputWidget
; // For backwards compatibility
8182 this.$container
= config
.$floatableContainer
|| config
.$container
|| this.inputWidget
.$element
;
8184 // Parent constructor
8185 OO
.ui
.FloatingMenuSelectWidget
.parent
.call( this, $.extend( {}, config
, { $floatableContainer
: this.$container
} ) );
8188 this.$element
.addClass( 'oo-ui-floatingMenuSelectWidget' );
8189 // For backwards compatibility
8190 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
8195 OO
.inheritClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
8198 * Progress bars visually display the status of an operation, such as a download,
8199 * and can be either determinate or indeterminate:
8201 * - **determinate** process bars show the percent of an operation that is complete.
8203 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
8204 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
8205 * not use percentages.
8207 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
8210 * // Examples of determinate and indeterminate progress bars.
8211 * var progressBar1 = new OO.ui.ProgressBarWidget( {
8214 * var progressBar2 = new OO.ui.ProgressBarWidget();
8216 * // Create a FieldsetLayout to layout progress bars
8217 * var fieldset = new OO.ui.FieldsetLayout;
8218 * fieldset.addItems( [
8219 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
8220 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
8222 * $( 'body' ).append( fieldset.$element );
8225 * @extends OO.ui.Widget
8228 * @param {Object} [config] Configuration options
8229 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
8230 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
8231 * By default, the progress bar is indeterminate.
8233 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
8234 // Configuration initialization
8235 config
= config
|| {};
8237 // Parent constructor
8238 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
8241 this.$bar
= $( '<div>' );
8242 this.progress
= null;
8245 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
8246 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
8249 role
: 'progressbar',
8251 'aria-valuemax': 100
8253 .addClass( 'oo-ui-progressBarWidget' )
8254 .append( this.$bar
);
8259 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
8261 /* Static Properties */
8267 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
8272 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
8274 * @return {number|boolean} Progress percent
8276 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
8277 return this.progress
;
8281 * Set the percent of the process completed or `false` for an indeterminate process.
8283 * @param {number|boolean} progress Progress percent or `false` for indeterminate
8285 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
8286 this.progress
= progress
;
8288 if ( progress
!== false ) {
8289 this.$bar
.css( 'width', this.progress
+ '%' );
8290 this.$element
.attr( 'aria-valuenow', this.progress
);
8292 this.$bar
.css( 'width', '' );
8293 this.$element
.removeAttr( 'aria-valuenow' );
8295 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress
=== false );
8299 * InputWidget is the base class for all input widgets, which
8300 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
8301 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
8302 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
8304 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8308 * @extends OO.ui.Widget
8309 * @mixins OO.ui.mixin.FlaggedElement
8310 * @mixins OO.ui.mixin.TabIndexedElement
8311 * @mixins OO.ui.mixin.TitledElement
8312 * @mixins OO.ui.mixin.AccessKeyedElement
8315 * @param {Object} [config] Configuration options
8316 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
8317 * @cfg {string} [value=''] The value of the input.
8318 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
8319 * @cfg {string} [inputId] The value of the input’s HTML `id` attribute.
8320 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
8321 * before it is accepted.
8323 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
8324 // Configuration initialization
8325 config
= config
|| {};
8327 // Parent constructor
8328 OO
.ui
.InputWidget
.parent
.call( this, config
);
8331 // See #reusePreInfuseDOM about config.$input
8332 this.$input
= config
.$input
|| this.getInputElement( config
);
8334 this.inputFilter
= config
.inputFilter
;
8336 // Mixin constructors
8337 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
8338 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
8339 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
8340 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$input
} ) );
8343 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
8347 .addClass( 'oo-ui-inputWidget-input' )
8348 .attr( 'name', config
.name
)
8349 .prop( 'disabled', this.isDisabled() );
8351 .addClass( 'oo-ui-inputWidget' )
8352 .append( this.$input
);
8353 this.setValue( config
.value
);
8355 this.setDir( config
.dir
);
8357 if ( config
.inputId
!== undefined ) {
8358 this.setInputId( config
.inputId
);
8364 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
8365 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
8366 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
8367 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
8368 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
8370 /* Static Methods */
8375 OO
.ui
.InputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
8376 config
= OO
.ui
.InputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
8377 // Reusing `$input` lets browsers preserve inputted values across page reloads, see T114134.
8378 config
.$input
= $( node
).find( '.oo-ui-inputWidget-input' );
8385 OO
.ui
.InputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8386 var state
= OO
.ui
.InputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8387 if ( config
.$input
&& config
.$input
.length
) {
8388 state
.value
= config
.$input
.val();
8389 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
8390 state
.focus
= config
.$input
.is( ':focus' );
8400 * A change event is emitted when the value of the input changes.
8402 * @param {string} value
8408 * Get input element.
8410 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
8411 * different circumstances. The element must have a `value` property (like form elements).
8414 * @param {Object} config Configuration options
8415 * @return {jQuery} Input element
8417 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
8418 return $( '<input>' );
8422 * Handle potentially value-changing events.
8425 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
8427 OO
.ui
.InputWidget
.prototype.onEdit = function () {
8429 if ( !this.isDisabled() ) {
8430 // Allow the stack to clear so the value will be updated
8431 setTimeout( function () {
8432 widget
.setValue( widget
.$input
.val() );
8438 * Get the value of the input.
8440 * @return {string} Input value
8442 OO
.ui
.InputWidget
.prototype.getValue = function () {
8443 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
8444 // it, and we won't know unless they're kind enough to trigger a 'change' event.
8445 var value
= this.$input
.val();
8446 if ( this.value
!== value
) {
8447 this.setValue( value
);
8453 * Set the directionality of the input.
8455 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
8458 OO
.ui
.InputWidget
.prototype.setDir = function ( dir
) {
8459 this.$input
.prop( 'dir', dir
);
8464 * Set the value of the input.
8466 * @param {string} value New value
8470 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
8471 value
= this.cleanUpValue( value
);
8472 // Update the DOM if it has changed. Note that with cleanUpValue, it
8473 // is possible for the DOM value to change without this.value changing.
8474 if ( this.$input
.val() !== value
) {
8475 this.$input
.val( value
);
8477 if ( this.value
!== value
) {
8479 this.emit( 'change', this.value
);
8485 * Clean up incoming value.
8487 * Ensures value is a string, and converts undefined and null to empty string.
8490 * @param {string} value Original value
8491 * @return {string} Cleaned up value
8493 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
8494 if ( value
=== undefined || value
=== null ) {
8496 } else if ( this.inputFilter
) {
8497 return this.inputFilter( String( value
) );
8499 return String( value
);
8506 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
8507 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
8508 if ( this.$input
) {
8509 this.$input
.prop( 'disabled', this.isDisabled() );
8515 * Set the 'id' attribute of the `<input>` element.
8517 * @param {string} id
8520 OO
.ui
.InputWidget
.prototype.setInputId = function ( id
) {
8521 this.$input
.attr( 'id', id
);
8528 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
8529 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
8530 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
8531 this.setValue( state
.value
);
8533 if ( state
.focus
) {
8539 * Data widget intended for creating 'hidden'-type inputs.
8542 * @extends OO.ui.Widget
8545 * @param {Object} [config] Configuration options
8546 * @cfg {string} [value=''] The value of the input.
8547 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
8549 OO
.ui
.HiddenInputWidget
= function OoUiHiddenInputWidget( config
) {
8550 // Configuration initialization
8551 config
= $.extend( { value
: '', name
: '' }, config
);
8553 // Parent constructor
8554 OO
.ui
.HiddenInputWidget
.parent
.call( this, config
);
8557 this.$element
.attr( {
8559 value
: config
.value
,
8562 this.$element
.removeAttr( 'aria-disabled' );
8567 OO
.inheritClass( OO
.ui
.HiddenInputWidget
, OO
.ui
.Widget
);
8569 /* Static Properties */
8575 OO
.ui
.HiddenInputWidget
.static.tagName
= 'input';
8578 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
8579 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
8580 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
8581 * HTML `<button>` (the default) or an HTML `<input>` tags. See the
8582 * [OOjs UI documentation on MediaWiki] [1] for more information.
8585 * // A ButtonInputWidget rendered as an HTML button, the default.
8586 * var button = new OO.ui.ButtonInputWidget( {
8587 * label: 'Input button',
8591 * $( 'body' ).append( button.$element );
8593 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
8596 * @extends OO.ui.InputWidget
8597 * @mixins OO.ui.mixin.ButtonElement
8598 * @mixins OO.ui.mixin.IconElement
8599 * @mixins OO.ui.mixin.IndicatorElement
8600 * @mixins OO.ui.mixin.LabelElement
8601 * @mixins OO.ui.mixin.TitledElement
8604 * @param {Object} [config] Configuration options
8605 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
8606 * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
8607 * Widgets configured to be an `<input>` do not support {@link #icon icons} and {@link #indicator indicators},
8608 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
8609 * be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
8611 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
8612 // Configuration initialization
8613 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
8615 // See InputWidget#reusePreInfuseDOM about config.$input
8616 if ( config
.$input
) {
8617 config
.$input
.empty();
8620 // Properties (must be set before parent constructor, which calls #setValue)
8621 this.useInputTag
= config
.useInputTag
;
8623 // Parent constructor
8624 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
8626 // Mixin constructors
8627 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
8628 OO
.ui
.mixin
.IconElement
.call( this, config
);
8629 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
8630 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8631 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
8634 if ( !config
.useInputTag
) {
8635 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
8637 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
8642 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
8643 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
8644 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
8645 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
8646 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
8647 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
8649 /* Static Properties */
8655 OO
.ui
.ButtonInputWidget
.static.tagName
= 'span';
8663 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
8665 type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ? config
.type
: 'button';
8666 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
8672 * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
8674 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
8675 * text, or `null` for no label
8678 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
8679 if ( typeof label
=== 'function' ) {
8680 label
= OO
.ui
.resolveMsg( label
);
8683 if ( this.useInputTag
) {
8684 // Discard non-plaintext labels
8685 if ( typeof label
!== 'string' ) {
8689 this.$input
.val( label
);
8692 return OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
8696 * Set the value of the input.
8698 * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
8699 * they do not support {@link #value values}.
8701 * @param {string} value New value
8704 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
8705 if ( !this.useInputTag
) {
8706 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
8714 OO
.ui
.ButtonInputWidget
.prototype.getInputId = function () {
8715 // Disable generating `<label>` elements for buttons. One would very rarely need additional label
8716 // for a button, and it's already a big clickable target, and it causes unexpected rendering.
8721 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
8722 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
8723 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
8724 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
8726 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
8729 * // An example of selected, unselected, and disabled checkbox inputs
8730 * var checkbox1=new OO.ui.CheckboxInputWidget( {
8734 * var checkbox2=new OO.ui.CheckboxInputWidget( {
8737 * var checkbox3=new OO.ui.CheckboxInputWidget( {
8741 * // Create a fieldset layout with fields for each checkbox.
8742 * var fieldset = new OO.ui.FieldsetLayout( {
8743 * label: 'Checkboxes'
8745 * fieldset.addItems( [
8746 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
8747 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
8748 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
8750 * $( 'body' ).append( fieldset.$element );
8752 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8755 * @extends OO.ui.InputWidget
8758 * @param {Object} [config] Configuration options
8759 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
8761 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
8762 // Configuration initialization
8763 config
= config
|| {};
8765 // Parent constructor
8766 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
8770 .addClass( 'oo-ui-checkboxInputWidget' )
8771 // Required for pretty styling in WikimediaUI theme
8772 .append( $( '<span>' ) );
8773 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
8778 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
8780 /* Static Properties */
8786 OO
.ui
.CheckboxInputWidget
.static.tagName
= 'span';
8788 /* Static Methods */
8793 OO
.ui
.CheckboxInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8794 var state
= OO
.ui
.CheckboxInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8795 state
.checked
= config
.$input
.prop( 'checked' );
8805 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
8806 return $( '<input>' ).attr( 'type', 'checkbox' );
8812 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
8814 if ( !this.isDisabled() ) {
8815 // Allow the stack to clear so the value will be updated
8816 setTimeout( function () {
8817 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
8823 * Set selection state of this checkbox.
8825 * @param {boolean} state `true` for selected
8828 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
8830 if ( this.selected
!== state
) {
8831 this.selected
= state
;
8832 this.$input
.prop( 'checked', this.selected
);
8833 this.emit( 'change', this.selected
);
8839 * Check if this checkbox is selected.
8841 * @return {boolean} Checkbox is selected
8843 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
8844 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
8845 // it, and we won't know unless they're kind enough to trigger a 'change' event.
8846 var selected
= this.$input
.prop( 'checked' );
8847 if ( this.selected
!== selected
) {
8848 this.setSelected( selected
);
8850 return this.selected
;
8856 OO
.ui
.CheckboxInputWidget
.prototype.simulateLabelClick = function () {
8857 if ( !this.isDisabled() ) {
8858 this.$input
.click();
8866 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
8867 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
8868 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
8869 this.setSelected( state
.checked
);
8874 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
8875 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
8876 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
8877 * more information about input widgets.
8879 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
8880 * are no options. If no `value` configuration option is provided, the first option is selected.
8881 * If you need a state representing no value (no option being selected), use a DropdownWidget.
8883 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
8886 * // Example: A DropdownInputWidget with three options
8887 * var dropdownInput = new OO.ui.DropdownInputWidget( {
8889 * { data: 'a', label: 'First' },
8890 * { data: 'b', label: 'Second'},
8891 * { data: 'c', label: 'Third' }
8894 * $( 'body' ).append( dropdownInput.$element );
8896 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8899 * @extends OO.ui.InputWidget
8900 * @mixins OO.ui.mixin.TitledElement
8903 * @param {Object} [config] Configuration options
8904 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
8905 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
8907 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
8908 // Configuration initialization
8909 config
= config
|| {};
8911 // See InputWidget#reusePreInfuseDOM about config.$input
8912 if ( config
.$input
) {
8913 config
.$input
.addClass( 'oo-ui-element-hidden' );
8916 // Properties (must be done before parent constructor which calls #setDisabled)
8917 this.dropdownWidget
= new OO
.ui
.DropdownWidget( config
.dropdown
);
8919 // Parent constructor
8920 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
8922 // Mixin constructors
8923 OO
.ui
.mixin
.TitledElement
.call( this, config
);
8926 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
8929 this.setOptions( config
.options
|| [] );
8930 // Set the value again, after we did setOptions(). The call from parent doesn't work because the
8931 // widget has no valid options when it happens.
8932 this.setValue( config
.value
);
8934 .addClass( 'oo-ui-dropdownInputWidget' )
8935 .append( this.dropdownWidget
.$element
);
8936 this.setTabIndexedElement( null );
8941 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
8942 OO
.mixinClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.mixin
.TitledElement
);
8950 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
8951 return $( '<input>' ).attr( 'type', 'hidden' );
8955 * Handles menu select events.
8958 * @param {OO.ui.MenuOptionWidget|null} item Selected menu item
8960 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
8961 this.setValue( item
? item
.getData() : '' );
8967 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
8969 value
= this.cleanUpValue( value
);
8970 // Only allow setting values that are actually present in the dropdown
8971 selected
= this.dropdownWidget
.getMenu().getItemFromData( value
) ||
8972 this.dropdownWidget
.getMenu().getFirstSelectableItem();
8973 this.dropdownWidget
.getMenu().selectItem( selected
);
8974 value
= selected
? selected
.getData() : '';
8975 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
8982 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
8983 this.dropdownWidget
.setDisabled( state
);
8984 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
8989 * Set the options available for this input.
8991 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
8994 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
8996 value
= this.getValue(),
8999 // Rebuild the dropdown menu
9000 this.dropdownWidget
.getMenu()
9002 .addItems( options
.map( function ( opt
) {
9003 var optValue
= widget
.cleanUpValue( opt
.data
);
9005 if ( opt
.optgroup
=== undefined ) {
9006 return new OO
.ui
.MenuOptionWidget( {
9008 label
: opt
.label
!== undefined ? opt
.label
: optValue
9011 return new OO
.ui
.MenuSectionOptionWidget( {
9017 // Restore the previous value, or reset to something sensible
9018 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
9019 // Previous value is still available, ensure consistency with the dropdown
9020 this.setValue( value
);
9022 // No longer valid, reset
9023 if ( options
.length
) {
9024 this.setValue( options
[ 0 ].data
);
9034 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
9035 this.dropdownWidget
.focus();
9042 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
9043 this.dropdownWidget
.blur();
9048 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
9049 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
9050 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
9051 * please see the [OOjs UI documentation on MediaWiki][1].
9053 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9056 * // An example of selected, unselected, and disabled radio inputs
9057 * var radio1 = new OO.ui.RadioInputWidget( {
9061 * var radio2 = new OO.ui.RadioInputWidget( {
9064 * var radio3 = new OO.ui.RadioInputWidget( {
9068 * // Create a fieldset layout with fields for each radio button.
9069 * var fieldset = new OO.ui.FieldsetLayout( {
9070 * label: 'Radio inputs'
9072 * fieldset.addItems( [
9073 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
9074 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
9075 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
9077 * $( 'body' ).append( fieldset.$element );
9079 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9082 * @extends OO.ui.InputWidget
9085 * @param {Object} [config] Configuration options
9086 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
9088 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
9089 // Configuration initialization
9090 config
= config
|| {};
9092 // Parent constructor
9093 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
9097 .addClass( 'oo-ui-radioInputWidget' )
9098 // Required for pretty styling in WikimediaUI theme
9099 .append( $( '<span>' ) );
9100 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
9105 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
9107 /* Static Properties */
9113 OO
.ui
.RadioInputWidget
.static.tagName
= 'span';
9115 /* Static Methods */
9120 OO
.ui
.RadioInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9121 var state
= OO
.ui
.RadioInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9122 state
.checked
= config
.$input
.prop( 'checked' );
9132 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
9133 return $( '<input>' ).attr( 'type', 'radio' );
9139 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
9140 // RadioInputWidget doesn't track its state.
9144 * Set selection state of this radio button.
9146 * @param {boolean} state `true` for selected
9149 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
9150 // RadioInputWidget doesn't track its state.
9151 this.$input
.prop( 'checked', state
);
9156 * Check if this radio button is selected.
9158 * @return {boolean} Radio is selected
9160 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
9161 return this.$input
.prop( 'checked' );
9167 OO
.ui
.RadioInputWidget
.prototype.simulateLabelClick = function () {
9168 if ( !this.isDisabled() ) {
9169 this.$input
.click();
9177 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
9178 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
9179 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
9180 this.setSelected( state
.checked
);
9185 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
9186 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
9187 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
9188 * more information about input widgets.
9190 * This and OO.ui.DropdownInputWidget support the same configuration options.
9193 * // Example: A RadioSelectInputWidget with three options
9194 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
9196 * { data: 'a', label: 'First' },
9197 * { data: 'b', label: 'Second'},
9198 * { data: 'c', label: 'Third' }
9201 * $( 'body' ).append( radioSelectInput.$element );
9203 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9206 * @extends OO.ui.InputWidget
9209 * @param {Object} [config] Configuration options
9210 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9212 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
9213 // Configuration initialization
9214 config
= config
|| {};
9216 // Properties (must be done before parent constructor which calls #setDisabled)
9217 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
9219 // Parent constructor
9220 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
9223 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
9226 this.setOptions( config
.options
|| [] );
9228 .addClass( 'oo-ui-radioSelectInputWidget' )
9229 .append( this.radioSelectWidget
.$element
);
9230 this.setTabIndexedElement( null );
9235 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
9237 /* Static Methods */
9242 OO
.ui
.RadioSelectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9243 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9244 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
9251 OO
.ui
.RadioSelectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
9252 config
= OO
.ui
.RadioSelectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
9253 // Cannot reuse the `<input type=radio>` set
9254 delete config
.$input
;
9264 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
9265 return $( '<input>' ).attr( 'type', 'hidden' );
9269 * Handles menu select events.
9272 * @param {OO.ui.RadioOptionWidget} item Selected menu item
9274 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
9275 this.setValue( item
.getData() );
9281 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
9282 value
= this.cleanUpValue( value
);
9283 this.radioSelectWidget
.selectItemByData( value
);
9284 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
9291 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
9292 this.radioSelectWidget
.setDisabled( state
);
9293 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9298 * Set the options available for this input.
9300 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9303 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
9305 value
= this.getValue(),
9308 // Rebuild the radioSelect menu
9309 this.radioSelectWidget
9311 .addItems( options
.map( function ( opt
) {
9312 var optValue
= widget
.cleanUpValue( opt
.data
);
9313 return new OO
.ui
.RadioOptionWidget( {
9315 label
: opt
.label
!== undefined ? opt
.label
: optValue
9319 // Restore the previous value, or reset to something sensible
9320 if ( this.radioSelectWidget
.getItemFromData( value
) ) {
9321 // Previous value is still available, ensure consistency with the radioSelect
9322 this.setValue( value
);
9324 // No longer valid, reset
9325 if ( options
.length
) {
9326 this.setValue( options
[ 0 ].data
);
9336 OO
.ui
.RadioSelectInputWidget
.prototype.focus = function () {
9337 this.radioSelectWidget
.focus();
9344 OO
.ui
.RadioSelectInputWidget
.prototype.blur = function () {
9345 this.radioSelectWidget
.blur();
9350 * CheckboxMultiselectInputWidget is a
9351 * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
9352 * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
9353 * HTML `<input type=checkbox>` tags. Please see the [OOjs UI documentation on MediaWiki][1] for
9354 * more information about input widgets.
9357 * // Example: A CheckboxMultiselectInputWidget with three options
9358 * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
9360 * { data: 'a', label: 'First' },
9361 * { data: 'b', label: 'Second'},
9362 * { data: 'c', label: 'Third' }
9365 * $( 'body' ).append( multiselectInput.$element );
9367 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9370 * @extends OO.ui.InputWidget
9373 * @param {Object} [config] Configuration options
9374 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: …, disabled: … }`
9376 OO
.ui
.CheckboxMultiselectInputWidget
= function OoUiCheckboxMultiselectInputWidget( config
) {
9377 // Configuration initialization
9378 config
= config
|| {};
9380 // Properties (must be done before parent constructor which calls #setDisabled)
9381 this.checkboxMultiselectWidget
= new OO
.ui
.CheckboxMultiselectWidget();
9383 // Parent constructor
9384 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.call( this, config
);
9387 this.inputName
= config
.name
;
9391 .addClass( 'oo-ui-checkboxMultiselectInputWidget' )
9392 .append( this.checkboxMultiselectWidget
.$element
);
9393 // We don't use this.$input, but rather the CheckboxInputWidgets inside each option
9394 this.$input
.detach();
9395 this.setOptions( config
.options
|| [] );
9396 // Have to repeat this from parent, as we need options to be set up for this to make sense
9397 this.setValue( config
.value
);
9399 // setValue when checkboxMultiselectWidget changes
9400 this.checkboxMultiselectWidget
.on( 'change', function () {
9401 this.setValue( this.checkboxMultiselectWidget
.getSelectedItemsData() );
9407 OO
.inheritClass( OO
.ui
.CheckboxMultiselectInputWidget
, OO
.ui
.InputWidget
);
9409 /* Static Methods */
9414 OO
.ui
.CheckboxMultiselectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9415 var state
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9416 state
.value
= $( node
).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
9417 .toArray().map( function ( el
) { return el
.value
; } );
9424 OO
.ui
.CheckboxMultiselectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
9425 config
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
9426 // Cannot reuse the `<input type=checkbox>` set
9427 delete config
.$input
;
9437 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getInputElement = function () {
9439 return $( '<unused>' );
9445 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getValue = function () {
9446 var value
= this.$element
.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
9447 .toArray().map( function ( el
) { return el
.value
; } );
9448 if ( this.value
!== value
) {
9449 this.setValue( value
);
9457 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setValue = function ( value
) {
9458 value
= this.cleanUpValue( value
);
9459 this.checkboxMultiselectWidget
.selectItemsByData( value
);
9460 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setValue
.call( this, value
);
9465 * Clean up incoming value.
9467 * @param {string[]} value Original value
9468 * @return {string[]} Cleaned up value
9470 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.cleanUpValue = function ( value
) {
9473 if ( !Array
.isArray( value
) ) {
9476 for ( i
= 0; i
< value
.length
; i
++ ) {
9478 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( this, value
[ i
] );
9479 // Remove options that we don't have here
9480 if ( !this.checkboxMultiselectWidget
.getItemFromData( singleValue
) ) {
9483 cleanValue
.push( singleValue
);
9491 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setDisabled = function ( state
) {
9492 this.checkboxMultiselectWidget
.setDisabled( state
);
9493 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9498 * Set the options available for this input.
9500 * @param {Object[]} options Array of menu options in the format `{ data: …, label: …, disabled: … }`
9503 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setOptions = function ( options
) {
9506 // Rebuild the checkboxMultiselectWidget menu
9507 this.checkboxMultiselectWidget
9509 .addItems( options
.map( function ( opt
) {
9510 var optValue
, item
, optDisabled
;
9512 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( widget
, opt
.data
);
9513 optDisabled
= opt
.disabled
!== undefined ? opt
.disabled
: false;
9514 item
= new OO
.ui
.CheckboxMultioptionWidget( {
9516 label
: opt
.label
!== undefined ? opt
.label
: optValue
,
9517 disabled
: optDisabled
9519 // Set the 'name' and 'value' for form submission
9520 item
.checkbox
.$input
.attr( 'name', widget
.inputName
);
9521 item
.checkbox
.setValue( optValue
);
9525 // Re-set the value, checking the checkboxes as needed.
9526 // This will also get rid of any stale options that we just removed.
9527 this.setValue( this.getValue() );
9535 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.focus = function () {
9536 this.checkboxMultiselectWidget
.focus();
9541 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
9542 * size of the field as well as its presentation. In addition, these widgets can be configured
9543 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
9544 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
9545 * which modifies incoming values rather than validating them.
9546 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9548 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9551 * // Example of a text input widget
9552 * var textInput = new OO.ui.TextInputWidget( {
9553 * value: 'Text input'
9555 * $( 'body' ).append( textInput.$element );
9557 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9560 * @extends OO.ui.InputWidget
9561 * @mixins OO.ui.mixin.IconElement
9562 * @mixins OO.ui.mixin.IndicatorElement
9563 * @mixins OO.ui.mixin.PendingElement
9564 * @mixins OO.ui.mixin.LabelElement
9567 * @param {Object} [config] Configuration options
9568 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password'
9569 * 'email', 'url' or 'number'.
9570 * @cfg {string} [placeholder] Placeholder text
9571 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
9572 * instruct the browser to focus this widget.
9573 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
9574 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
9575 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
9576 * the value or placeholder text: `'before'` or `'after'`
9577 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
9578 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
9579 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
9580 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
9581 * (the value must contain only numbers); when RegExp, a regular expression that must match the
9582 * value for it to be considered valid; when Function, a function receiving the value as parameter
9583 * that must return true, or promise resolving to true, for it to be considered valid.
9585 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
9586 // Configuration initialization
9587 config
= $.extend( {
9589 labelPosition
: 'after'
9592 if ( config
.multiline
) {
9593 OO
.ui
.warnDeprecation( 'TextInputWidget: config.multiline is deprecated. Use the MultilineTextInputWidget instead. See T130434.' );
9594 return new OO
.ui
.MultilineTextInputWidget( config
);
9597 // Parent constructor
9598 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
9600 // Mixin constructors
9601 OO
.ui
.mixin
.IconElement
.call( this, config
);
9602 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
9603 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
9604 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9607 this.type
= this.getSaneType( config
);
9608 this.readOnly
= false;
9609 this.required
= false;
9610 this.validate
= null;
9611 this.styleHeight
= null;
9612 this.scrollWidth
= null;
9614 this.setValidation( config
.validate
);
9615 this.setLabelPosition( config
.labelPosition
);
9619 keypress
: this.onKeyPress
.bind( this ),
9620 blur
: this.onBlur
.bind( this ),
9621 focus
: this.onFocus
.bind( this )
9623 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
9624 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
9625 this.on( 'labelChange', this.updatePosition
.bind( this ) );
9626 this.on( 'change', OO
.ui
.debounce( this.onDebouncedChange
.bind( this ), 250 ) );
9630 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
9631 .append( this.$icon
, this.$indicator
);
9632 this.setReadOnly( !!config
.readOnly
);
9633 this.setRequired( !!config
.required
);
9634 if ( config
.placeholder
!== undefined ) {
9635 this.$input
.attr( 'placeholder', config
.placeholder
);
9637 if ( config
.maxLength
!== undefined ) {
9638 this.$input
.attr( 'maxlength', config
.maxLength
);
9640 if ( config
.autofocus
) {
9641 this.$input
.attr( 'autofocus', 'autofocus' );
9643 if ( config
.autocomplete
=== false ) {
9644 this.$input
.attr( 'autocomplete', 'off' );
9645 // Turning off autocompletion also disables "form caching" when the user navigates to a
9646 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
9648 beforeunload: function () {
9649 this.$input
.removeAttr( 'autocomplete' );
9651 pageshow: function () {
9652 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
9653 // whole page... it shouldn't hurt, though.
9654 this.$input
.attr( 'autocomplete', 'off' );
9659 this.isWaitingToBeAttached
= true;
9660 this.installParentChangeDetector();
9666 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
9667 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
9668 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
9669 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
9670 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
9672 /* Static Properties */
9674 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
9679 /* Static Methods */
9684 OO
.ui
.TextInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9685 var state
= OO
.ui
.TextInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9692 * An `enter` event is emitted when the user presses 'enter' inside the text box.
9700 * Handle icon mouse down events.
9703 * @param {jQuery.Event} e Mouse down event
9705 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
9706 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
9713 * Handle indicator mouse down events.
9716 * @param {jQuery.Event} e Mouse down event
9718 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
9719 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
9726 * Handle key press events.
9729 * @param {jQuery.Event} e Key press event
9730 * @fires enter If enter key is pressed
9732 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
9733 if ( e
.which
=== OO
.ui
.Keys
.ENTER
) {
9734 this.emit( 'enter', e
);
9739 * Handle blur events.
9742 * @param {jQuery.Event} e Blur event
9744 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
9745 this.setValidityFlag();
9749 * Handle focus events.
9752 * @param {jQuery.Event} e Focus event
9754 OO
.ui
.TextInputWidget
.prototype.onFocus = function () {
9755 if ( this.isWaitingToBeAttached
) {
9756 // If we've received focus, then we must be attached to the document, and if
9757 // isWaitingToBeAttached is still true, that means the handler never fired. Fire it now.
9758 this.onElementAttach();
9760 this.setValidityFlag( true );
9764 * Handle element attach events.
9767 * @param {jQuery.Event} e Element attach event
9769 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
9770 this.isWaitingToBeAttached
= false;
9771 // Any previously calculated size is now probably invalid if we reattached elsewhere
9772 this.valCache
= null;
9773 this.positionLabel();
9777 * Handle debounced change events.
9779 * @param {string} value
9782 OO
.ui
.TextInputWidget
.prototype.onDebouncedChange = function () {
9783 this.setValidityFlag();
9787 * Check if the input is {@link #readOnly read-only}.
9791 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
9792 return this.readOnly
;
9796 * Set the {@link #readOnly read-only} state of the input.
9798 * @param {boolean} state Make input read-only
9801 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
9802 this.readOnly
= !!state
;
9803 this.$input
.prop( 'readOnly', this.readOnly
);
9808 * Check if the input is {@link #required required}.
9812 OO
.ui
.TextInputWidget
.prototype.isRequired = function () {
9813 return this.required
;
9817 * Set the {@link #required required} state of the input.
9819 * @param {boolean} state Make input required
9822 OO
.ui
.TextInputWidget
.prototype.setRequired = function ( state
) {
9823 this.required
= !!state
;
9824 if ( this.required
) {
9826 .prop( 'required', true )
9827 .attr( 'aria-required', 'true' );
9828 if ( this.getIndicator() === null ) {
9829 this.setIndicator( 'required' );
9833 .prop( 'required', false )
9834 .removeAttr( 'aria-required' );
9835 if ( this.getIndicator() === 'required' ) {
9836 this.setIndicator( null );
9843 * Support function for making #onElementAttach work across browsers.
9845 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
9846 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
9848 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
9849 * first time that the element gets attached to the documented.
9851 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
9852 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
9853 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
9856 if ( MutationObserver
) {
9857 // The new way. If only it wasn't so ugly.
9859 if ( this.isElementAttached() ) {
9860 // Widget is attached already, do nothing. This breaks the functionality of this function when
9861 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
9862 // would require observation of the whole document, which would hurt performance of other,
9863 // more important code.
9867 // Find topmost node in the tree
9868 topmostNode
= this.$element
[ 0 ];
9869 while ( topmostNode
.parentNode
) {
9870 topmostNode
= topmostNode
.parentNode
;
9873 // We have no way to detect the $element being attached somewhere without observing the entire
9874 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
9875 // parent node of $element, and instead detect when $element is removed from it (and thus
9876 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
9877 // doesn't get attached, we end up back here and create the parent.
9879 mutationObserver
= new MutationObserver( function ( mutations
) {
9880 var i
, j
, removedNodes
;
9881 for ( i
= 0; i
< mutations
.length
; i
++ ) {
9882 removedNodes
= mutations
[ i
].removedNodes
;
9883 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
9884 if ( removedNodes
[ j
] === topmostNode
) {
9885 setTimeout( onRemove
, 0 );
9892 onRemove = function () {
9893 // If the node was attached somewhere else, report it
9894 if ( widget
.isElementAttached() ) {
9895 widget
.onElementAttach();
9897 mutationObserver
.disconnect();
9898 widget
.installParentChangeDetector();
9901 // Create a fake parent and observe it
9902 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
9903 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
9905 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
9906 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
9907 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
9915 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
9916 if ( this.getSaneType( config
) === 'number' ) {
9917 return $( '<input>' )
9918 .attr( 'step', 'any' )
9919 .attr( 'type', 'number' );
9921 return $( '<input>' ).attr( 'type', this.getSaneType( config
) );
9926 * Get sanitized value for 'type' for given config.
9928 * @param {Object} config Configuration options
9929 * @return {string|null}
9932 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
9933 var allowedTypes
= [
9940 return allowedTypes
.indexOf( config
.type
) !== -1 ? config
.type
: 'text';
9944 * Focus the input and select a specified range within the text.
9946 * @param {number} from Select from offset
9947 * @param {number} [to] Select to offset, defaults to from
9950 OO
.ui
.TextInputWidget
.prototype.selectRange = function ( from, to
) {
9951 var isBackwards
, start
, end
,
9952 input
= this.$input
[ 0 ];
9956 isBackwards
= to
< from;
9957 start
= isBackwards
? to
: from;
9958 end
= isBackwards
? from : to
;
9963 input
.setSelectionRange( start
, end
, isBackwards
? 'backward' : 'forward' );
9965 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
9966 // Rather than expensively check if the input is attached every time, just check
9967 // if it was the cause of an error being thrown. If not, rethrow the error.
9968 if ( this.getElementDocument().body
.contains( input
) ) {
9976 * Get an object describing the current selection range in a directional manner
9978 * @return {Object} Object containing 'from' and 'to' offsets
9980 OO
.ui
.TextInputWidget
.prototype.getRange = function () {
9981 var input
= this.$input
[ 0 ],
9982 start
= input
.selectionStart
,
9983 end
= input
.selectionEnd
,
9984 isBackwards
= input
.selectionDirection
=== 'backward';
9987 from: isBackwards
? end
: start
,
9988 to
: isBackwards
? start
: end
9993 * Get the length of the text input value.
9995 * This could differ from the length of #getValue if the
9996 * value gets filtered
9998 * @return {number} Input length
10000 OO
.ui
.TextInputWidget
.prototype.getInputLength = function () {
10001 return this.$input
[ 0 ].value
.length
;
10005 * Focus the input and select the entire text.
10009 OO
.ui
.TextInputWidget
.prototype.select = function () {
10010 return this.selectRange( 0, this.getInputLength() );
10014 * Focus the input and move the cursor to the start.
10018 OO
.ui
.TextInputWidget
.prototype.moveCursorToStart = function () {
10019 return this.selectRange( 0 );
10023 * Focus the input and move the cursor to the end.
10027 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
10028 return this.selectRange( this.getInputLength() );
10032 * Insert new content into the input.
10034 * @param {string} content Content to be inserted
10037 OO
.ui
.TextInputWidget
.prototype.insertContent = function ( content
) {
10039 range
= this.getRange(),
10040 value
= this.getValue();
10042 start
= Math
.min( range
.from, range
.to
);
10043 end
= Math
.max( range
.from, range
.to
);
10045 this.setValue( value
.slice( 0, start
) + content
+ value
.slice( end
) );
10046 this.selectRange( start
+ content
.length
);
10051 * Insert new content either side of a selection.
10053 * @param {string} pre Content to be inserted before the selection
10054 * @param {string} post Content to be inserted after the selection
10057 OO
.ui
.TextInputWidget
.prototype.encapsulateContent = function ( pre
, post
) {
10059 range
= this.getRange(),
10060 offset
= pre
.length
;
10062 start
= Math
.min( range
.from, range
.to
);
10063 end
= Math
.max( range
.from, range
.to
);
10065 this.selectRange( start
).insertContent( pre
);
10066 this.selectRange( offset
+ end
).insertContent( post
);
10068 this.selectRange( offset
+ start
, offset
+ end
);
10073 * Set the validation pattern.
10075 * The validation pattern is either a regular expression, a function, or the symbolic name of a
10076 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
10077 * value must contain only numbers).
10079 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
10080 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
10082 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
10083 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
10084 this.validate
= validate
;
10086 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
10091 * Sets the 'invalid' flag appropriately.
10093 * @param {boolean} [isValid] Optionally override validation result
10095 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
10097 setFlag = function ( valid
) {
10099 widget
.$input
.attr( 'aria-invalid', 'true' );
10101 widget
.$input
.removeAttr( 'aria-invalid' );
10103 widget
.setFlags( { invalid
: !valid
} );
10106 if ( isValid
!== undefined ) {
10107 setFlag( isValid
);
10109 this.getValidity().then( function () {
10118 * Get the validity of current value.
10120 * This method returns a promise that resolves if the value is valid and rejects if
10121 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
10123 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
10125 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
10128 function rejectOrResolve( valid
) {
10130 return $.Deferred().resolve().promise();
10132 return $.Deferred().reject().promise();
10136 // Check browser validity and reject if it is invalid
10138 this.$input
[ 0 ].checkValidity
!== undefined &&
10139 this.$input
[ 0 ].checkValidity() === false
10141 return rejectOrResolve( false );
10144 // Run our checks if the browser thinks the field is valid
10145 if ( this.validate
instanceof Function
) {
10146 result
= this.validate( this.getValue() );
10147 if ( result
&& $.isFunction( result
.promise
) ) {
10148 return result
.promise().then( function ( valid
) {
10149 return rejectOrResolve( valid
);
10152 return rejectOrResolve( result
);
10155 return rejectOrResolve( this.getValue().match( this.validate
) );
10160 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
10162 * @param {string} labelPosition Label position, 'before' or 'after'
10165 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
10166 this.labelPosition
= labelPosition
;
10167 if ( this.label
) {
10168 // If there is no label and we only change the position, #updatePosition is a no-op,
10169 // but it takes really a lot of work to do nothing.
10170 this.updatePosition();
10176 * Update the position of the inline label.
10178 * This method is called by #setLabelPosition, and can also be called on its own if
10179 * something causes the label to be mispositioned.
10183 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
10184 var after
= this.labelPosition
=== 'after';
10187 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
10188 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
10190 this.valCache
= null;
10191 this.scrollWidth
= null;
10192 this.positionLabel();
10198 * Position the label by setting the correct padding on the input.
10203 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
10204 var after
, rtl
, property
, newCss
;
10206 if ( this.isWaitingToBeAttached
) {
10207 // #onElementAttach will be called soon, which calls this method
10212 'padding-right': '',
10216 if ( this.label
) {
10217 this.$element
.append( this.$label
);
10219 this.$label
.detach();
10220 // Clear old values if present
10221 this.$input
.css( newCss
);
10225 after
= this.labelPosition
=== 'after';
10226 rtl
= this.$element
.css( 'direction' ) === 'rtl';
10227 property
= after
=== rtl
? 'padding-left' : 'padding-right';
10229 newCss
[ property
] = this.$label
.outerWidth( true ) + ( after
? this.scrollWidth
: 0 );
10230 // We have to clear the padding on the other side, in case the element direction changed
10231 this.$input
.css( newCss
);
10239 OO
.ui
.TextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
10240 OO
.ui
.TextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
10241 if ( state
.scrollTop
!== undefined ) {
10242 this.$input
.scrollTop( state
.scrollTop
);
10248 * @extends OO.ui.TextInputWidget
10251 * @param {Object} [config] Configuration options
10253 OO
.ui
.SearchInputWidget
= function OoUiSearchInputWidget( config
) {
10254 config
= $.extend( {
10258 // Set type to text so that TextInputWidget doesn't
10259 // get stuck in an infinite loop.
10260 config
.type
= 'text';
10262 // Parent constructor
10263 OO
.ui
.SearchInputWidget
.parent
.call( this, config
);
10266 this.connect( this, {
10271 this.$element
.addClass( 'oo-ui-textInputWidget-type-search' );
10272 this.updateSearchIndicator();
10273 this.connect( this, {
10274 disable
: 'onDisable'
10280 OO
.inheritClass( OO
.ui
.SearchInputWidget
, OO
.ui
.TextInputWidget
);
10288 OO
.ui
.SearchInputWidget
.prototype.getInputElement = function () {
10289 return $( '<input>' ).attr( 'type', 'search' );
10295 OO
.ui
.SearchInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
10296 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
10297 // Clear the text field
10298 this.setValue( '' );
10305 * Update the 'clear' indicator displayed on type: 'search' text
10306 * fields, hiding it when the field is already empty or when it's not
10309 OO
.ui
.SearchInputWidget
.prototype.updateSearchIndicator = function () {
10310 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
10311 this.setIndicator( null );
10313 this.setIndicator( 'clear' );
10318 * Handle change events.
10322 OO
.ui
.SearchInputWidget
.prototype.onChange = function () {
10323 this.updateSearchIndicator();
10327 * Handle disable events.
10329 * @param {boolean} disabled Element is disabled
10332 OO
.ui
.SearchInputWidget
.prototype.onDisable = function () {
10333 this.updateSearchIndicator();
10339 OO
.ui
.SearchInputWidget
.prototype.setReadOnly = function ( state
) {
10340 OO
.ui
.SearchInputWidget
.parent
.prototype.setReadOnly
.call( this, state
);
10341 this.updateSearchIndicator();
10347 * @extends OO.ui.TextInputWidget
10350 * @param {Object} [config] Configuration options
10351 * @cfg {number} [rows] Number of visible lines in textarea. If used with `autosize`,
10352 * specifies minimum number of rows to display.
10353 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
10354 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
10355 * Use the #maxRows config to specify a maximum number of displayed rows.
10356 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
10357 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
10359 OO
.ui
.MultilineTextInputWidget
= function OoUiMultilineTextInputWidget( config
) {
10360 config
= $.extend( {
10363 config
.multiline
= false;
10364 // Parent constructor
10365 OO
.ui
.MultilineTextInputWidget
.parent
.call( this, config
);
10368 this.multiline
= true;
10369 this.autosize
= !!config
.autosize
;
10370 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
10371 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
10373 // Clone for resizing
10374 if ( this.autosize
) {
10375 this.$clone
= this.$input
10377 .insertAfter( this.$input
)
10378 .attr( 'aria-hidden', 'true' )
10379 .addClass( 'oo-ui-element-hidden' );
10383 this.connect( this, {
10388 if ( this.multiline
&& config
.rows
) {
10389 this.$input
.attr( 'rows', config
.rows
);
10391 if ( this.autosize
) {
10392 this.isWaitingToBeAttached
= true;
10393 this.installParentChangeDetector();
10399 OO
.inheritClass( OO
.ui
.MultilineTextInputWidget
, OO
.ui
.TextInputWidget
);
10401 /* Static Methods */
10406 OO
.ui
.MultilineTextInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
10407 var state
= OO
.ui
.MultilineTextInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
10408 state
.scrollTop
= config
.$input
.scrollTop();
10417 OO
.ui
.MultilineTextInputWidget
.prototype.onElementAttach = function () {
10418 OO
.ui
.MultilineTextInputWidget
.parent
.prototype.onElementAttach
.call( this );
10423 * Handle change events.
10427 OO
.ui
.MultilineTextInputWidget
.prototype.onChange = function () {
10434 OO
.ui
.MultilineTextInputWidget
.prototype.updatePosition = function () {
10435 OO
.ui
.MultilineTextInputWidget
.parent
.prototype.updatePosition
.call( this );
10440 * Override TextInputWidget so it doesn't emit the 'enter' event.
10443 * @param {jQuery.Event} e Key press event
10445 OO
.ui
.MultilineTextInputWidget
.prototype.onKeyPress = function () {
10450 * Automatically adjust the size of the text input.
10452 * This only affects multiline inputs that are {@link #autosize autosized}.
10457 OO
.ui
.MultilineTextInputWidget
.prototype.adjustSize = function () {
10458 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
,
10459 idealHeight
, newHeight
, scrollWidth
, property
;
10461 if ( this.$input
.val() !== this.valCache
) {
10462 if ( this.autosize
) {
10464 .val( this.$input
.val() )
10465 .attr( 'rows', this.minRows
)
10466 // Set inline height property to 0 to measure scroll height
10467 .css( 'height', 0 );
10469 this.$clone
.removeClass( 'oo-ui-element-hidden' );
10471 this.valCache
= this.$input
.val();
10473 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
10475 // Remove inline height property to measure natural heights
10476 this.$clone
.css( 'height', '' );
10477 innerHeight
= this.$clone
.innerHeight();
10478 outerHeight
= this.$clone
.outerHeight();
10480 // Measure max rows height
10482 .attr( 'rows', this.maxRows
)
10483 .css( 'height', 'auto' )
10485 maxInnerHeight
= this.$clone
.innerHeight();
10487 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
10488 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
10489 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
10490 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
10492 this.$clone
.addClass( 'oo-ui-element-hidden' );
10494 // Only apply inline height when expansion beyond natural height is needed
10495 // Use the difference between the inner and outer height as a buffer
10496 newHeight
= idealHeight
> innerHeight
? idealHeight
+ ( outerHeight
- innerHeight
) : '';
10497 if ( newHeight
!== this.styleHeight
) {
10498 this.$input
.css( 'height', newHeight
);
10499 this.styleHeight
= newHeight
;
10500 this.emit( 'resize' );
10503 scrollWidth
= this.$input
[ 0 ].offsetWidth
- this.$input
[ 0 ].clientWidth
;
10504 if ( scrollWidth
!== this.scrollWidth
) {
10505 property
= this.$element
.css( 'direction' ) === 'rtl' ? 'left' : 'right';
10507 this.$label
.css( { right
: '', left
: '' } );
10508 this.$indicator
.css( { right
: '', left
: '' } );
10510 if ( scrollWidth
) {
10511 this.$indicator
.css( property
, scrollWidth
);
10512 if ( this.labelPosition
=== 'after' ) {
10513 this.$label
.css( property
, scrollWidth
);
10517 this.scrollWidth
= scrollWidth
;
10518 this.positionLabel();
10528 OO
.ui
.MultilineTextInputWidget
.prototype.getInputElement = function () {
10529 return $( '<textarea>' );
10533 * Check if the input supports multiple lines.
10535 * @return {boolean}
10537 OO
.ui
.MultilineTextInputWidget
.prototype.isMultiline = function () {
10538 return !!this.multiline
;
10542 * Check if the input automatically adjusts its size.
10544 * @return {boolean}
10546 OO
.ui
.MultilineTextInputWidget
.prototype.isAutosizing = function () {
10547 return !!this.autosize
;
10551 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
10552 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
10553 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
10555 * - by typing a value in the text input field. If the value exactly matches the value of a menu
10556 * option, that option will appear to be selected.
10557 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
10560 * After the user chooses an option, its `data` will be used as a new value for the widget.
10561 * A `label` also can be specified for each option: if given, it will be shown instead of the
10562 * `data` in the dropdown menu.
10564 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
10566 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
10569 * // Example: A ComboBoxInputWidget.
10570 * var comboBox = new OO.ui.ComboBoxInputWidget( {
10571 * value: 'Option 1',
10573 * { data: 'Option 1' },
10574 * { data: 'Option 2' },
10575 * { data: 'Option 3' }
10578 * $( 'body' ).append( comboBox.$element );
10581 * // Example: A ComboBoxInputWidget with additional option labels.
10582 * var comboBox = new OO.ui.ComboBoxInputWidget( {
10583 * value: 'Option 1',
10586 * data: 'Option 1',
10587 * label: 'Option One'
10590 * data: 'Option 2',
10591 * label: 'Option Two'
10594 * data: 'Option 3',
10595 * label: 'Option Three'
10599 * $( 'body' ).append( comboBox.$element );
10601 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
10604 * @extends OO.ui.TextInputWidget
10607 * @param {Object} [config] Configuration options
10608 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
10609 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
10610 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
10611 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
10612 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
10613 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
10615 OO
.ui
.ComboBoxInputWidget
= function OoUiComboBoxInputWidget( config
) {
10616 // Configuration initialization
10617 config
= $.extend( {
10618 autocomplete
: false
10621 // ComboBoxInputWidget shouldn't support `multiline`
10622 config
.multiline
= false;
10624 // See InputWidget#reusePreInfuseDOM about `config.$input`
10625 if ( config
.$input
) {
10626 config
.$input
.removeAttr( 'list' );
10629 // Parent constructor
10630 OO
.ui
.ComboBoxInputWidget
.parent
.call( this, config
);
10633 this.$overlay
= config
.$overlay
|| this.$element
;
10634 this.dropdownButton
= new OO
.ui
.ButtonWidget( {
10635 classes
: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ],
10637 disabled
: this.disabled
10639 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend(
10643 $floatableContainer
: this.$element
,
10644 disabled
: this.isDisabled()
10650 this.connect( this, {
10651 change
: 'onInputChange',
10652 enter
: 'onInputEnter'
10654 this.dropdownButton
.connect( this, {
10655 click
: 'onDropdownButtonClick'
10657 this.menu
.connect( this, {
10658 choose
: 'onMenuChoose',
10659 add
: 'onMenuItemsChange',
10660 remove
: 'onMenuItemsChange'
10664 this.$input
.attr( {
10666 'aria-owns': this.menu
.getElementId(),
10667 'aria-autocomplete': 'list'
10669 // Do not override options set via config.menu.items
10670 if ( config
.options
!== undefined ) {
10671 this.setOptions( config
.options
);
10673 this.$field
= $( '<div>' )
10674 .addClass( 'oo-ui-comboBoxInputWidget-field' )
10675 .append( this.$input
, this.dropdownButton
.$element
);
10677 .addClass( 'oo-ui-comboBoxInputWidget' )
10678 .append( this.$field
);
10679 this.$overlay
.append( this.menu
.$element
);
10680 this.onMenuItemsChange();
10685 OO
.inheritClass( OO
.ui
.ComboBoxInputWidget
, OO
.ui
.TextInputWidget
);
10690 * Get the combobox's menu.
10692 * @return {OO.ui.MenuSelectWidget} Menu widget
10694 OO
.ui
.ComboBoxInputWidget
.prototype.getMenu = function () {
10699 * Get the combobox's text input widget.
10701 * @return {OO.ui.TextInputWidget} Text input widget
10703 OO
.ui
.ComboBoxInputWidget
.prototype.getInput = function () {
10708 * Handle input change events.
10711 * @param {string} value New value
10713 OO
.ui
.ComboBoxInputWidget
.prototype.onInputChange = function ( value
) {
10714 var match
= this.menu
.getItemFromData( value
);
10716 this.menu
.selectItem( match
);
10717 if ( this.menu
.getHighlightedItem() ) {
10718 this.menu
.highlightItem( match
);
10721 if ( !this.isDisabled() ) {
10722 this.menu
.toggle( true );
10727 * Handle input enter events.
10731 OO
.ui
.ComboBoxInputWidget
.prototype.onInputEnter = function () {
10732 if ( !this.isDisabled() ) {
10733 this.menu
.toggle( false );
10738 * Handle button click events.
10742 OO
.ui
.ComboBoxInputWidget
.prototype.onDropdownButtonClick = function () {
10743 this.menu
.toggle();
10748 * Handle menu choose events.
10751 * @param {OO.ui.OptionWidget} item Chosen item
10753 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuChoose = function ( item
) {
10754 this.setValue( item
.getData() );
10758 * Handle menu item change events.
10762 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuItemsChange = function () {
10763 var match
= this.menu
.getItemFromData( this.getValue() );
10764 this.menu
.selectItem( match
);
10765 if ( this.menu
.getHighlightedItem() ) {
10766 this.menu
.highlightItem( match
);
10768 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu
.isEmpty() );
10774 OO
.ui
.ComboBoxInputWidget
.prototype.setDisabled = function ( disabled
) {
10776 OO
.ui
.ComboBoxInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
10778 if ( this.dropdownButton
) {
10779 this.dropdownButton
.setDisabled( this.isDisabled() );
10782 this.menu
.setDisabled( this.isDisabled() );
10789 * Set the options available for this input.
10791 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10794 OO
.ui
.ComboBoxInputWidget
.prototype.setOptions = function ( options
) {
10797 .addItems( options
.map( function ( opt
) {
10798 return new OO
.ui
.MenuOptionWidget( {
10800 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
10808 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
10809 * which is a widget that is specified by reference before any optional configuration settings.
10811 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
10813 * - **left**: The label is placed before the field-widget and aligned with the left margin.
10814 * A left-alignment is used for forms with many fields.
10815 * - **right**: The label is placed before the field-widget and aligned to the right margin.
10816 * A right-alignment is used for long but familiar forms which users tab through,
10817 * verifying the current field with a quick glance at the label.
10818 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
10819 * that users fill out from top to bottom.
10820 * - **inline**: The label is placed after the field-widget and aligned to the left.
10821 * An inline-alignment is best used with checkboxes or radio buttons.
10823 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
10824 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
10826 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
10829 * @extends OO.ui.Layout
10830 * @mixins OO.ui.mixin.LabelElement
10831 * @mixins OO.ui.mixin.TitledElement
10834 * @param {OO.ui.Widget} fieldWidget Field widget
10835 * @param {Object} [config] Configuration options
10836 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
10837 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
10838 * The array may contain strings or OO.ui.HtmlSnippet instances.
10839 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
10840 * The array may contain strings or OO.ui.HtmlSnippet instances.
10841 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
10842 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
10843 * For important messages, you are advised to use `notices`, as they are always shown.
10844 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
10845 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
10847 * @throws {Error} An error is thrown if no widget is specified
10849 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
10850 // Allow passing positional parameters inside the config object
10851 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
10852 config
= fieldWidget
;
10853 fieldWidget
= config
.fieldWidget
;
10856 // Make sure we have required constructor arguments
10857 if ( fieldWidget
=== undefined ) {
10858 throw new Error( 'Widget not found' );
10861 // Configuration initialization
10862 config
= $.extend( { align
: 'left' }, config
);
10864 // Parent constructor
10865 OO
.ui
.FieldLayout
.parent
.call( this, config
);
10867 // Mixin constructors
10868 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, {
10869 $label
: $( '<label>' )
10871 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
10874 this.fieldWidget
= fieldWidget
;
10877 this.$field
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
10878 this.$messages
= $( '<ul>' );
10879 this.$header
= $( '<span>' );
10880 this.$body
= $( '<div>' );
10882 if ( config
.help
) {
10883 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
10884 $overlay
: config
.$overlay
,
10888 classes
: [ 'oo-ui-fieldLayout-help' ],
10892 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
10893 this.popupButtonWidget
.getPopup().$body
.html( config
.help
.toString() );
10895 this.popupButtonWidget
.getPopup().$body
.text( config
.help
);
10897 this.$help
= this.popupButtonWidget
.$element
;
10899 this.$help
= $( [] );
10903 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
10906 if ( config
.help
) {
10907 // Set the 'aria-describedby' attribute on the fieldWidget
10908 // Preference given to an input or a button
10910 this.fieldWidget
.$input
||
10911 this.fieldWidget
.$button
||
10912 this.fieldWidget
.$element
10914 'aria-describedby',
10915 this.popupButtonWidget
.getPopup().getBodyId()
10918 if ( this.fieldWidget
.getInputId() ) {
10919 this.$label
.attr( 'for', this.fieldWidget
.getInputId() );
10921 this.$label
.on( 'click', function () {
10922 this.fieldWidget
.simulateLabelClick();
10927 .addClass( 'oo-ui-fieldLayout' )
10928 .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget
.isDisabled() )
10929 .append( this.$body
);
10930 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
10931 this.$header
.addClass( 'oo-ui-fieldLayout-header' );
10932 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
10934 .addClass( 'oo-ui-fieldLayout-field' )
10935 .append( this.fieldWidget
.$element
);
10937 this.setErrors( config
.errors
|| [] );
10938 this.setNotices( config
.notices
|| [] );
10939 this.setAlignment( config
.align
);
10940 // Call this again to take into account the widget's accessKey
10941 this.updateTitle();
10946 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
10947 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
10948 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
10953 * Handle field disable events.
10956 * @param {boolean} value Field is disabled
10958 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
10959 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
10963 * Get the widget contained by the field.
10965 * @return {OO.ui.Widget} Field widget
10967 OO
.ui
.FieldLayout
.prototype.getField = function () {
10968 return this.fieldWidget
;
10972 * Return `true` if the given field widget can be used with `'inline'` alignment (see
10973 * #setAlignment). Return `false` if it can't or if this can't be determined.
10975 * @return {boolean}
10977 OO
.ui
.FieldLayout
.prototype.isFieldInline = function () {
10978 // This is very simplistic, but should be good enough.
10979 return this.getField().$element
.prop( 'tagName' ).toLowerCase() === 'span';
10984 * @param {string} kind 'error' or 'notice'
10985 * @param {string|OO.ui.HtmlSnippet} text
10988 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
10989 var $listItem
, $icon
, message
;
10990 $listItem
= $( '<li>' );
10991 if ( kind
=== 'error' ) {
10992 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
10993 $listItem
.attr( 'role', 'alert' );
10994 } else if ( kind
=== 'notice' ) {
10995 $icon
= new OO
.ui
.IconWidget( { icon
: 'info' } ).$element
;
10999 message
= new OO
.ui
.LabelWidget( { label
: text
} );
11001 .append( $icon
, message
.$element
)
11002 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
11007 * Set the field alignment mode.
11010 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
11013 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
11014 if ( value
!== this.align
) {
11015 // Default to 'left'
11016 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
11020 if ( value
=== 'inline' && !this.isFieldInline() ) {
11023 // Reorder elements
11024 if ( value
=== 'top' ) {
11025 this.$header
.append( this.$label
, this.$help
);
11026 this.$body
.append( this.$header
, this.$field
);
11027 } else if ( value
=== 'inline' ) {
11028 this.$header
.append( this.$label
, this.$help
);
11029 this.$body
.append( this.$field
, this.$header
);
11031 this.$header
.append( this.$label
);
11032 this.$body
.append( this.$header
, this.$help
, this.$field
);
11034 // Set classes. The following classes can be used here:
11035 // * oo-ui-fieldLayout-align-left
11036 // * oo-ui-fieldLayout-align-right
11037 // * oo-ui-fieldLayout-align-top
11038 // * oo-ui-fieldLayout-align-inline
11039 if ( this.align
) {
11040 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
11042 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
11043 this.align
= value
;
11050 * Set the list of error messages.
11052 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
11053 * The array may contain strings or OO.ui.HtmlSnippet instances.
11056 OO
.ui
.FieldLayout
.prototype.setErrors = function ( errors
) {
11057 this.errors
= errors
.slice();
11058 this.updateMessages();
11063 * Set the list of notice messages.
11065 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
11066 * The array may contain strings or OO.ui.HtmlSnippet instances.
11069 OO
.ui
.FieldLayout
.prototype.setNotices = function ( notices
) {
11070 this.notices
= notices
.slice();
11071 this.updateMessages();
11076 * Update the rendering of error and notice messages.
11080 OO
.ui
.FieldLayout
.prototype.updateMessages = function () {
11082 this.$messages
.empty();
11084 if ( this.errors
.length
|| this.notices
.length
) {
11085 this.$body
.after( this.$messages
);
11087 this.$messages
.remove();
11091 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
11092 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
11094 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
11095 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
11100 * Include information about the widget's accessKey in our title. TitledElement calls this method.
11101 * (This is a bit of a hack.)
11104 * @param {string} title Tooltip label for 'title' attribute
11107 OO
.ui
.FieldLayout
.prototype.formatTitleWithAccessKey = function ( title
) {
11108 if ( this.fieldWidget
&& this.fieldWidget
.formatTitleWithAccessKey
) {
11109 return this.fieldWidget
.formatTitleWithAccessKey( title
);
11115 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
11116 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
11117 * is required and is specified before any optional configuration settings.
11119 * Labels can be aligned in one of four ways:
11121 * - **left**: The label is placed before the field-widget and aligned with the left margin.
11122 * A left-alignment is used for forms with many fields.
11123 * - **right**: The label is placed before the field-widget and aligned to the right margin.
11124 * A right-alignment is used for long but familiar forms which users tab through,
11125 * verifying the current field with a quick glance at the label.
11126 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
11127 * that users fill out from top to bottom.
11128 * - **inline**: The label is placed after the field-widget and aligned to the left.
11129 * An inline-alignment is best used with checkboxes or radio buttons.
11131 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
11132 * text is specified.
11135 * // Example of an ActionFieldLayout
11136 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
11137 * new OO.ui.TextInputWidget( {
11138 * placeholder: 'Field widget'
11140 * new OO.ui.ButtonWidget( {
11144 * label: 'An ActionFieldLayout. This label is aligned top',
11146 * help: 'This is help text'
11150 * $( 'body' ).append( actionFieldLayout.$element );
11153 * @extends OO.ui.FieldLayout
11156 * @param {OO.ui.Widget} fieldWidget Field widget
11157 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
11158 * @param {Object} config
11160 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
11161 // Allow passing positional parameters inside the config object
11162 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
11163 config
= fieldWidget
;
11164 fieldWidget
= config
.fieldWidget
;
11165 buttonWidget
= config
.buttonWidget
;
11168 // Parent constructor
11169 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
11172 this.buttonWidget
= buttonWidget
;
11173 this.$button
= $( '<span>' );
11174 this.$input
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
11178 .addClass( 'oo-ui-actionFieldLayout' );
11180 .addClass( 'oo-ui-actionFieldLayout-button' )
11181 .append( this.buttonWidget
.$element
);
11183 .addClass( 'oo-ui-actionFieldLayout-input' )
11184 .append( this.fieldWidget
.$element
);
11186 .append( this.$input
, this.$button
);
11191 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
11194 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
11195 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
11196 * configured with a label as well. For more information and examples,
11197 * please see the [OOjs UI documentation on MediaWiki][1].
11200 * // Example of a fieldset layout
11201 * var input1 = new OO.ui.TextInputWidget( {
11202 * placeholder: 'A text input field'
11205 * var input2 = new OO.ui.TextInputWidget( {
11206 * placeholder: 'A text input field'
11209 * var fieldset = new OO.ui.FieldsetLayout( {
11210 * label: 'Example of a fieldset layout'
11213 * fieldset.addItems( [
11214 * new OO.ui.FieldLayout( input1, {
11215 * label: 'Field One'
11217 * new OO.ui.FieldLayout( input2, {
11218 * label: 'Field Two'
11221 * $( 'body' ).append( fieldset.$element );
11223 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
11226 * @extends OO.ui.Layout
11227 * @mixins OO.ui.mixin.IconElement
11228 * @mixins OO.ui.mixin.LabelElement
11229 * @mixins OO.ui.mixin.GroupElement
11232 * @param {Object} [config] Configuration options
11233 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
11234 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
11235 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
11236 * For important messages, you are advised to use `notices`, as they are always shown.
11237 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
11238 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
11240 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
11241 // Configuration initialization
11242 config
= config
|| {};
11244 // Parent constructor
11245 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
11247 // Mixin constructors
11248 OO
.ui
.mixin
.IconElement
.call( this, config
);
11249 OO
.ui
.mixin
.LabelElement
.call( this, config
);
11250 OO
.ui
.mixin
.GroupElement
.call( this, config
);
11253 this.$header
= $( '<legend>' );
11254 if ( config
.help
) {
11255 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
11256 $overlay
: config
.$overlay
,
11260 classes
: [ 'oo-ui-fieldsetLayout-help' ],
11264 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
11265 this.popupButtonWidget
.getPopup().$body
.html( config
.help
.toString() );
11267 this.popupButtonWidget
.getPopup().$body
.text( config
.help
);
11269 this.$help
= this.popupButtonWidget
.$element
;
11271 this.$help
= $( [] );
11276 .addClass( 'oo-ui-fieldsetLayout-header' )
11277 .append( this.$icon
, this.$label
, this.$help
);
11278 this.$group
.addClass( 'oo-ui-fieldsetLayout-group' );
11280 .addClass( 'oo-ui-fieldsetLayout' )
11281 .prepend( this.$header
, this.$group
);
11282 if ( Array
.isArray( config
.items
) ) {
11283 this.addItems( config
.items
);
11289 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
11290 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
11291 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
11292 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
11294 /* Static Properties */
11300 OO
.ui
.FieldsetLayout
.static.tagName
= 'fieldset';
11303 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
11304 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
11305 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
11306 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
11308 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
11309 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
11310 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
11311 * some fancier controls. Some controls have both regular and InputWidget variants, for example
11312 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
11313 * often have simplified APIs to match the capabilities of HTML forms.
11314 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
11316 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
11317 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11320 * // Example of a form layout that wraps a fieldset layout
11321 * var input1 = new OO.ui.TextInputWidget( {
11322 * placeholder: 'Username'
11324 * var input2 = new OO.ui.TextInputWidget( {
11325 * placeholder: 'Password',
11328 * var submit = new OO.ui.ButtonInputWidget( {
11332 * var fieldset = new OO.ui.FieldsetLayout( {
11333 * label: 'A form layout'
11335 * fieldset.addItems( [
11336 * new OO.ui.FieldLayout( input1, {
11337 * label: 'Username',
11340 * new OO.ui.FieldLayout( input2, {
11341 * label: 'Password',
11344 * new OO.ui.FieldLayout( submit )
11346 * var form = new OO.ui.FormLayout( {
11347 * items: [ fieldset ],
11348 * action: '/api/formhandler',
11351 * $( 'body' ).append( form.$element );
11354 * @extends OO.ui.Layout
11355 * @mixins OO.ui.mixin.GroupElement
11358 * @param {Object} [config] Configuration options
11359 * @cfg {string} [method] HTML form `method` attribute
11360 * @cfg {string} [action] HTML form `action` attribute
11361 * @cfg {string} [enctype] HTML form `enctype` attribute
11362 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
11364 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
11367 // Configuration initialization
11368 config
= config
|| {};
11370 // Parent constructor
11371 OO
.ui
.FormLayout
.parent
.call( this, config
);
11373 // Mixin constructors
11374 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
11377 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
11379 // Make sure the action is safe
11380 action
= config
.action
;
11381 if ( action
!== undefined && !OO
.ui
.isSafeUrl( action
) ) {
11382 action
= './' + action
;
11387 .addClass( 'oo-ui-formLayout' )
11389 method
: config
.method
,
11391 enctype
: config
.enctype
11393 if ( Array
.isArray( config
.items
) ) {
11394 this.addItems( config
.items
);
11400 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
11401 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
11406 * A 'submit' event is emitted when the form is submitted.
11411 /* Static Properties */
11417 OO
.ui
.FormLayout
.static.tagName
= 'form';
11422 * Handle form submit events.
11425 * @param {jQuery.Event} e Submit event
11428 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
11429 if ( this.emit( 'submit' ) ) {
11435 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
11436 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
11439 * // Example of a panel layout
11440 * var panel = new OO.ui.PanelLayout( {
11444 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
11446 * $( 'body' ).append( panel.$element );
11449 * @extends OO.ui.Layout
11452 * @param {Object} [config] Configuration options
11453 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
11454 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
11455 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
11456 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
11458 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
11459 // Configuration initialization
11460 config
= $.extend( {
11467 // Parent constructor
11468 OO
.ui
.PanelLayout
.parent
.call( this, config
);
11471 this.$element
.addClass( 'oo-ui-panelLayout' );
11472 if ( config
.scrollable
) {
11473 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
11475 if ( config
.padded
) {
11476 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
11478 if ( config
.expanded
) {
11479 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
11481 if ( config
.framed
) {
11482 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
11488 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
11493 * Focus the panel layout
11495 * The default implementation just focuses the first focusable element in the panel
11497 OO
.ui
.PanelLayout
.prototype.focus = function () {
11498 OO
.ui
.findFocusable( this.$element
).focus();
11502 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
11503 * items), with small margins between them. Convenient when you need to put a number of block-level
11504 * widgets on a single line next to each other.
11506 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
11509 * // HorizontalLayout with a text input and a label
11510 * var layout = new OO.ui.HorizontalLayout( {
11512 * new OO.ui.LabelWidget( { label: 'Label' } ),
11513 * new OO.ui.TextInputWidget( { value: 'Text' } )
11516 * $( 'body' ).append( layout.$element );
11519 * @extends OO.ui.Layout
11520 * @mixins OO.ui.mixin.GroupElement
11523 * @param {Object} [config] Configuration options
11524 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
11526 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
11527 // Configuration initialization
11528 config
= config
|| {};
11530 // Parent constructor
11531 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
11533 // Mixin constructors
11534 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
11537 this.$element
.addClass( 'oo-ui-horizontalLayout' );
11538 if ( Array
.isArray( config
.items
) ) {
11539 this.addItems( config
.items
);
11545 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
11546 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);
11550 //# sourceMappingURL=oojs-ui-core.js.map