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-02-08T00:38:31Z
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 from :focusable in jQueryUI v1.11.4 - 2015-04-14
78 * @param {jQuery} $element Element to test
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
.filters
.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, 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
239 * @param {number} wait
240 * @param {boolean} immediate
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
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
286 * @param {number} wait
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
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 accept button of a confirmation dialog
366 'ooui-dialog-message-accept': 'OK',
367 // Default label for the reject button of a confirmation dialog
368 'ooui-dialog-message-reject': 'Cancel',
369 // Title for process dialog error description
370 'ooui-dialog-process-error': 'Something went wrong',
371 // Label for process dialog dismiss error button, visible when describing errors
372 'ooui-dialog-process-dismiss': 'Dismiss',
373 // Label for process dialog retry action button, visible when describing only recoverable errors
374 'ooui-dialog-process-retry': 'Try again',
375 // Label for process dialog retry action button, visible when describing only warnings
376 'ooui-dialog-process-continue': 'Continue',
377 // Label for the file selection widget's select file button
378 'ooui-selectfile-button-select': 'Select a file',
379 // Label for the file selection widget if file selection is not supported
380 'ooui-selectfile-not-supported': 'File selection is not supported',
381 // Label for the file selection widget when no file is currently selected
382 'ooui-selectfile-placeholder': 'No file is selected',
383 // Label for the file selection widget's drop target
384 'ooui-selectfile-dragdrop-placeholder': 'Drop file here'
388 * Get a localized message.
390 * After the message key, message parameters may optionally be passed. In the default implementation,
391 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
392 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
393 * they support unnamed, ordered message parameters.
395 * In environments that provide a localization system, this function should be overridden to
396 * return the message translated in the user's language. The default implementation always returns
397 * English messages. An example of doing this with [jQuery.i18n](https://github.com/wikimedia/jquery.i18n)
401 * var i, iLen, button,
402 * messagePath = 'oojs-ui/dist/i18n/',
403 * languages = [ $.i18n().locale, 'ur', 'en' ],
406 * for ( i = 0, iLen = languages.length; i < iLen; i++ ) {
407 * languageMap[ languages[ i ] ] = messagePath + languages[ i ].toLowerCase() + '.json';
410 * $.i18n().load( languageMap ).done( function() {
411 * // Replace the built-in `msg` only once we've loaded the internationalization.
412 * // OOjs UI uses `OO.ui.deferMsg` for all initially-loaded messages. So long as
413 * // you put off creating any widgets until this promise is complete, no English
414 * // will be displayed.
415 * OO.ui.msg = $.i18n;
417 * // A button displaying "OK" in the default locale
418 * button = new OO.ui.ButtonWidget( {
419 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
422 * $( 'body' ).append( button.$element );
424 * // A button displaying "OK" in Urdu
425 * $.i18n().locale = 'ur';
426 * button = new OO.ui.ButtonWidget( {
427 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
430 * $( 'body' ).append( button.$element );
433 * @param {string} key Message key
434 * @param {...Mixed} [params] Message parameters
435 * @return {string} Translated message with parameters substituted
437 OO
.ui
.msg = function ( key
) {
438 var message
= messages
[ key
],
439 params
= Array
.prototype.slice
.call( arguments
, 1 );
440 if ( typeof message
=== 'string' ) {
441 // Perform $1 substitution
442 message
= message
.replace( /\$(\d+)/g, function ( unused
, n
) {
443 var i
= parseInt( n
, 10 );
444 return params
[ i
- 1 ] !== undefined ? params
[ i
- 1 ] : '$' + n
;
447 // Return placeholder if message not found
448 message
= '[' + key
+ ']';
455 * Package a message and arguments for deferred resolution.
457 * Use this when you are statically specifying a message and the message may not yet be present.
459 * @param {string} key Message key
460 * @param {...Mixed} [params] Message parameters
461 * @return {Function} Function that returns the resolved message when executed
463 OO
.ui
.deferMsg = function () {
464 var args
= arguments
;
466 return OO
.ui
.msg
.apply( OO
.ui
, args
);
473 * If the message is a function it will be executed, otherwise it will pass through directly.
475 * @param {Function|string} msg Deferred message, or message text
476 * @return {string} Resolved message
478 OO
.ui
.resolveMsg = function ( msg
) {
479 if ( $.isFunction( msg
) ) {
486 * @param {string} url
489 OO
.ui
.isSafeUrl = function ( url
) {
490 // Keep this function in sync with php/Tag.php
491 var i
, protocolWhitelist
;
493 function stringStartsWith( haystack
, needle
) {
494 return haystack
.substr( 0, needle
.length
) === needle
;
497 protocolWhitelist
= [
498 'bitcoin', 'ftp', 'ftps', 'geo', 'git', 'gopher', 'http', 'https', 'irc', 'ircs',
499 'magnet', 'mailto', 'mms', 'news', 'nntp', 'redis', 'sftp', 'sip', 'sips', 'sms', 'ssh',
500 'svn', 'tel', 'telnet', 'urn', 'worldwind', 'xmpp'
507 for ( i
= 0; i
< protocolWhitelist
.length
; i
++ ) {
508 if ( stringStartsWith( url
, protocolWhitelist
[ i
] + ':' ) ) {
513 // This matches '//' too
514 if ( stringStartsWith( url
, '/' ) || stringStartsWith( url
, './' ) ) {
517 if ( stringStartsWith( url
, '?' ) || stringStartsWith( url
, '#' ) ) {
525 * Check if the user has a 'mobile' device.
527 * For our purposes this means the user is primarily using an
528 * on-screen keyboard, touch input instead of a mouse and may
529 * have a physically small display.
531 * It is left up to implementors to decide how to compute this
532 * so the default implementation always returns false.
534 * @return {boolean} Use is on a mobile device
536 OO
.ui
.isMobile = function () {
545 * Namespace for OOjs UI mixins.
547 * Mixins are named according to the type of object they are intended to
548 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
549 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
550 * is intended to be mixed in to an instance of OO.ui.Widget.
558 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
559 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
560 * connected to them and can't be interacted with.
566 * @param {Object} [config] Configuration options
567 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
568 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
570 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
571 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
572 * @cfg {string} [text] Text to insert
573 * @cfg {Array} [content] An array of content elements to append (after #text).
574 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
575 * Instances of OO.ui.Element will have their $element appended.
576 * @cfg {jQuery} [$content] Content elements to append (after #text).
577 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
578 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
579 * Data can also be specified with the #setData method.
581 OO
.ui
.Element
= function OoUiElement( config
) {
582 // Configuration initialization
583 config
= config
|| {};
588 this.data
= config
.data
;
589 this.$element
= config
.$element
||
590 $( document
.createElement( this.getTagName() ) );
591 this.elementGroup
= null;
594 if ( Array
.isArray( config
.classes
) ) {
595 this.$element
.addClass( config
.classes
.join( ' ' ) );
598 this.$element
.attr( 'id', config
.id
);
601 this.$element
.text( config
.text
);
603 if ( config
.content
) {
604 // The `content` property treats plain strings as text; use an
605 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
606 // appropriate $element appended.
607 this.$element
.append( config
.content
.map( function ( v
) {
608 if ( typeof v
=== 'string' ) {
609 // Escape string so it is properly represented in HTML.
610 return document
.createTextNode( v
);
611 } else if ( v
instanceof OO
.ui
.HtmlSnippet
) {
614 } else if ( v
instanceof OO
.ui
.Element
) {
620 if ( config
.$content
) {
621 // The `$content` property treats plain strings as HTML.
622 this.$element
.append( config
.$content
);
628 OO
.initClass( OO
.ui
.Element
);
630 /* Static Properties */
633 * The name of the HTML tag used by the element.
635 * The static value may be ignored if the #getTagName method is overridden.
641 OO
.ui
.Element
.static.tagName
= 'div';
646 * Reconstitute a JavaScript object corresponding to a widget created
647 * by the PHP implementation.
649 * @param {string|HTMLElement|jQuery} idOrNode
650 * A DOM id (if a string) or node for the widget to infuse.
651 * @return {OO.ui.Element}
652 * The `OO.ui.Element` corresponding to this (infusable) document node.
653 * For `Tag` objects emitted on the HTML side (used occasionally for content)
654 * the value returned is a newly-created Element wrapping around the existing
657 OO
.ui
.Element
.static.infuse = function ( idOrNode
) {
658 var obj
= OO
.ui
.Element
.static.unsafeInfuse( idOrNode
, false );
659 // Verify that the type matches up.
660 // FIXME: uncomment after T89721 is fixed (see T90929)
662 if ( !( obj instanceof this['class'] ) ) {
663 throw new Error( 'Infusion type mismatch!' );
670 * Implementation helper for `infuse`; skips the type check and has an
671 * extra property so that only the top-level invocation touches the DOM.
674 * @param {string|HTMLElement|jQuery} idOrNode
675 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
676 * when the top-level widget of this infusion is inserted into DOM,
677 * replacing the original node; or false for top-level invocation.
678 * @return {OO.ui.Element}
680 OO
.ui
.Element
.static.unsafeInfuse = function ( idOrNode
, domPromise
) {
681 // look for a cached result of a previous infusion.
682 var id
, $elem
, data
, cls
, parts
, parent
, obj
, top
, state
, infusedChildren
;
683 if ( typeof idOrNode
=== 'string' ) {
685 $elem
= $( document
.getElementById( id
) );
687 $elem
= $( idOrNode
);
688 id
= $elem
.attr( 'id' );
690 if ( !$elem
.length
) {
691 throw new Error( 'Widget not found: ' + id
);
693 if ( $elem
[ 0 ].oouiInfused
) {
694 $elem
= $elem
[ 0 ].oouiInfused
;
696 data
= $elem
.data( 'ooui-infused' );
699 if ( data
=== true ) {
700 throw new Error( 'Circular dependency! ' + id
);
703 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
704 state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
705 // restore dynamic state after the new element is re-inserted into DOM under infused parent
706 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
707 infusedChildren
= $elem
.data( 'ooui-infused-children' );
708 if ( infusedChildren
&& infusedChildren
.length
) {
709 infusedChildren
.forEach( function ( data
) {
710 var state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
711 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
717 data
= $elem
.attr( 'data-ooui' );
719 throw new Error( 'No infusion data found: ' + id
);
722 data
= $.parseJSON( data
);
726 if ( !( data
&& data
._
) ) {
727 throw new Error( 'No valid infusion data found: ' + id
);
729 if ( data
._
=== 'Tag' ) {
730 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
731 return new OO
.ui
.Element( { $element
: $elem
} );
733 parts
= data
._
.split( '.' );
734 cls
= OO
.getProp
.apply( OO
, [ window
].concat( parts
) );
735 if ( cls
=== undefined ) {
736 // The PHP output might be old and not including the "OO.ui" prefix
737 // TODO: Remove this back-compat after next major release
738 cls
= OO
.getProp
.apply( OO
, [ OO
.ui
].concat( parts
) );
739 if ( cls
=== undefined ) {
740 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
744 // Verify that we're creating an OO.ui.Element instance
747 while ( parent
!== undefined ) {
748 if ( parent
=== OO
.ui
.Element
) {
753 parent
= parent
.parent
;
756 if ( parent
!== OO
.ui
.Element
) {
757 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
760 if ( domPromise
=== false ) {
762 domPromise
= top
.promise();
764 $elem
.data( 'ooui-infused', true ); // prevent loops
765 data
.id
= id
; // implicit
766 infusedChildren
= [];
767 data
= OO
.copy( data
, null, function deserialize( value
) {
769 if ( OO
.isPlainObject( value
) ) {
771 infused
= OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, domPromise
);
772 infusedChildren
.push( infused
);
773 // Flatten the structure
774 infusedChildren
.push
.apply( infusedChildren
, infused
.$element
.data( 'ooui-infused-children' ) || [] );
775 infused
.$element
.removeData( 'ooui-infused-children' );
778 if ( value
.html
!== undefined ) {
779 return new OO
.ui
.HtmlSnippet( value
.html
);
783 // allow widgets to reuse parts of the DOM
784 data
= cls
.static.reusePreInfuseDOM( $elem
[ 0 ], data
);
785 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
786 state
= cls
.static.gatherPreInfuseState( $elem
[ 0 ], data
);
788 // eslint-disable-next-line new-cap
789 obj
= new cls( data
);
790 // now replace old DOM with this new DOM.
792 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
793 // so only mutate the DOM if we need to.
794 if ( $elem
[ 0 ] !== obj
.$element
[ 0 ] ) {
795 $elem
.replaceWith( obj
.$element
);
796 // This element is now gone from the DOM, but if anyone is holding a reference to it,
797 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
798 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
799 $elem
[ 0 ].oouiInfused
= obj
.$element
;
803 obj
.$element
.data( 'ooui-infused', obj
);
804 obj
.$element
.data( 'ooui-infused-children', infusedChildren
);
805 // set the 'data-ooui' attribute so we can identify infused widgets
806 obj
.$element
.attr( 'data-ooui', '' );
807 // restore dynamic state after the new element is inserted into DOM
808 domPromise
.done( obj
.restorePreInfuseState
.bind( obj
, state
) );
813 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
815 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
816 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
817 * constructor, which will be given the enhanced config.
820 * @param {HTMLElement} node
821 * @param {Object} config
824 OO
.ui
.Element
.static.reusePreInfuseDOM = function ( node
, config
) {
829 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of an HTML DOM node
830 * (and its children) that represent an Element of the same class and the given configuration,
831 * generated by the PHP implementation.
833 * This method is called just before `node` is detached from the DOM. The return value of this
834 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
835 * is inserted into DOM to replace `node`.
838 * @param {HTMLElement} node
839 * @param {Object} config
842 OO
.ui
.Element
.static.gatherPreInfuseState = function () {
847 * Get a jQuery function within a specific document.
850 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
851 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
853 * @return {Function} Bound jQuery function
855 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
856 function wrapper( selector
) {
857 return $( selector
, wrapper
.context
);
860 wrapper
.context
= this.getDocument( context
);
863 wrapper
.$iframe
= $iframe
;
870 * Get the document of an element.
873 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
874 * @return {HTMLDocument|null} Document object
876 OO
.ui
.Element
.static.getDocument = function ( obj
) {
877 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
878 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
879 // Empty jQuery selections might have a context
886 ( obj
.nodeType
=== 9 && obj
) ||
891 * Get the window of an element or document.
894 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
895 * @return {Window} Window object
897 OO
.ui
.Element
.static.getWindow = function ( obj
) {
898 var doc
= this.getDocument( obj
);
899 return doc
.defaultView
;
903 * Get the direction of an element or document.
906 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
907 * @return {string} Text direction, either 'ltr' or 'rtl'
909 OO
.ui
.Element
.static.getDir = function ( obj
) {
912 if ( obj
instanceof jQuery
) {
915 isDoc
= obj
.nodeType
=== 9;
916 isWin
= obj
.document
!== undefined;
917 if ( isDoc
|| isWin
) {
923 return $( obj
).css( 'direction' );
927 * Get the offset between two frames.
929 * TODO: Make this function not use recursion.
932 * @param {Window} from Window of the child frame
933 * @param {Window} [to=window] Window of the parent frame
934 * @param {Object} [offset] Offset to start with, used internally
935 * @return {Object} Offset object, containing left and top properties
937 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
938 var i
, len
, frames
, frame
, rect
;
944 offset
= { top
: 0, left
: 0 };
946 if ( from.parent
=== from ) {
950 // Get iframe element
951 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
952 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
953 if ( frames
[ i
].contentWindow
=== from ) {
959 // Recursively accumulate offset values
961 rect
= frame
.getBoundingClientRect();
962 offset
.left
+= rect
.left
;
963 offset
.top
+= rect
.top
;
965 this.getFrameOffset( from.parent
, offset
);
972 * Get the offset between two elements.
974 * The two elements may be in a different frame, but in that case the frame $element is in must
975 * be contained in the frame $anchor is in.
978 * @param {jQuery} $element Element whose position to get
979 * @param {jQuery} $anchor Element to get $element's position relative to
980 * @return {Object} Translated position coordinates, containing top and left properties
982 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
983 var iframe
, iframePos
,
984 pos
= $element
.offset(),
985 anchorPos
= $anchor
.offset(),
986 elementDocument
= this.getDocument( $element
),
987 anchorDocument
= this.getDocument( $anchor
);
989 // If $element isn't in the same document as $anchor, traverse up
990 while ( elementDocument
!== anchorDocument
) {
991 iframe
= elementDocument
.defaultView
.frameElement
;
993 throw new Error( '$element frame is not contained in $anchor frame' );
995 iframePos
= $( iframe
).offset();
996 pos
.left
+= iframePos
.left
;
997 pos
.top
+= iframePos
.top
;
998 elementDocument
= iframe
.ownerDocument
;
1000 pos
.left
-= anchorPos
.left
;
1001 pos
.top
-= anchorPos
.top
;
1006 * Get element border sizes.
1009 * @param {HTMLElement} el Element to measure
1010 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1012 OO
.ui
.Element
.static.getBorders = function ( el
) {
1013 var doc
= el
.ownerDocument
,
1014 win
= doc
.defaultView
,
1015 style
= win
.getComputedStyle( el
, null ),
1017 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
1018 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
1019 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
1020 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
1031 * Get dimensions of an element or window.
1034 * @param {HTMLElement|Window} el Element to measure
1035 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1037 OO
.ui
.Element
.static.getDimensions = function ( el
) {
1039 doc
= el
.ownerDocument
|| el
.document
,
1040 win
= doc
.defaultView
;
1042 if ( win
=== el
|| el
=== doc
.documentElement
) {
1045 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
1047 top
: $win
.scrollTop(),
1048 left
: $win
.scrollLeft()
1050 scrollbar
: { right
: 0, bottom
: 0 },
1054 bottom
: $win
.innerHeight(),
1055 right
: $win
.innerWidth()
1061 borders
: this.getBorders( el
),
1063 top
: $el
.scrollTop(),
1064 left
: $el
.scrollLeft()
1067 right
: $el
.innerWidth() - el
.clientWidth
,
1068 bottom
: $el
.innerHeight() - el
.clientHeight
1070 rect
: el
.getBoundingClientRect()
1076 * Get scrollable object parent
1078 * documentElement can't be used to get or set the scrollTop
1079 * property on Blink. Changing and testing its value lets us
1080 * use 'body' or 'documentElement' based on what is working.
1082 * https://code.google.com/p/chromium/issues/detail?id=303131
1085 * @param {HTMLElement} el Element to find scrollable parent for
1086 * @return {HTMLElement} Scrollable parent
1088 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1089 var scrollTop
, body
;
1091 if ( OO
.ui
.scrollableElement
=== undefined ) {
1092 body
= el
.ownerDocument
.body
;
1093 scrollTop
= body
.scrollTop
;
1096 if ( body
.scrollTop
=== 1 ) {
1097 body
.scrollTop
= scrollTop
;
1098 OO
.ui
.scrollableElement
= 'body';
1100 OO
.ui
.scrollableElement
= 'documentElement';
1104 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1108 * Get closest scrollable container.
1110 * Traverses up until either a scrollable element or the root is reached, in which case the window
1114 * @param {HTMLElement} el Element to find scrollable container for
1115 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1116 * @return {HTMLElement} Closest scrollable container
1118 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1120 // props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
1121 props
= [ 'overflow-x', 'overflow-y' ],
1122 $parent
= $( el
).parent();
1124 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1125 props
= [ 'overflow-' + dimension
];
1128 while ( $parent
.length
) {
1129 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1130 return $parent
[ 0 ];
1134 val
= $parent
.css( props
[ i
] );
1135 if ( val
=== 'auto' || val
=== 'scroll' ) {
1136 return $parent
[ 0 ];
1139 $parent
= $parent
.parent();
1141 return this.getDocument( el
).body
;
1145 * Scroll element into view.
1148 * @param {HTMLElement} el Element to scroll into view
1149 * @param {Object} [config] Configuration options
1150 * @param {string} [config.duration='fast'] jQuery animation duration value
1151 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1152 * to scroll in both directions
1153 * @param {Function} [config.complete] Function to call when scrolling completes.
1154 * Deprecated since 0.15.4, use the return promise instead.
1155 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1157 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1158 var position
, animations
, callback
, container
, $container
, elementDimensions
, containerDimensions
, $window
,
1159 deferred
= $.Deferred();
1161 // Configuration initialization
1162 config
= config
|| {};
1165 callback
= typeof config
.complete
=== 'function' && config
.complete
;
1167 OO
.ui
.warnDeprecation( 'Element#scrollIntoView: The `complete` callback config option is deprecated. Use the return promise instead.' );
1169 container
= this.getClosestScrollableContainer( el
, config
.direction
);
1170 $container
= $( container
);
1171 elementDimensions
= this.getDimensions( el
);
1172 containerDimensions
= this.getDimensions( container
);
1173 $window
= $( this.getWindow( el
) );
1175 // Compute the element's position relative to the container
1176 if ( $container
.is( 'html, body' ) ) {
1177 // If the scrollable container is the root, this is easy
1179 top
: elementDimensions
.rect
.top
,
1180 bottom
: $window
.innerHeight() - elementDimensions
.rect
.bottom
,
1181 left
: elementDimensions
.rect
.left
,
1182 right
: $window
.innerWidth() - elementDimensions
.rect
.right
1185 // Otherwise, we have to subtract el's coordinates from container's coordinates
1187 top
: elementDimensions
.rect
.top
- ( containerDimensions
.rect
.top
+ containerDimensions
.borders
.top
),
1188 bottom
: containerDimensions
.rect
.bottom
- containerDimensions
.borders
.bottom
- containerDimensions
.scrollbar
.bottom
- elementDimensions
.rect
.bottom
,
1189 left
: elementDimensions
.rect
.left
- ( containerDimensions
.rect
.left
+ containerDimensions
.borders
.left
),
1190 right
: containerDimensions
.rect
.right
- containerDimensions
.borders
.right
- containerDimensions
.scrollbar
.right
- elementDimensions
.rect
.right
1194 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1195 if ( position
.top
< 0 ) {
1196 animations
.scrollTop
= containerDimensions
.scroll
.top
+ position
.top
;
1197 } else if ( position
.top
> 0 && position
.bottom
< 0 ) {
1198 animations
.scrollTop
= containerDimensions
.scroll
.top
+ Math
.min( position
.top
, -position
.bottom
);
1201 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1202 if ( position
.left
< 0 ) {
1203 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ position
.left
;
1204 } else if ( position
.left
> 0 && position
.right
< 0 ) {
1205 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ Math
.min( position
.left
, -position
.right
);
1208 if ( !$.isEmptyObject( animations
) ) {
1209 $container
.stop( true ).animate( animations
, config
.duration
=== undefined ? 'fast' : config
.duration
);
1210 $container
.queue( function ( next
) {
1223 return deferred
.promise();
1227 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1228 * and reserve space for them, because it probably doesn't.
1230 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1231 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1232 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1233 * and then reattach (or show) them back.
1236 * @param {HTMLElement} el Element to reconsider the scrollbars on
1238 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1239 var i
, len
, scrollLeft
, scrollTop
, nodes
= [];
1240 // Save scroll position
1241 scrollLeft
= el
.scrollLeft
;
1242 scrollTop
= el
.scrollTop
;
1243 // Detach all children
1244 while ( el
.firstChild
) {
1245 nodes
.push( el
.firstChild
);
1246 el
.removeChild( el
.firstChild
);
1249 void el
.offsetHeight
;
1250 // Reattach all children
1251 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1252 el
.appendChild( nodes
[ i
] );
1254 // Restore scroll position (no-op if scrollbars disappeared)
1255 el
.scrollLeft
= scrollLeft
;
1256 el
.scrollTop
= scrollTop
;
1262 * Toggle visibility of an element.
1264 * @param {boolean} [show] Make element visible, omit to toggle visibility
1268 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1269 show
= show
=== undefined ? !this.visible
: !!show
;
1271 if ( show
!== this.isVisible() ) {
1272 this.visible
= show
;
1273 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1274 this.emit( 'toggle', show
);
1281 * Check if element is visible.
1283 * @return {boolean} element is visible
1285 OO
.ui
.Element
.prototype.isVisible = function () {
1286 return this.visible
;
1292 * @return {Mixed} Element data
1294 OO
.ui
.Element
.prototype.getData = function () {
1301 * @param {Mixed} data Element data
1304 OO
.ui
.Element
.prototype.setData = function ( data
) {
1310 * Check if element supports one or more methods.
1312 * @param {string|string[]} methods Method or list of methods to check
1313 * @return {boolean} All methods are supported
1315 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1319 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1320 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1321 if ( $.isFunction( this[ methods
[ i
] ] ) ) {
1326 return methods
.length
=== support
;
1330 * Update the theme-provided classes.
1332 * @localdoc This is called in element mixins and widget classes any time state changes.
1333 * Updating is debounced, minimizing overhead of changing multiple attributes and
1334 * guaranteeing that theme updates do not occur within an element's constructor
1336 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1337 OO
.ui
.theme
.queueUpdateElementClasses( this );
1341 * Get the HTML tag name.
1343 * Override this method to base the result on instance information.
1345 * @return {string} HTML tag name
1347 OO
.ui
.Element
.prototype.getTagName = function () {
1348 return this.constructor.static.tagName
;
1352 * Check if the element is attached to the DOM
1354 * @return {boolean} The element is attached to the DOM
1356 OO
.ui
.Element
.prototype.isElementAttached = function () {
1357 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1361 * Get the DOM document.
1363 * @return {HTMLDocument} Document object
1365 OO
.ui
.Element
.prototype.getElementDocument = function () {
1366 // Don't cache this in other ways either because subclasses could can change this.$element
1367 return OO
.ui
.Element
.static.getDocument( this.$element
);
1371 * Get the DOM window.
1373 * @return {Window} Window object
1375 OO
.ui
.Element
.prototype.getElementWindow = function () {
1376 return OO
.ui
.Element
.static.getWindow( this.$element
);
1380 * Get closest scrollable container.
1382 * @return {HTMLElement} Closest scrollable container
1384 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1385 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1389 * Get group element is in.
1391 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1393 OO
.ui
.Element
.prototype.getElementGroup = function () {
1394 return this.elementGroup
;
1398 * Set group element is in.
1400 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1403 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1404 this.elementGroup
= group
;
1409 * Scroll element into view.
1411 * @param {Object} [config] Configuration options
1412 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1414 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1416 !this.isElementAttached() ||
1417 !this.isVisible() ||
1418 ( this.getElementGroup() && !this.getElementGroup().isVisible() )
1420 return $.Deferred().resolve();
1422 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1426 * Restore the pre-infusion dynamic state for this widget.
1428 * This method is called after #$element has been inserted into DOM. The parameter is the return
1429 * value of #gatherPreInfuseState.
1432 * @param {Object} state
1434 OO
.ui
.Element
.prototype.restorePreInfuseState = function () {
1438 * Wraps an HTML snippet for use with configuration values which default
1439 * to strings. This bypasses the default html-escaping done to string
1445 * @param {string} [content] HTML content
1447 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
1449 this.content
= content
;
1454 OO
.initClass( OO
.ui
.HtmlSnippet
);
1461 * @return {string} Unchanged HTML snippet.
1463 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
1464 return this.content
;
1468 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1469 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1470 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1471 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1472 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1476 * @extends OO.ui.Element
1477 * @mixins OO.EventEmitter
1480 * @param {Object} [config] Configuration options
1482 OO
.ui
.Layout
= function OoUiLayout( config
) {
1483 // Configuration initialization
1484 config
= config
|| {};
1486 // Parent constructor
1487 OO
.ui
.Layout
.parent
.call( this, config
);
1489 // Mixin constructors
1490 OO
.EventEmitter
.call( this );
1493 this.$element
.addClass( 'oo-ui-layout' );
1498 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1499 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1502 * Widgets are compositions of one or more OOjs UI elements that users can both view
1503 * and interact with. All widgets can be configured and modified via a standard API,
1504 * and their state can change dynamically according to a model.
1508 * @extends OO.ui.Element
1509 * @mixins OO.EventEmitter
1512 * @param {Object} [config] Configuration options
1513 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1514 * appearance reflects this state.
1516 OO
.ui
.Widget
= function OoUiWidget( config
) {
1517 // Initialize config
1518 config
= $.extend( { disabled
: false }, config
);
1520 // Parent constructor
1521 OO
.ui
.Widget
.parent
.call( this, config
);
1523 // Mixin constructors
1524 OO
.EventEmitter
.call( this );
1527 this.disabled
= null;
1528 this.wasDisabled
= null;
1531 this.$element
.addClass( 'oo-ui-widget' );
1532 this.setDisabled( !!config
.disabled
);
1537 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1538 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1540 /* Static Properties */
1543 * Whether this widget will behave reasonably when wrapped in an HTML `<label>`. If this is true,
1544 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
1549 * @property {boolean}
1551 OO
.ui
.Widget
.static.supportsSimpleLabel
= false;
1558 * A 'disable' event is emitted when the disabled state of the widget changes
1559 * (i.e. on disable **and** enable).
1561 * @param {boolean} disabled Widget is disabled
1567 * A 'toggle' event is emitted when the visibility of the widget changes.
1569 * @param {boolean} visible Widget is visible
1575 * Check if the widget is disabled.
1577 * @return {boolean} Widget is disabled
1579 OO
.ui
.Widget
.prototype.isDisabled = function () {
1580 return this.disabled
;
1584 * Set the 'disabled' state of the widget.
1586 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1588 * @param {boolean} disabled Disable widget
1591 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
1594 this.disabled
= !!disabled
;
1595 isDisabled
= this.isDisabled();
1596 if ( isDisabled
!== this.wasDisabled
) {
1597 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
1598 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
1599 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
1600 this.emit( 'disable', isDisabled
);
1601 this.updateThemeClasses();
1603 this.wasDisabled
= isDisabled
;
1609 * Update the disabled state, in case of changes in parent widget.
1613 OO
.ui
.Widget
.prototype.updateDisabled = function () {
1614 this.setDisabled( this.disabled
);
1626 OO
.ui
.Theme
= function OoUiTheme() {
1627 this.elementClassesQueue
= [];
1628 this.debouncedUpdateQueuedElementClasses
= OO
.ui
.debounce( this.updateQueuedElementClasses
);
1633 OO
.initClass( OO
.ui
.Theme
);
1638 * Get a list of classes to be applied to a widget.
1640 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
1641 * otherwise state transitions will not work properly.
1643 * @param {OO.ui.Element} element Element for which to get classes
1644 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1646 OO
.ui
.Theme
.prototype.getElementClasses = function () {
1647 return { on
: [], off
: [] };
1651 * Update CSS classes provided by the theme.
1653 * For elements with theme logic hooks, this should be called any time there's a state change.
1655 * @param {OO.ui.Element} element Element for which to update classes
1657 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
1658 var $elements
= $( [] ),
1659 classes
= this.getElementClasses( element
);
1661 if ( element
.$icon
) {
1662 $elements
= $elements
.add( element
.$icon
);
1664 if ( element
.$indicator
) {
1665 $elements
= $elements
.add( element
.$indicator
);
1669 .removeClass( classes
.off
.join( ' ' ) )
1670 .addClass( classes
.on
.join( ' ' ) );
1676 OO
.ui
.Theme
.prototype.updateQueuedElementClasses = function () {
1678 for ( i
= 0; i
< this.elementClassesQueue
.length
; i
++ ) {
1679 this.updateElementClasses( this.elementClassesQueue
[ i
] );
1682 this.elementClassesQueue
= [];
1686 * Queue #updateElementClasses to be called for this element.
1688 * @localdoc QUnit tests override this method to directly call #queueUpdateElementClasses,
1689 * to make them synchronous.
1691 * @param {OO.ui.Element} element Element for which to update classes
1693 OO
.ui
.Theme
.prototype.queueUpdateElementClasses = function ( element
) {
1694 // Keep items in the queue unique. Use lastIndexOf to start checking from the end because that's
1695 // the most common case (this method is often called repeatedly for the same element).
1696 if ( this.elementClassesQueue
.lastIndexOf( element
) !== -1 ) {
1699 this.elementClassesQueue
.push( element
);
1700 this.debouncedUpdateQueuedElementClasses();
1704 * Get the transition duration in milliseconds for dialogs opening/closing
1706 * The dialog should be fully rendered this many milliseconds after the
1707 * ready process has executed.
1709 * @return {number} Transition duration in milliseconds
1711 OO
.ui
.Theme
.prototype.getDialogTransitionDuration = function () {
1716 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
1717 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
1718 * order in which users will navigate through the focusable elements via the "tab" key.
1721 * // TabIndexedElement is mixed into the ButtonWidget class
1722 * // to provide a tabIndex property.
1723 * var button1 = new OO.ui.ButtonWidget( {
1727 * var button2 = new OO.ui.ButtonWidget( {
1731 * var button3 = new OO.ui.ButtonWidget( {
1735 * var button4 = new OO.ui.ButtonWidget( {
1739 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
1745 * @param {Object} [config] Configuration options
1746 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
1747 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
1748 * functionality will be applied to it instead.
1749 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
1750 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
1751 * to remove the element from the tab-navigation flow.
1753 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
1754 // Configuration initialization
1755 config
= $.extend( { tabIndex
: 0 }, config
);
1758 this.$tabIndexed
= null;
1759 this.tabIndex
= null;
1762 this.connect( this, { disable
: 'onTabIndexedElementDisable' } );
1765 this.setTabIndex( config
.tabIndex
);
1766 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
1771 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
1776 * Set the element that should use the tabindex functionality.
1778 * This method is used to retarget a tabindex mixin so that its functionality applies
1779 * to the specified element. If an element is currently using the functionality, the mixin’s
1780 * effect on that element is removed before the new element is set up.
1782 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
1785 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
1786 var tabIndex
= this.tabIndex
;
1787 // Remove attributes from old $tabIndexed
1788 this.setTabIndex( null );
1789 // Force update of new $tabIndexed
1790 this.$tabIndexed
= $tabIndexed
;
1791 this.tabIndex
= tabIndex
;
1792 return this.updateTabIndex();
1796 * Set the value of the tabindex.
1798 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
1801 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
1802 tabIndex
= typeof tabIndex
=== 'number' ? tabIndex
: null;
1804 if ( this.tabIndex
!== tabIndex
) {
1805 this.tabIndex
= tabIndex
;
1806 this.updateTabIndex();
1813 * Update the `tabindex` attribute, in case of changes to tab index or
1819 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
1820 if ( this.$tabIndexed
) {
1821 if ( this.tabIndex
!== null ) {
1822 // Do not index over disabled elements
1823 this.$tabIndexed
.attr( {
1824 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
1825 // Support: ChromeVox and NVDA
1826 // These do not seem to inherit aria-disabled from parent elements
1827 'aria-disabled': this.isDisabled().toString()
1830 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
1837 * Handle disable events.
1840 * @param {boolean} disabled Element is disabled
1842 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
1843 this.updateTabIndex();
1847 * Get the value of the tabindex.
1849 * @return {number|null} Tabindex value
1851 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
1852 return this.tabIndex
;
1856 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
1857 * interface element that can be configured with access keys for accessibility.
1858 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
1860 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
1866 * @param {Object} [config] Configuration options
1867 * @cfg {jQuery} [$button] The button element created by the class.
1868 * If this configuration is omitted, the button element will use a generated `<a>`.
1869 * @cfg {boolean} [framed=true] Render the button with a frame
1871 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
1872 // Configuration initialization
1873 config
= config
|| {};
1876 this.$button
= null;
1878 this.active
= config
.active
!== undefined && config
.active
;
1879 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
1880 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
1881 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
1882 this.onKeyUpHandler
= this.onKeyUp
.bind( this );
1883 this.onClickHandler
= this.onClick
.bind( this );
1884 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
1887 this.$element
.addClass( 'oo-ui-buttonElement' );
1888 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
1889 this.setButtonElement( config
.$button
|| $( '<a>' ) );
1894 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
1896 /* Static Properties */
1899 * Cancel mouse down events.
1901 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
1902 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
1903 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
1908 * @property {boolean}
1910 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
1915 * A 'click' event is emitted when the button element is clicked.
1923 * Set the button element.
1925 * This method is used to retarget a button mixin so that its functionality applies to
1926 * the specified button element instead of the one created by the class. If a button element
1927 * is already set, the method will remove the mixin’s effect on that element.
1929 * @param {jQuery} $button Element to use as button
1931 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
1932 if ( this.$button
) {
1934 .removeClass( 'oo-ui-buttonElement-button' )
1935 .removeAttr( 'role accesskey' )
1937 mousedown
: this.onMouseDownHandler
,
1938 keydown
: this.onKeyDownHandler
,
1939 click
: this.onClickHandler
,
1940 keypress
: this.onKeyPressHandler
1944 this.$button
= $button
1945 .addClass( 'oo-ui-buttonElement-button' )
1947 mousedown
: this.onMouseDownHandler
,
1948 keydown
: this.onKeyDownHandler
,
1949 click
: this.onClickHandler
,
1950 keypress
: this.onKeyPressHandler
1953 // Add `role="button"` on `<a>` elements, where it's needed
1954 // `toUppercase()` is added for XHTML documents
1955 if ( this.$button
.prop( 'tagName' ).toUpperCase() === 'A' ) {
1956 this.$button
.attr( 'role', 'button' );
1961 * Handles mouse down events.
1964 * @param {jQuery.Event} e Mouse down event
1966 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
1967 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
1970 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
1971 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
1972 // reliably remove the pressed class
1973 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
1974 // Prevent change of focus unless specifically configured otherwise
1975 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
1981 * Handles mouse up events.
1984 * @param {MouseEvent} e Mouse up event
1986 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp = function ( e
) {
1987 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
1990 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
1991 // Stop listening for mouseup, since we only needed this once
1992 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
1996 * Handles mouse click events.
1999 * @param {jQuery.Event} e Mouse click event
2002 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
2003 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
2004 if ( this.emit( 'click' ) ) {
2011 * Handles key down events.
2014 * @param {jQuery.Event} e Key down event
2016 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
2017 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2020 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
2021 // Run the keyup handler no matter where the key is when the button is let go, so we can
2022 // reliably remove the pressed class
2023 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler
, true );
2027 * Handles key up events.
2030 * @param {KeyboardEvent} e Key up event
2032 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyUp = function ( e
) {
2033 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2036 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
2037 // Stop listening for keyup, since we only needed this once
2038 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler
, true );
2042 * Handles key press events.
2045 * @param {jQuery.Event} e Key press event
2048 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
2049 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
2050 if ( this.emit( 'click' ) ) {
2057 * Check if button has a frame.
2059 * @return {boolean} Button is framed
2061 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
2066 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
2068 * @param {boolean} [framed] Make button framed, omit to toggle
2071 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
2072 framed
= framed
=== undefined ? !this.framed
: !!framed
;
2073 if ( framed
!== this.framed
) {
2074 this.framed
= framed
;
2076 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
2077 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
2078 this.updateThemeClasses();
2085 * Set the button's active state.
2087 * The active state can be set on:
2089 * - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected
2090 * - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on
2091 * - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page
2094 * @param {boolean} value Make button active
2097 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
2098 this.active
= !!value
;
2099 this.$element
.toggleClass( 'oo-ui-buttonElement-active', this.active
);
2100 this.updateThemeClasses();
2105 * Check if the button is active
2108 * @return {boolean} The button is active
2110 OO
.ui
.mixin
.ButtonElement
.prototype.isActive = function () {
2115 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
2116 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
2117 * items from the group is done through the interface the class provides.
2118 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2120 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
2126 * @param {Object} [config] Configuration options
2127 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
2128 * is omitted, the group element will use a generated `<div>`.
2130 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
2131 // Configuration initialization
2132 config
= config
|| {};
2137 this.aggregateItemEvents
= {};
2140 this.setGroupElement( config
.$group
|| $( '<div>' ) );
2148 * A change event is emitted when the set of selected items changes.
2150 * @param {OO.ui.Element[]} items Items currently in the group
2156 * Set the group element.
2158 * If an element is already set, items will be moved to the new element.
2160 * @param {jQuery} $group Element to use as group
2162 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
2165 this.$group
= $group
;
2166 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2167 this.$group
.append( this.items
[ i
].$element
);
2172 * Check if a group contains no items.
2174 * @return {boolean} Group is empty
2176 OO
.ui
.mixin
.GroupElement
.prototype.isEmpty = function () {
2177 return !this.items
.length
;
2181 * Get all items in the group.
2183 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
2184 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
2187 * @return {OO.ui.Element[]} An array of items.
2189 OO
.ui
.mixin
.GroupElement
.prototype.getItems = function () {
2190 return this.items
.slice( 0 );
2194 * Get an item by its data.
2196 * Only the first item with matching data will be returned. To return all matching items,
2197 * use the #getItemsFromData method.
2199 * @param {Object} data Item data to search for
2200 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2202 OO
.ui
.mixin
.GroupElement
.prototype.getItemFromData = function ( data
) {
2204 hash
= OO
.getHash( data
);
2206 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2207 item
= this.items
[ i
];
2208 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2217 * Get items by their data.
2219 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
2221 * @param {Object} data Item data to search for
2222 * @return {OO.ui.Element[]} Items with equivalent data
2224 OO
.ui
.mixin
.GroupElement
.prototype.getItemsFromData = function ( data
) {
2226 hash
= OO
.getHash( data
),
2229 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2230 item
= this.items
[ i
];
2231 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2240 * Aggregate the events emitted by the group.
2242 * When events are aggregated, the group will listen to all contained items for the event,
2243 * and then emit the event under a new name. The new event will contain an additional leading
2244 * parameter containing the item that emitted the original event. Other arguments emitted from
2245 * the original event are passed through.
2247 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
2248 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
2249 * A `null` value will remove aggregated events.
2251 * @throws {Error} An error is thrown if aggregation already exists.
2253 OO
.ui
.mixin
.GroupElement
.prototype.aggregate = function ( events
) {
2254 var i
, len
, item
, add
, remove
, itemEvent
, groupEvent
;
2256 for ( itemEvent
in events
) {
2257 groupEvent
= events
[ itemEvent
];
2259 // Remove existing aggregated event
2260 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
2261 // Don't allow duplicate aggregations
2263 throw new Error( 'Duplicate item event aggregation for ' + itemEvent
);
2265 // Remove event aggregation from existing items
2266 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2267 item
= this.items
[ i
];
2268 if ( item
.connect
&& item
.disconnect
) {
2270 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
2271 item
.disconnect( this, remove
);
2274 // Prevent future items from aggregating event
2275 delete this.aggregateItemEvents
[ itemEvent
];
2278 // Add new aggregate event
2280 // Make future items aggregate event
2281 this.aggregateItemEvents
[ itemEvent
] = groupEvent
;
2282 // Add event aggregation to existing items
2283 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2284 item
= this.items
[ i
];
2285 if ( item
.connect
&& item
.disconnect
) {
2287 add
[ itemEvent
] = [ 'emit', groupEvent
, item
];
2288 item
.connect( this, add
);
2296 * Add items to the group.
2298 * Items will be added to the end of the group array unless the optional `index` parameter specifies
2299 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
2301 * @param {OO.ui.Element[]} items An array of items to add to the group
2302 * @param {number} [index] Index of the insertion point
2305 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
2306 var i
, len
, item
, itemEvent
, events
, currentIndex
,
2309 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
2312 // Check if item exists then remove it first, effectively "moving" it
2313 currentIndex
= this.items
.indexOf( item
);
2314 if ( currentIndex
>= 0 ) {
2315 this.removeItems( [ item
] );
2316 // Adjust index to compensate for removal
2317 if ( currentIndex
< index
) {
2322 if ( item
.connect
&& item
.disconnect
&& !$.isEmptyObject( this.aggregateItemEvents
) ) {
2324 for ( itemEvent
in this.aggregateItemEvents
) {
2325 events
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
2327 item
.connect( this, events
);
2329 item
.setElementGroup( this );
2330 itemElements
.push( item
.$element
.get( 0 ) );
2333 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
2334 this.$group
.append( itemElements
);
2335 this.items
.push
.apply( this.items
, items
);
2336 } else if ( index
=== 0 ) {
2337 this.$group
.prepend( itemElements
);
2338 this.items
.unshift
.apply( this.items
, items
);
2340 this.items
[ index
].$element
.before( itemElements
);
2341 this.items
.splice
.apply( this.items
, [ index
, 0 ].concat( items
) );
2344 this.emit( 'change', this.getItems() );
2349 * Remove the specified items from a group.
2351 * Removed items are detached (not removed) from the DOM so that they may be reused.
2352 * To remove all items from a group, you may wish to use the #clearItems method instead.
2354 * @param {OO.ui.Element[]} items An array of items to remove
2357 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
2358 var i
, len
, item
, index
, events
, itemEvent
;
2360 // Remove specific items
2361 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
2363 index
= this.items
.indexOf( item
);
2364 if ( index
!== -1 ) {
2365 if ( item
.connect
&& item
.disconnect
&& !$.isEmptyObject( this.aggregateItemEvents
) ) {
2367 for ( itemEvent
in this.aggregateItemEvents
) {
2368 events
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
2370 item
.disconnect( this, events
);
2372 item
.setElementGroup( null );
2373 this.items
.splice( index
, 1 );
2374 item
.$element
.detach();
2378 this.emit( 'change', this.getItems() );
2383 * Clear all items from the group.
2385 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2386 * To remove only a subset of items from a group, use the #removeItems method.
2390 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
2391 var i
, len
, item
, remove
, itemEvent
;
2394 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2395 item
= this.items
[ i
];
2397 item
.connect
&& item
.disconnect
&&
2398 !$.isEmptyObject( this.aggregateItemEvents
)
2401 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
2402 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
2404 item
.disconnect( this, remove
);
2406 item
.setElementGroup( null );
2407 item
.$element
.detach();
2410 this.emit( 'change', this.getItems() );
2416 * IconElement is often mixed into other classes to generate an icon.
2417 * Icons are graphics, about the size of normal text. They are used to aid the user
2418 * in locating a control or to convey information in a space-efficient way. See the
2419 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
2420 * included in the library.
2422 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2428 * @param {Object} [config] Configuration options
2429 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2430 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2431 * the icon element be set to an existing icon instead of the one generated by this class, set a
2432 * value using a jQuery selection. For example:
2434 * // Use a <div> tag instead of a <span>
2436 * // Use an existing icon element instead of the one generated by the class
2437 * $icon: this.$element
2438 * // Use an icon element from a child widget
2439 * $icon: this.childwidget.$element
2440 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
2441 * symbolic names. A map is used for i18n purposes and contains a `default` icon
2442 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
2443 * by the user's language.
2445 * Example of an i18n map:
2447 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2448 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
2449 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2450 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
2451 * text. The icon title is displayed when users move the mouse over the icon.
2453 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
2454 // Configuration initialization
2455 config
= config
|| {};
2460 this.iconTitle
= null;
2463 this.setIcon( config
.icon
|| this.constructor.static.icon
);
2464 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
2465 this.setIconElement( config
.$icon
|| $( '<span>' ) );
2470 OO
.initClass( OO
.ui
.mixin
.IconElement
);
2472 /* Static Properties */
2475 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
2476 * for i18n purposes and contains a `default` icon name and additional names keyed by
2477 * language code. The `default` name is used when no icon is keyed by the user's language.
2479 * Example of an i18n map:
2481 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2483 * Note: the static property will be overridden if the #icon configuration is used.
2487 * @property {Object|string}
2489 OO
.ui
.mixin
.IconElement
.static.icon
= null;
2492 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2493 * function that returns title text, or `null` for no title.
2495 * The static property will be overridden if the #iconTitle configuration is used.
2499 * @property {string|Function|null}
2501 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
2506 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2507 * applies to the specified icon element instead of the one created by the class. If an icon
2508 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2509 * and mixin methods will no longer affect the element.
2511 * @param {jQuery} $icon Element to use as icon
2513 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
2516 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
2517 .removeAttr( 'title' );
2521 .addClass( 'oo-ui-iconElement-icon' )
2522 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
2523 if ( this.iconTitle
!== null ) {
2524 this.$icon
.attr( 'title', this.iconTitle
);
2527 this.updateThemeClasses();
2531 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
2532 * The icon parameter can also be set to a map of icon names. See the #icon config setting
2535 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
2536 * by language code, or `null` to remove the icon.
2539 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
2540 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
2541 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
2543 if ( this.icon
!== icon
) {
2545 if ( this.icon
!== null ) {
2546 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
2548 if ( icon
!== null ) {
2549 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
2555 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
2556 this.updateThemeClasses();
2562 * Set the icon title. Use `null` to remove the title.
2564 * @param {string|Function|null} iconTitle A text string used as the icon title,
2565 * a function that returns title text, or `null` for no title.
2568 OO
.ui
.mixin
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
2569 iconTitle
= typeof iconTitle
=== 'function' ||
2570 ( typeof iconTitle
=== 'string' && iconTitle
.length
) ?
2571 OO
.ui
.resolveMsg( iconTitle
) : null;
2573 if ( this.iconTitle
!== iconTitle
) {
2574 this.iconTitle
= iconTitle
;
2576 if ( this.iconTitle
!== null ) {
2577 this.$icon
.attr( 'title', iconTitle
);
2579 this.$icon
.removeAttr( 'title' );
2588 * Get the symbolic name of the icon.
2590 * @return {string} Icon name
2592 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
2597 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
2599 * @return {string} Icon title text
2601 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
2602 return this.iconTitle
;
2606 * IndicatorElement is often mixed into other classes to generate an indicator.
2607 * Indicators are small graphics that are generally used in two ways:
2609 * - To draw attention to the status of an item. For example, an indicator might be
2610 * used to show that an item in a list has errors that need to be resolved.
2611 * - To clarify the function of a control that acts in an exceptional way (a button
2612 * that opens a menu instead of performing an action directly, for example).
2614 * For a list of indicators included in the library, please see the
2615 * [OOjs UI documentation on MediaWiki] [1].
2617 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2623 * @param {Object} [config] Configuration options
2624 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
2625 * configuration is omitted, the indicator element will use a generated `<span>`.
2626 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2627 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
2629 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2630 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
2631 * or a function that returns title text. The indicator title is displayed when users move
2632 * the mouse over the indicator.
2634 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
2635 // Configuration initialization
2636 config
= config
|| {};
2639 this.$indicator
= null;
2640 this.indicator
= null;
2641 this.indicatorTitle
= null;
2644 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
2645 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
2646 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
2651 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
2653 /* Static Properties */
2656 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2657 * The static property will be overridden if the #indicator configuration is used.
2661 * @property {string|null}
2663 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
2666 * A text string used as the indicator title, a function that returns title text, or `null`
2667 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
2671 * @property {string|Function|null}
2673 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
2678 * Set the indicator element.
2680 * If an element is already set, it will be cleaned up before setting up the new element.
2682 * @param {jQuery} $indicator Element to use as indicator
2684 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
2685 if ( this.$indicator
) {
2687 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
2688 .removeAttr( 'title' );
2691 this.$indicator
= $indicator
2692 .addClass( 'oo-ui-indicatorElement-indicator' )
2693 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
2694 if ( this.indicatorTitle
!== null ) {
2695 this.$indicator
.attr( 'title', this.indicatorTitle
);
2698 this.updateThemeClasses();
2702 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
2704 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
2707 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
2708 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
2710 if ( this.indicator
!== indicator
) {
2711 if ( this.$indicator
) {
2712 if ( this.indicator
!== null ) {
2713 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
2715 if ( indicator
!== null ) {
2716 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
2719 this.indicator
= indicator
;
2722 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
2723 this.updateThemeClasses();
2729 * Set the indicator title.
2731 * The title is displayed when a user moves the mouse over the indicator.
2733 * @param {string|Function|null} indicatorTitle Indicator title text, a function that returns text, or
2734 * `null` for no indicator title
2737 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
2738 indicatorTitle
= typeof indicatorTitle
=== 'function' ||
2739 ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ?
2740 OO
.ui
.resolveMsg( indicatorTitle
) : null;
2742 if ( this.indicatorTitle
!== indicatorTitle
) {
2743 this.indicatorTitle
= indicatorTitle
;
2744 if ( this.$indicator
) {
2745 if ( this.indicatorTitle
!== null ) {
2746 this.$indicator
.attr( 'title', indicatorTitle
);
2748 this.$indicator
.removeAttr( 'title' );
2757 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2759 * @return {string} Symbolic name of indicator
2761 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
2762 return this.indicator
;
2766 * Get the indicator title.
2768 * The title is displayed when a user moves the mouse over the indicator.
2770 * @return {string} Indicator title text
2772 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
2773 return this.indicatorTitle
;
2777 * LabelElement is often mixed into other classes to generate a label, which
2778 * helps identify the function of an interface element.
2779 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
2781 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2787 * @param {Object} [config] Configuration options
2788 * @cfg {jQuery} [$label] The label element created by the class. If this
2789 * configuration is omitted, the label element will use a generated `<span>`.
2790 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
2791 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
2792 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
2793 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2795 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
2796 // Configuration initialization
2797 config
= config
|| {};
2804 this.setLabel( config
.label
|| this.constructor.static.label
);
2805 this.setLabelElement( config
.$label
|| $( '<span>' ) );
2810 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
2815 * @event labelChange
2816 * @param {string} value
2819 /* Static Properties */
2822 * The label text. The label can be specified as a plaintext string, a function that will
2823 * produce a string in the future, or `null` for no label. The static value will
2824 * be overridden if a label is specified with the #label config option.
2828 * @property {string|Function|null}
2830 OO
.ui
.mixin
.LabelElement
.static.label
= null;
2832 /* Static methods */
2835 * Highlight the first occurrence of the query in the given text
2837 * @param {string} text Text
2838 * @param {string} query Query to find
2839 * @return {jQuery} Text with the first match of the query
2840 * sub-string wrapped in highlighted span
2842 OO
.ui
.mixin
.LabelElement
.static.highlightQuery = function ( text
, query
) {
2843 var $result
= $( '<span>' ),
2844 offset
= text
.toLowerCase().indexOf( query
.toLowerCase() );
2846 if ( !query
.length
|| offset
=== -1 ) {
2847 return $result
.text( text
);
2850 document
.createTextNode( text
.slice( 0, offset
) ),
2852 .addClass( 'oo-ui-labelElement-label-highlight' )
2853 .text( text
.slice( offset
, offset
+ query
.length
) ),
2854 document
.createTextNode( text
.slice( offset
+ query
.length
) )
2856 return $result
.contents();
2862 * Set the label element.
2864 * If an element is already set, it will be cleaned up before setting up the new element.
2866 * @param {jQuery} $label Element to use as label
2868 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
2869 if ( this.$label
) {
2870 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
2873 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
2874 this.setLabelContent( this.label
);
2880 * An empty string will result in the label being hidden. A string containing only whitespace will
2881 * be converted to a single ` `.
2883 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
2884 * text; or null for no label
2887 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
2888 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
2889 label
= ( ( typeof label
=== 'string' || label
instanceof jQuery
) && label
.length
) || ( label
instanceof OO
.ui
.HtmlSnippet
&& label
.toString().length
) ? label
: null;
2891 if ( this.label
!== label
) {
2892 if ( this.$label
) {
2893 this.setLabelContent( label
);
2896 this.emit( 'labelChange' );
2899 this.$element
.toggleClass( 'oo-ui-labelElement', !!this.label
);
2905 * Set the label as plain text with a highlighted query
2907 * @param {string} text Text label to set
2908 * @param {string} query Substring of text to highlight
2911 OO
.ui
.mixin
.LabelElement
.prototype.setHighlightedQuery = function ( text
, query
) {
2912 return this.setLabel( this.constructor.static.highlightQuery( text
, query
) );
2918 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
2919 * text; or null for no label
2921 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
2926 * Set the content of the label.
2928 * Do not call this method until after the label element has been set by #setLabelElement.
2931 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
2932 * text; or null for no label
2934 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
2935 if ( typeof label
=== 'string' ) {
2936 if ( label
.match( /^\s*$/ ) ) {
2937 // Convert whitespace only string to a single non-breaking space
2938 this.$label
.html( ' ' );
2940 this.$label
.text( label
);
2942 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
2943 this.$label
.html( label
.toString() );
2944 } else if ( label
instanceof jQuery
) {
2945 this.$label
.empty().append( label
);
2947 this.$label
.empty();
2952 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
2953 * additional functionality to an element created by another class. The class provides
2954 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
2955 * which are used to customize the look and feel of a widget to better describe its
2956 * importance and functionality.
2958 * The library currently contains the following styling flags for general use:
2960 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
2961 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
2962 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
2964 * The flags affect the appearance of the buttons:
2967 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
2968 * var button1 = new OO.ui.ButtonWidget( {
2969 * label: 'Constructive',
2970 * flags: 'constructive'
2972 * var button2 = new OO.ui.ButtonWidget( {
2973 * label: 'Destructive',
2974 * flags: 'destructive'
2976 * var button3 = new OO.ui.ButtonWidget( {
2977 * label: 'Progressive',
2978 * flags: 'progressive'
2980 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
2982 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
2983 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
2985 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
2991 * @param {Object} [config] Configuration options
2992 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
2993 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
2994 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
2995 * @cfg {jQuery} [$flagged] The flagged element. By default,
2996 * the flagged functionality is applied to the element created by the class ($element).
2997 * If a different element is specified, the flagged functionality will be applied to it instead.
2999 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
3000 // Configuration initialization
3001 config
= config
|| {};
3005 this.$flagged
= null;
3008 this.setFlags( config
.flags
);
3009 this.setFlaggedElement( config
.$flagged
|| this.$element
);
3016 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
3017 * parameter contains the name of each modified flag and indicates whether it was
3020 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
3021 * that the flag was added, `false` that the flag was removed.
3027 * Set the flagged element.
3029 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
3030 * If an element is already set, the method will remove the mixin’s effect on that element.
3032 * @param {jQuery} $flagged Element that should be flagged
3034 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
3035 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
3036 return 'oo-ui-flaggedElement-' + flag
;
3039 if ( this.$flagged
) {
3040 this.$flagged
.removeClass( classNames
);
3043 this.$flagged
= $flagged
.addClass( classNames
);
3047 * Check if the specified flag is set.
3049 * @param {string} flag Name of flag
3050 * @return {boolean} The flag is set
3052 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
3053 // This may be called before the constructor, thus before this.flags is set
3054 return this.flags
&& ( flag
in this.flags
);
3058 * Get the names of all flags set.
3060 * @return {string[]} Flag names
3062 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
3063 // This may be called before the constructor, thus before this.flags is set
3064 return Object
.keys( this.flags
|| {} );
3073 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
3074 var flag
, className
,
3077 classPrefix
= 'oo-ui-flaggedElement-';
3079 for ( flag
in this.flags
) {
3080 className
= classPrefix
+ flag
;
3081 changes
[ flag
] = false;
3082 delete this.flags
[ flag
];
3083 remove
.push( className
);
3086 if ( this.$flagged
) {
3087 this.$flagged
.removeClass( remove
.join( ' ' ) );
3090 this.updateThemeClasses();
3091 this.emit( 'flag', changes
);
3097 * Add one or more flags.
3099 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
3100 * or an object keyed by flag name with a boolean value that indicates whether the flag should
3101 * be added (`true`) or removed (`false`).
3105 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
3106 var i
, len
, flag
, className
,
3110 classPrefix
= 'oo-ui-flaggedElement-';
3112 if ( typeof flags
=== 'string' ) {
3113 className
= classPrefix
+ flags
;
3115 if ( !this.flags
[ flags
] ) {
3116 this.flags
[ flags
] = true;
3117 add
.push( className
);
3119 } else if ( Array
.isArray( flags
) ) {
3120 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
3122 className
= classPrefix
+ flag
;
3124 if ( !this.flags
[ flag
] ) {
3125 changes
[ flag
] = true;
3126 this.flags
[ flag
] = true;
3127 add
.push( className
);
3130 } else if ( OO
.isPlainObject( flags
) ) {
3131 for ( flag
in flags
) {
3132 className
= classPrefix
+ flag
;
3133 if ( flags
[ flag
] ) {
3135 if ( !this.flags
[ flag
] ) {
3136 changes
[ flag
] = true;
3137 this.flags
[ flag
] = true;
3138 add
.push( className
);
3142 if ( this.flags
[ flag
] ) {
3143 changes
[ flag
] = false;
3144 delete this.flags
[ flag
];
3145 remove
.push( className
);
3151 if ( this.$flagged
) {
3153 .addClass( add
.join( ' ' ) )
3154 .removeClass( remove
.join( ' ' ) );
3157 this.updateThemeClasses();
3158 this.emit( 'flag', changes
);
3164 * TitledElement is mixed into other classes to provide a `title` attribute.
3165 * Titles are rendered by the browser and are made visible when the user moves
3166 * the mouse over the element. Titles are not visible on touch devices.
3169 * // TitledElement provides a 'title' attribute to the
3170 * // ButtonWidget class
3171 * var button = new OO.ui.ButtonWidget( {
3172 * label: 'Button with Title',
3173 * title: 'I am a button'
3175 * $( 'body' ).append( button.$element );
3181 * @param {Object} [config] Configuration options
3182 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
3183 * If this config is omitted, the title functionality is applied to $element, the
3184 * element created by the class.
3185 * @cfg {string|Function} [title] The title text or a function that returns text. If
3186 * this config is omitted, the value of the {@link #static-title static title} property is used.
3188 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
3189 // Configuration initialization
3190 config
= config
|| {};
3193 this.$titled
= null;
3197 this.setTitle( config
.title
!== undefined ? config
.title
: this.constructor.static.title
);
3198 this.setTitledElement( config
.$titled
|| this.$element
);
3203 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
3205 /* Static Properties */
3208 * The title text, a function that returns text, or `null` for no title. The value of the static property
3209 * is overridden if the #title config option is used.
3213 * @property {string|Function|null}
3215 OO
.ui
.mixin
.TitledElement
.static.title
= null;
3220 * Set the titled element.
3222 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
3223 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
3225 * @param {jQuery} $titled Element that should use the 'titled' functionality
3227 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
3228 if ( this.$titled
) {
3229 this.$titled
.removeAttr( 'title' );
3232 this.$titled
= $titled
;
3234 this.$titled
.attr( 'title', this.title
);
3241 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
3244 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
3245 title
= typeof title
=== 'function' ? OO
.ui
.resolveMsg( title
) : title
;
3246 title
= ( typeof title
=== 'string' && title
.length
) ? title
: null;
3248 if ( this.title
!== title
) {
3249 if ( this.$titled
) {
3250 if ( title
!== null ) {
3251 this.$titled
.attr( 'title', title
);
3253 this.$titled
.removeAttr( 'title' );
3265 * @return {string} Title string
3267 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
3272 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
3273 * Accesskeys allow an user to go to a specific element by using
3274 * a shortcut combination of a browser specific keys + the key
3278 * // AccessKeyedElement provides an 'accesskey' attribute to the
3279 * // ButtonWidget class
3280 * var button = new OO.ui.ButtonWidget( {
3281 * label: 'Button with Accesskey',
3284 * $( 'body' ).append( button.$element );
3290 * @param {Object} [config] Configuration options
3291 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3292 * If this config is omitted, the accesskey functionality is applied to $element, the
3293 * element created by the class.
3294 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3295 * this config is omitted, no accesskey will be added.
3297 OO
.ui
.mixin
.AccessKeyedElement
= function OoUiMixinAccessKeyedElement( config
) {
3298 // Configuration initialization
3299 config
= config
|| {};
3302 this.$accessKeyed
= null;
3303 this.accessKey
= null;
3306 this.setAccessKey( config
.accessKey
|| null );
3307 this.setAccessKeyedElement( config
.$accessKeyed
|| this.$element
);
3312 OO
.initClass( OO
.ui
.mixin
.AccessKeyedElement
);
3314 /* Static Properties */
3317 * The access key, a function that returns a key, or `null` for no accesskey.
3321 * @property {string|Function|null}
3323 OO
.ui
.mixin
.AccessKeyedElement
.static.accessKey
= null;
3328 * Set the accesskeyed element.
3330 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
3331 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
3333 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
3335 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKeyedElement = function ( $accessKeyed
) {
3336 if ( this.$accessKeyed
) {
3337 this.$accessKeyed
.removeAttr( 'accesskey' );
3340 this.$accessKeyed
= $accessKeyed
;
3341 if ( this.accessKey
) {
3342 this.$accessKeyed
.attr( 'accesskey', this.accessKey
);
3349 * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no accesskey
3352 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKey = function ( accessKey
) {
3353 accessKey
= typeof accessKey
=== 'string' ? OO
.ui
.resolveMsg( accessKey
) : null;
3355 if ( this.accessKey
!== accessKey
) {
3356 if ( this.$accessKeyed
) {
3357 if ( accessKey
!== null ) {
3358 this.$accessKeyed
.attr( 'accesskey', accessKey
);
3360 this.$accessKeyed
.removeAttr( 'accesskey' );
3363 this.accessKey
= accessKey
;
3372 * @return {string} accessKey string
3374 OO
.ui
.mixin
.AccessKeyedElement
.prototype.getAccessKey = function () {
3375 return this.accessKey
;
3379 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3380 * feels, and functionality can be customized via the class’s configuration options
3381 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
3384 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
3387 * // A button widget
3388 * var button = new OO.ui.ButtonWidget( {
3389 * label: 'Button with Icon',
3391 * iconTitle: 'Remove'
3393 * $( 'body' ).append( button.$element );
3395 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3398 * @extends OO.ui.Widget
3399 * @mixins OO.ui.mixin.ButtonElement
3400 * @mixins OO.ui.mixin.IconElement
3401 * @mixins OO.ui.mixin.IndicatorElement
3402 * @mixins OO.ui.mixin.LabelElement
3403 * @mixins OO.ui.mixin.TitledElement
3404 * @mixins OO.ui.mixin.FlaggedElement
3405 * @mixins OO.ui.mixin.TabIndexedElement
3406 * @mixins OO.ui.mixin.AccessKeyedElement
3409 * @param {Object} [config] Configuration options
3410 * @cfg {boolean} [active=false] Whether button should be shown as active
3411 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3412 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3413 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3415 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
3416 // Configuration initialization
3417 config
= config
|| {};
3419 // Parent constructor
3420 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
3422 // Mixin constructors
3423 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
3424 OO
.ui
.mixin
.IconElement
.call( this, config
);
3425 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
3426 OO
.ui
.mixin
.LabelElement
.call( this, config
);
3427 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
3428 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
3429 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
3430 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$button
} ) );
3435 this.noFollow
= false;
3438 this.connect( this, { disable
: 'onDisable' } );
3441 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
3443 .addClass( 'oo-ui-buttonWidget' )
3444 .append( this.$button
);
3445 this.setActive( config
.active
);
3446 this.setHref( config
.href
);
3447 this.setTarget( config
.target
);
3448 this.setNoFollow( config
.noFollow
);
3453 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
3454 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
3455 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
3456 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
3457 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
3458 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
3459 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
3460 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
3461 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
3463 /* Static Properties */
3469 OO
.ui
.ButtonWidget
.static.cancelButtonMouseDownEvents
= false;
3474 * Get hyperlink location.
3476 * @return {string} Hyperlink location
3478 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
3483 * Get hyperlink target.
3485 * @return {string} Hyperlink target
3487 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
3492 * Get search engine traversal hint.
3494 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3496 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
3497 return this.noFollow
;
3501 * Set hyperlink location.
3503 * @param {string|null} href Hyperlink location, null to remove
3505 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
3506 href
= typeof href
=== 'string' ? href
: null;
3507 if ( href
!== null && !OO
.ui
.isSafeUrl( href
) ) {
3511 if ( href
!== this.href
) {
3520 * Update the `href` attribute, in case of changes to href or
3526 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
3527 if ( this.href
!== null && !this.isDisabled() ) {
3528 this.$button
.attr( 'href', this.href
);
3530 this.$button
.removeAttr( 'href' );
3537 * Handle disable events.
3540 * @param {boolean} disabled Element is disabled
3542 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
3547 * Set hyperlink target.
3549 * @param {string|null} target Hyperlink target, null to remove
3551 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
3552 target
= typeof target
=== 'string' ? target
: null;
3554 if ( target
!== this.target
) {
3555 this.target
= target
;
3556 if ( target
!== null ) {
3557 this.$button
.attr( 'target', target
);
3559 this.$button
.removeAttr( 'target' );
3567 * Set search engine traversal hint.
3569 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3571 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
3572 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
3574 if ( noFollow
!== this.noFollow
) {
3575 this.noFollow
= noFollow
;
3577 this.$button
.attr( 'rel', 'nofollow' );
3579 this.$button
.removeAttr( 'rel' );
3586 // Override method visibility hints from ButtonElement
3595 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3596 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3597 * removed, and cleared from the group.
3600 * // Example: A ButtonGroupWidget with two buttons
3601 * var button1 = new OO.ui.PopupButtonWidget( {
3602 * label: 'Select a category',
3605 * $content: $( '<p>List of categories...</p>' ),
3610 * var button2 = new OO.ui.ButtonWidget( {
3613 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
3614 * items: [button1, button2]
3616 * $( 'body' ).append( buttonGroup.$element );
3619 * @extends OO.ui.Widget
3620 * @mixins OO.ui.mixin.GroupElement
3623 * @param {Object} [config] Configuration options
3624 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
3626 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
3627 // Configuration initialization
3628 config
= config
|| {};
3630 // Parent constructor
3631 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
3633 // Mixin constructors
3634 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
3637 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
3638 if ( Array
.isArray( config
.items
) ) {
3639 this.addItems( config
.items
);
3645 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
3646 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
3649 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
3650 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
3651 * for a list of icons included in the library.
3654 * // An icon widget with a label
3655 * var myIcon = new OO.ui.IconWidget( {
3659 * // Create a label.
3660 * var iconLabel = new OO.ui.LabelWidget( {
3663 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
3665 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
3668 * @extends OO.ui.Widget
3669 * @mixins OO.ui.mixin.IconElement
3670 * @mixins OO.ui.mixin.TitledElement
3671 * @mixins OO.ui.mixin.FlaggedElement
3674 * @param {Object} [config] Configuration options
3676 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
3677 // Configuration initialization
3678 config
= config
|| {};
3680 // Parent constructor
3681 OO
.ui
.IconWidget
.parent
.call( this, config
);
3683 // Mixin constructors
3684 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
3685 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
3686 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
3689 this.$element
.addClass( 'oo-ui-iconWidget' );
3694 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
3695 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
3696 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
3697 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
3699 /* Static Properties */
3705 OO
.ui
.IconWidget
.static.tagName
= 'span';
3708 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
3709 * attention to the status of an item or to clarify the function of a control. For a list of
3710 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
3713 * // Example of an indicator widget
3714 * var indicator1 = new OO.ui.IndicatorWidget( {
3715 * indicator: 'alert'
3718 * // Create a fieldset layout to add a label
3719 * var fieldset = new OO.ui.FieldsetLayout();
3720 * fieldset.addItems( [
3721 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
3723 * $( 'body' ).append( fieldset.$element );
3725 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3728 * @extends OO.ui.Widget
3729 * @mixins OO.ui.mixin.IndicatorElement
3730 * @mixins OO.ui.mixin.TitledElement
3733 * @param {Object} [config] Configuration options
3735 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
3736 // Configuration initialization
3737 config
= config
|| {};
3739 // Parent constructor
3740 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
3742 // Mixin constructors
3743 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
3744 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
3747 this.$element
.addClass( 'oo-ui-indicatorWidget' );
3752 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
3753 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
3754 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
3756 /* Static Properties */
3762 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
3765 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
3766 * be configured with a `label` option that is set to a string, a label node, or a function:
3768 * - String: a plaintext string
3769 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
3770 * label that includes a link or special styling, such as a gray color or additional graphical elements.
3771 * - Function: a function that will produce a string in the future. Functions are used
3772 * in cases where the value of the label is not currently defined.
3774 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
3775 * will come into focus when the label is clicked.
3778 * // Examples of LabelWidgets
3779 * var label1 = new OO.ui.LabelWidget( {
3780 * label: 'plaintext label'
3782 * var label2 = new OO.ui.LabelWidget( {
3783 * label: $( '<a href="default.html">jQuery label</a>' )
3785 * // Create a fieldset layout with fields for each example
3786 * var fieldset = new OO.ui.FieldsetLayout();
3787 * fieldset.addItems( [
3788 * new OO.ui.FieldLayout( label1 ),
3789 * new OO.ui.FieldLayout( label2 )
3791 * $( 'body' ).append( fieldset.$element );
3794 * @extends OO.ui.Widget
3795 * @mixins OO.ui.mixin.LabelElement
3796 * @mixins OO.ui.mixin.TitledElement
3799 * @param {Object} [config] Configuration options
3800 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
3801 * Clicking the label will focus the specified input field.
3803 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
3804 // Configuration initialization
3805 config
= config
|| {};
3807 // Parent constructor
3808 OO
.ui
.LabelWidget
.parent
.call( this, config
);
3810 // Mixin constructors
3811 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
3812 OO
.ui
.mixin
.TitledElement
.call( this, config
);
3815 this.input
= config
.input
;
3818 if ( this.input
instanceof OO
.ui
.InputWidget
) {
3819 this.$element
.attr( 'for', this.input
.getInputId() );
3821 this.$element
.addClass( 'oo-ui-labelWidget' );
3826 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
3827 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
3828 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
3830 /* Static Properties */
3836 OO
.ui
.LabelWidget
.static.tagName
= 'label';
3839 * PendingElement is a mixin that is used to create elements that notify users that something is happening
3840 * and that they should wait before proceeding. The pending state is visually represented with a pending
3841 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
3842 * field of a {@link OO.ui.TextInputWidget text input widget}.
3844 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
3845 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
3846 * in process dialogs.
3849 * function MessageDialog( config ) {
3850 * MessageDialog.parent.call( this, config );
3852 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
3854 * MessageDialog.static.name = 'myMessageDialog';
3855 * MessageDialog.static.actions = [
3856 * { action: 'save', label: 'Done', flags: 'primary' },
3857 * { label: 'Cancel', flags: 'safe' }
3860 * MessageDialog.prototype.initialize = function () {
3861 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
3862 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
3863 * 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>' );
3864 * this.$body.append( this.content.$element );
3866 * MessageDialog.prototype.getBodyHeight = function () {
3869 * MessageDialog.prototype.getActionProcess = function ( action ) {
3870 * var dialog = this;
3871 * if ( action === 'save' ) {
3872 * dialog.getActions().get({actions: 'save'})[0].pushPending();
3873 * return new OO.ui.Process()
3875 * .next( function () {
3876 * dialog.getActions().get({actions: 'save'})[0].popPending();
3879 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
3882 * var windowManager = new OO.ui.WindowManager();
3883 * $( 'body' ).append( windowManager.$element );
3885 * var dialog = new MessageDialog();
3886 * windowManager.addWindows( [ dialog ] );
3887 * windowManager.openWindow( dialog );
3893 * @param {Object} [config] Configuration options
3894 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
3896 OO
.ui
.mixin
.PendingElement
= function OoUiMixinPendingElement( config
) {
3897 // Configuration initialization
3898 config
= config
|| {};
3902 this.$pending
= null;
3905 this.setPendingElement( config
.$pending
|| this.$element
);
3910 OO
.initClass( OO
.ui
.mixin
.PendingElement
);
3915 * Set the pending element (and clean up any existing one).
3917 * @param {jQuery} $pending The element to set to pending.
3919 OO
.ui
.mixin
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
3920 if ( this.$pending
) {
3921 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
3924 this.$pending
= $pending
;
3925 if ( this.pending
> 0 ) {
3926 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
3931 * Check if an element is pending.
3933 * @return {boolean} Element is pending
3935 OO
.ui
.mixin
.PendingElement
.prototype.isPending = function () {
3936 return !!this.pending
;
3940 * Increase the pending counter. The pending state will remain active until the counter is zero
3941 * (i.e., the number of calls to #pushPending and #popPending is the same).
3945 OO
.ui
.mixin
.PendingElement
.prototype.pushPending = function () {
3946 if ( this.pending
=== 0 ) {
3947 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
3948 this.updateThemeClasses();
3956 * Decrease the pending counter. The pending state will remain active until the counter is zero
3957 * (i.e., the number of calls to #pushPending and #popPending is the same).
3961 OO
.ui
.mixin
.PendingElement
.prototype.popPending = function () {
3962 if ( this.pending
=== 1 ) {
3963 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
3964 this.updateThemeClasses();
3966 this.pending
= Math
.max( 0, this.pending
- 1 );
3972 * Element that will stick under a specified container, even when it is inserted elsewhere in the
3973 * document (for example, in a OO.ui.Window's $overlay).
3975 * The elements's position is automatically calculated and maintained when window is resized or the
3976 * page is scrolled. If you reposition the container manually, you have to call #position to make
3977 * sure the element is still placed correctly.
3979 * As positioning is only possible when both the element and the container are attached to the DOM
3980 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
3981 * the #toggle method to display a floating popup, for example.
3987 * @param {Object} [config] Configuration options
3988 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
3989 * @cfg {jQuery} [$floatableContainer] Node to position below
3991 OO
.ui
.mixin
.FloatableElement
= function OoUiMixinFloatableElement( config
) {
3992 // Configuration initialization
3993 config
= config
|| {};
3996 this.$floatable
= null;
3997 this.$floatableContainer
= null;
3998 this.$floatableWindow
= null;
3999 this.$floatableClosestScrollable
= null;
4000 this.onFloatableScrollHandler
= this.position
.bind( this );
4001 this.onFloatableWindowResizeHandler
= this.position
.bind( this );
4004 this.setFloatableContainer( config
.$floatableContainer
);
4005 this.setFloatableElement( config
.$floatable
|| this.$element
);
4011 * Set floatable element.
4013 * If an element is already set, it will be cleaned up before setting up the new element.
4015 * @param {jQuery} $floatable Element to make floatable
4017 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableElement = function ( $floatable
) {
4018 if ( this.$floatable
) {
4019 this.$floatable
.removeClass( 'oo-ui-floatableElement-floatable' );
4020 this.$floatable
.css( { left
: '', top
: '' } );
4023 this.$floatable
= $floatable
.addClass( 'oo-ui-floatableElement-floatable' );
4028 * Set floatable container.
4030 * The element will be always positioned under the specified container.
4032 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
4034 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableContainer = function ( $floatableContainer
) {
4035 this.$floatableContainer
= $floatableContainer
;
4036 if ( this.$floatable
) {
4042 * Toggle positioning.
4044 * Do not turn positioning on until after the element is attached to the DOM and visible.
4046 * @param {boolean} [positioning] Enable positioning, omit to toggle
4049 OO
.ui
.mixin
.FloatableElement
.prototype.togglePositioning = function ( positioning
) {
4050 var closestScrollableOfContainer
;
4052 if ( !this.$floatable
|| !this.$floatableContainer
) {
4056 positioning
= positioning
=== undefined ? !this.positioning
: !!positioning
;
4058 if ( this.positioning
!== positioning
) {
4059 this.positioning
= positioning
;
4061 closestScrollableOfContainer
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatableContainer
[ 0 ] );
4062 this.needsCustomPosition
= !OO
.ui
.contains( this.$floatableContainer
[ 0 ], this.$floatable
[ 0 ] );
4063 // If the scrollable is the root, we have to listen to scroll events
4064 // on the window because of browser inconsistencies.
4065 if ( $( closestScrollableOfContainer
).is( 'html, body' ) ) {
4066 closestScrollableOfContainer
= OO
.ui
.Element
.static.getWindow( closestScrollableOfContainer
);
4069 if ( positioning
) {
4070 this.$floatableWindow
= $( this.getElementWindow() );
4071 this.$floatableWindow
.on( 'resize', this.onFloatableWindowResizeHandler
);
4073 this.$floatableClosestScrollable
= $( closestScrollableOfContainer
);
4074 this.$floatableClosestScrollable
.on( 'scroll', this.onFloatableScrollHandler
);
4076 // Initial position after visible
4079 if ( this.$floatableWindow
) {
4080 this.$floatableWindow
.off( 'resize', this.onFloatableWindowResizeHandler
);
4081 this.$floatableWindow
= null;
4084 if ( this.$floatableClosestScrollable
) {
4085 this.$floatableClosestScrollable
.off( 'scroll', this.onFloatableScrollHandler
);
4086 this.$floatableClosestScrollable
= null;
4089 this.$floatable
.css( { left
: '', top
: '' } );
4097 * Check whether the bottom edge of the given element is within the viewport of the given container.
4100 * @param {jQuery} $element
4101 * @param {jQuery} $container
4104 OO
.ui
.mixin
.FloatableElement
.prototype.isElementInViewport = function ( $element
, $container
) {
4105 var elemRect
, contRect
,
4106 leftEdgeInBounds
= false,
4107 bottomEdgeInBounds
= false,
4108 rightEdgeInBounds
= false;
4110 elemRect
= $element
[ 0 ].getBoundingClientRect();
4111 if ( $container
[ 0 ] === window
) {
4115 right
: document
.documentElement
.clientWidth
,
4116 bottom
: document
.documentElement
.clientHeight
4119 contRect
= $container
[ 0 ].getBoundingClientRect();
4122 // For completeness, if we still cared about topEdgeInBounds, that'd be:
4123 // elemRect.top >= contRect.top && elemRect.top <= contRect.bottom
4124 if ( elemRect
.left
>= contRect
.left
&& elemRect
.left
<= contRect
.right
) {
4125 leftEdgeInBounds
= true;
4127 if ( elemRect
.bottom
>= contRect
.top
&& elemRect
.bottom
<= contRect
.bottom
) {
4128 bottomEdgeInBounds
= true;
4130 if ( elemRect
.right
>= contRect
.left
&& elemRect
.right
<= contRect
.right
) {
4131 rightEdgeInBounds
= true;
4134 // We only care that any part of the bottom edge is visible
4135 return bottomEdgeInBounds
&& ( leftEdgeInBounds
|| rightEdgeInBounds
);
4139 * Position the floatable below its container.
4141 * This should only be done when both of them are attached to the DOM and visible.
4145 OO
.ui
.mixin
.FloatableElement
.prototype.position = function () {
4148 if ( !this.positioning
) {
4152 if ( !this.isElementInViewport( this.$floatableContainer
, this.$floatableClosestScrollable
) ) {
4153 this.$floatable
.addClass( 'oo-ui-element-hidden' );
4156 this.$floatable
.removeClass( 'oo-ui-element-hidden' );
4159 if ( !this.needsCustomPosition
) {
4163 pos
= OO
.ui
.Element
.static.getRelativePosition( this.$floatableContainer
, this.$floatable
.offsetParent() );
4165 // Position under container
4166 pos
.top
+= this.$floatableContainer
.height();
4167 this.$floatable
.css( pos
);
4169 // We updated the position, so re-evaluate the clipping state.
4170 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
4171 // will not notice the need to update itself.)
4172 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
4173 // it not listen to the right events in the right places?
4182 * Element that can be automatically clipped to visible boundaries.
4184 * Whenever the element's natural height changes, you have to call
4185 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
4186 * clipping correctly.
4188 * The dimensions of #$clippableContainer will be compared to the boundaries of the
4189 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
4190 * then #$clippable will be given a fixed reduced height and/or width and will be made
4191 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
4192 * but you can build a static footer by setting #$clippableContainer to an element that contains
4193 * #$clippable and the footer.
4199 * @param {Object} [config] Configuration options
4200 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
4201 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
4202 * omit to use #$clippable
4204 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
4205 // Configuration initialization
4206 config
= config
|| {};
4209 this.$clippable
= null;
4210 this.$clippableContainer
= null;
4211 this.clipping
= false;
4212 this.clippedHorizontally
= false;
4213 this.clippedVertically
= false;
4214 this.$clippableScrollableContainer
= null;
4215 this.$clippableScroller
= null;
4216 this.$clippableWindow
= null;
4217 this.idealWidth
= null;
4218 this.idealHeight
= null;
4219 this.onClippableScrollHandler
= this.clip
.bind( this );
4220 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
4223 if ( config
.$clippableContainer
) {
4224 this.setClippableContainer( config
.$clippableContainer
);
4226 this.setClippableElement( config
.$clippable
|| this.$element
);
4232 * Set clippable element.
4234 * If an element is already set, it will be cleaned up before setting up the new element.
4236 * @param {jQuery} $clippable Element to make clippable
4238 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
4239 if ( this.$clippable
) {
4240 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
4241 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
4242 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4245 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
4250 * Set clippable container.
4252 * This is the container that will be measured when deciding whether to clip. When clipping,
4253 * #$clippable will be resized in order to keep the clippable container fully visible.
4255 * If the clippable container is unset, #$clippable will be used.
4257 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
4259 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableContainer = function ( $clippableContainer
) {
4260 this.$clippableContainer
= $clippableContainer
;
4261 if ( this.$clippable
) {
4269 * Do not turn clipping on until after the element is attached to the DOM and visible.
4271 * @param {boolean} [clipping] Enable clipping, omit to toggle
4274 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
4275 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
4277 if ( this.clipping
!== clipping
) {
4278 this.clipping
= clipping
;
4280 this.$clippableScrollableContainer
= $( this.getClosestScrollableElementContainer() );
4281 // If the clippable container is the root, we have to listen to scroll events and check
4282 // jQuery.scrollTop on the window because of browser inconsistencies
4283 this.$clippableScroller
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
4284 $( OO
.ui
.Element
.static.getWindow( this.$clippableScrollableContainer
) ) :
4285 this.$clippableScrollableContainer
;
4286 this.$clippableScroller
.on( 'scroll', this.onClippableScrollHandler
);
4287 this.$clippableWindow
= $( this.getElementWindow() )
4288 .on( 'resize', this.onClippableWindowResizeHandler
);
4289 // Initial clip after visible
4292 this.$clippable
.css( {
4300 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4302 this.$clippableScrollableContainer
= null;
4303 this.$clippableScroller
.off( 'scroll', this.onClippableScrollHandler
);
4304 this.$clippableScroller
= null;
4305 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
4306 this.$clippableWindow
= null;
4314 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4316 * @return {boolean} Element will be clipped to the visible area
4318 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
4319 return this.clipping
;
4323 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
4325 * @return {boolean} Part of the element is being clipped
4327 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
4328 return this.clippedHorizontally
|| this.clippedVertically
;
4332 * Check if the right of the element is being clipped by the nearest scrollable container.
4334 * @return {boolean} Part of the element is being clipped
4336 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
4337 return this.clippedHorizontally
;
4341 * Check if the bottom of the element is being clipped by the nearest scrollable container.
4343 * @return {boolean} Part of the element is being clipped
4345 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
4346 return this.clippedVertically
;
4350 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
4352 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
4353 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
4355 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
4356 this.idealWidth
= width
;
4357 this.idealHeight
= height
;
4359 if ( !this.clipping
) {
4360 // Update dimensions
4361 this.$clippable
.css( { width
: width
, height
: height
} );
4363 // While clipping, idealWidth and idealHeight are not considered
4367 * Clip element to visible boundaries and allow scrolling when needed. You should call this method
4368 * when the element's natural height changes.
4370 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
4371 * overlapped by, the visible area of the nearest scrollable container.
4373 * Because calling clip() when the natural height changes isn't always possible, we also set
4374 * max-height when the element isn't being clipped. This means that if the element tries to grow
4375 * beyond the edge, something reasonable will happen before clip() is called.
4379 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
4380 var $container
, extraHeight
, extraWidth
, ccOffset
,
4381 $scrollableContainer
, scOffset
, scHeight
, scWidth
,
4382 ccWidth
, scrollerIsWindow
, scrollTop
, scrollLeft
,
4383 desiredWidth
, desiredHeight
, allotedWidth
, allotedHeight
,
4384 naturalWidth
, naturalHeight
, clipWidth
, clipHeight
,
4385 buffer
= 7; // Chosen by fair dice roll
4387 if ( !this.clipping
) {
4388 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
4392 $container
= this.$clippableContainer
|| this.$clippable
;
4393 extraHeight
= $container
.outerHeight() - this.$clippable
.outerHeight();
4394 extraWidth
= $container
.outerWidth() - this.$clippable
.outerWidth();
4395 ccOffset
= $container
.offset();
4396 if ( this.$clippableScrollableContainer
.is( 'html, body' ) ) {
4397 $scrollableContainer
= this.$clippableWindow
;
4398 scOffset
= { top
: 0, left
: 0 };
4400 $scrollableContainer
= this.$clippableScrollableContainer
;
4401 scOffset
= $scrollableContainer
.offset();
4403 scHeight
= $scrollableContainer
.innerHeight() - buffer
;
4404 scWidth
= $scrollableContainer
.innerWidth() - buffer
;
4405 ccWidth
= $container
.outerWidth() + buffer
;
4406 scrollerIsWindow
= this.$clippableScroller
[ 0 ] === this.$clippableWindow
[ 0 ];
4407 scrollTop
= scrollerIsWindow
? this.$clippableScroller
.scrollTop() : 0;
4408 scrollLeft
= scrollerIsWindow
? this.$clippableScroller
.scrollLeft() : 0;
4409 desiredWidth
= ccOffset
.left
< 0 ?
4410 ccWidth
+ ccOffset
.left
:
4411 ( scOffset
.left
+ scrollLeft
+ scWidth
) - ccOffset
.left
;
4412 desiredHeight
= ( scOffset
.top
+ scrollTop
+ scHeight
) - ccOffset
.top
;
4413 // It should never be desirable to exceed the dimensions of the browser viewport... right?
4414 desiredWidth
= Math
.min( desiredWidth
, document
.documentElement
.clientWidth
);
4415 desiredHeight
= Math
.min( desiredHeight
, document
.documentElement
.clientHeight
);
4416 allotedWidth
= Math
.ceil( desiredWidth
- extraWidth
);
4417 allotedHeight
= Math
.ceil( desiredHeight
- extraHeight
);
4418 naturalWidth
= this.$clippable
.prop( 'scrollWidth' );
4419 naturalHeight
= this.$clippable
.prop( 'scrollHeight' );
4420 clipWidth
= allotedWidth
< naturalWidth
;
4421 clipHeight
= allotedHeight
< naturalHeight
;
4424 this.$clippable
.css( {
4425 overflowX
: 'scroll',
4426 width
: Math
.max( 0, allotedWidth
),
4430 this.$clippable
.css( {
4432 width
: this.idealWidth
? this.idealWidth
- extraWidth
: '',
4433 maxWidth
: Math
.max( 0, allotedWidth
)
4437 this.$clippable
.css( {
4438 overflowY
: 'scroll',
4439 height
: Math
.max( 0, allotedHeight
),
4443 this.$clippable
.css( {
4445 height
: this.idealHeight
? this.idealHeight
- extraHeight
: '',
4446 maxHeight
: Math
.max( 0, allotedHeight
)
4450 // If we stopped clipping in at least one of the dimensions
4451 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
4452 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4455 this.clippedHorizontally
= clipWidth
;
4456 this.clippedVertically
= clipHeight
;
4462 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
4463 * By default, each popup has an anchor that points toward its origin.
4464 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
4467 * // A popup widget.
4468 * var popup = new OO.ui.PopupWidget( {
4469 * $content: $( '<p>Hi there!</p>' ),
4474 * $( 'body' ).append( popup.$element );
4475 * // To display the popup, toggle the visibility to 'true'.
4476 * popup.toggle( true );
4478 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
4481 * @extends OO.ui.Widget
4482 * @mixins OO.ui.mixin.LabelElement
4483 * @mixins OO.ui.mixin.ClippableElement
4484 * @mixins OO.ui.mixin.FloatableElement
4487 * @param {Object} [config] Configuration options
4488 * @cfg {number} [width=320] Width of popup in pixels
4489 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
4490 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
4491 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
4492 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
4493 * popup is leaning towards the right of the screen.
4494 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
4495 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
4496 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
4497 * sentence in the given language.
4498 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
4499 * See the [OOjs UI docs on MediaWiki][3] for an example.
4500 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
4501 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
4502 * @cfg {jQuery} [$content] Content to append to the popup's body
4503 * @cfg {jQuery} [$footer] Content to append to the popup's footer
4504 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
4505 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
4506 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
4508 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
4509 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
4511 * @cfg {boolean} [padded=false] Add padding to the popup's body
4513 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
4514 // Configuration initialization
4515 config
= config
|| {};
4517 // Parent constructor
4518 OO
.ui
.PopupWidget
.parent
.call( this, config
);
4520 // Properties (must be set before ClippableElement constructor call)
4521 this.$body
= $( '<div>' );
4522 this.$popup
= $( '<div>' );
4524 // Mixin constructors
4525 OO
.ui
.mixin
.LabelElement
.call( this, config
);
4526 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, {
4527 $clippable
: this.$body
,
4528 $clippableContainer
: this.$popup
4530 OO
.ui
.mixin
.FloatableElement
.call( this, config
);
4533 this.$anchor
= $( '<div>' );
4534 // If undefined, will be computed lazily in updateDimensions()
4535 this.$container
= config
.$container
;
4536 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
4537 this.autoClose
= !!config
.autoClose
;
4538 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
4539 this.transitionTimeout
= null;
4541 this.width
= config
.width
!== undefined ? config
.width
: 320;
4542 this.height
= config
.height
!== undefined ? config
.height
: null;
4543 this.setAlignment( config
.align
);
4544 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
4545 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
4548 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
4549 this.$body
.addClass( 'oo-ui-popupWidget-body' );
4550 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
4552 .addClass( 'oo-ui-popupWidget-popup' )
4553 .append( this.$body
);
4555 .addClass( 'oo-ui-popupWidget' )
4556 .append( this.$popup
, this.$anchor
);
4557 // Move content, which was added to #$element by OO.ui.Widget, to the body
4558 // FIXME This is gross, we should use '$body' or something for the config
4559 if ( config
.$content
instanceof jQuery
) {
4560 this.$body
.append( config
.$content
);
4563 if ( config
.padded
) {
4564 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
4567 if ( config
.head
) {
4568 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
4569 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
4570 this.$head
= $( '<div>' )
4571 .addClass( 'oo-ui-popupWidget-head' )
4572 .append( this.$label
, this.closeButton
.$element
);
4573 this.$popup
.prepend( this.$head
);
4576 if ( config
.$footer
) {
4577 this.$footer
= $( '<div>' )
4578 .addClass( 'oo-ui-popupWidget-footer' )
4579 .append( config
.$footer
);
4580 this.$popup
.append( this.$footer
);
4583 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
4584 // that reference properties not initialized at that time of parent class construction
4585 // TODO: Find a better way to handle post-constructor setup
4586 this.visible
= false;
4587 this.$element
.addClass( 'oo-ui-element-hidden' );
4592 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
4593 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
4594 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
4595 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.FloatableElement
);
4600 * Handles mouse down events.
4603 * @param {MouseEvent} e Mouse down event
4605 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
4608 !OO
.ui
.contains( this.$element
.add( this.$autoCloseIgnore
).get(), e
.target
, true )
4610 this.toggle( false );
4615 * Bind mouse down listener.
4619 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
4620 // Capture clicks outside popup
4621 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler
, true );
4625 * Handles close button click events.
4629 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
4630 if ( this.isVisible() ) {
4631 this.toggle( false );
4636 * Unbind mouse down listener.
4640 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
4641 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler
, true );
4645 * Handles key down events.
4648 * @param {KeyboardEvent} e Key down event
4650 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
4652 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
4655 this.toggle( false );
4657 e
.stopPropagation();
4662 * Bind key down listener.
4666 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
4667 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
4671 * Unbind key down listener.
4675 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
4676 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
4680 * Show, hide, or toggle the visibility of the anchor.
4682 * @param {boolean} [show] Show anchor, omit to toggle
4684 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
4685 show
= show
=== undefined ? !this.anchored
: !!show
;
4687 if ( this.anchored
!== show
) {
4689 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
4691 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
4693 this.anchored
= show
;
4698 * Check if the anchor is visible.
4700 * @return {boolean} Anchor is visible
4702 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
4709 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
4711 show
= show
=== undefined ? !this.isVisible() : !!show
;
4713 change
= show
!== this.isVisible();
4716 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
4719 this.togglePositioning( show
&& !!this.$floatableContainer
);
4722 if ( this.autoClose
) {
4723 this.bindMouseDownListener();
4724 this.bindKeyDownListener();
4726 this.updateDimensions();
4727 this.toggleClipping( true );
4729 this.toggleClipping( false );
4730 if ( this.autoClose
) {
4731 this.unbindMouseDownListener();
4732 this.unbindKeyDownListener();
4741 * Set the size of the popup.
4743 * Changing the size may also change the popup's position depending on the alignment.
4745 * @param {number} width Width in pixels
4746 * @param {number} height Height in pixels
4747 * @param {boolean} [transition=false] Use a smooth transition
4750 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
4752 this.height
= height
!== undefined ? height
: null;
4753 if ( this.isVisible() ) {
4754 this.updateDimensions( transition
);
4759 * Update the size and position.
4761 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
4762 * be called automatically.
4764 * @param {boolean} [transition=false] Use a smooth transition
4767 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
4768 var popupOffset
, originOffset
, containerLeft
, containerWidth
, containerRight
,
4769 popupLeft
, popupRight
, overlapLeft
, overlapRight
, anchorWidth
,
4773 if ( !this.$container
) {
4774 // Lazy-initialize $container if not specified in constructor
4775 this.$container
= $( this.getClosestScrollableElementContainer() );
4778 // Set height and width before measuring things, since it might cause our measurements
4779 // to change (e.g. due to scrollbars appearing or disappearing)
4782 height
: this.height
!== null ? this.height
: 'auto'
4785 // If we are in RTL, we need to flip the alignment, unless it is center
4786 if ( align
=== 'forwards' || align
=== 'backwards' ) {
4787 if ( this.$container
.css( 'direction' ) === 'rtl' ) {
4788 align
= ( { forwards
: 'force-left', backwards
: 'force-right' } )[ this.align
];
4790 align
= ( { forwards
: 'force-right', backwards
: 'force-left' } )[ this.align
];
4795 // Compute initial popupOffset based on alignment
4796 popupOffset
= this.width
* ( { 'force-left': -1, center
: -0.5, 'force-right': 0 } )[ align
];
4798 // Figure out if this will cause the popup to go beyond the edge of the container
4799 originOffset
= this.$element
.offset().left
;
4800 containerLeft
= this.$container
.offset().left
;
4801 containerWidth
= this.$container
.innerWidth();
4802 containerRight
= containerLeft
+ containerWidth
;
4803 popupLeft
= popupOffset
- this.containerPadding
;
4804 popupRight
= popupOffset
+ this.containerPadding
+ this.width
+ this.containerPadding
;
4805 overlapLeft
= ( originOffset
+ popupLeft
) - containerLeft
;
4806 overlapRight
= containerRight
- ( originOffset
+ popupRight
);
4808 // Adjust offset to make the popup not go beyond the edge, if needed
4809 if ( overlapRight
< 0 ) {
4810 popupOffset
+= overlapRight
;
4811 } else if ( overlapLeft
< 0 ) {
4812 popupOffset
-= overlapLeft
;
4815 // Adjust offset to avoid anchor being rendered too close to the edge
4816 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
4817 // TODO: Find a measurement that works for CSS anchors and image anchors
4818 anchorWidth
= this.$anchor
[ 0 ].scrollWidth
* 2;
4819 if ( popupOffset
+ this.width
< anchorWidth
) {
4820 popupOffset
= anchorWidth
- this.width
;
4821 } else if ( -popupOffset
< anchorWidth
) {
4822 popupOffset
= -anchorWidth
;
4825 // Prevent transition from being interrupted
4826 clearTimeout( this.transitionTimeout
);
4828 // Enable transition
4829 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
4832 // Position body relative to anchor
4833 this.$popup
.css( 'margin-left', popupOffset
);
4836 // Prevent transitioning after transition is complete
4837 this.transitionTimeout
= setTimeout( function () {
4838 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
4841 // Prevent transitioning immediately
4842 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
4845 // Reevaluate clipping state since we've relocated and resized the popup
4852 * Set popup alignment
4854 * @param {string} [align=center] Alignment of the popup, `center`, `force-left`, `force-right`,
4855 * `backwards` or `forwards`.
4857 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
4858 // Transform values deprecated since v0.11.0
4859 if ( align
=== 'left' || align
=== 'right' ) {
4860 OO
.ui
.warnDeprecation( 'PopupWidget#setAlignment parameter value `' + align
+ '` is deprecated. Use `force-right` or `force-left` instead.' );
4861 align
= { left
: 'force-right', right
: 'force-left' }[ align
];
4864 // Validate alignment
4865 if ( [ 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
4868 this.align
= 'center';
4873 * Get popup alignment
4875 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
4876 * `backwards` or `forwards`.
4878 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
4883 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
4884 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
4885 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
4886 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
4892 * @param {Object} [config] Configuration options
4893 * @cfg {Object} [popup] Configuration to pass to popup
4894 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
4896 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
4897 // Configuration initialization
4898 config
= config
|| {};
4901 this.popup
= new OO
.ui
.PopupWidget( $.extend(
4902 { autoClose
: true },
4904 { $autoCloseIgnore
: this.$element
.add( config
.popup
&& config
.popup
.$autoCloseIgnore
) }
4913 * @return {OO.ui.PopupWidget} Popup widget
4915 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
4920 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
4921 * which is used to display additional information or options.
4924 * // Example of a popup button.
4925 * var popupButton = new OO.ui.PopupButtonWidget( {
4926 * label: 'Popup button with options',
4929 * $content: $( '<p>Additional options here.</p>' ),
4931 * align: 'force-left'
4934 * // Append the button to the DOM.
4935 * $( 'body' ).append( popupButton.$element );
4938 * @extends OO.ui.ButtonWidget
4939 * @mixins OO.ui.mixin.PopupElement
4942 * @param {Object} [config] Configuration options
4943 * @cfg {jQuery} [$overlay] Render the popup into a separate layer. This configuration is useful in cases where
4944 * the expanded popup is larger than its containing `<div>`. The specified overlay layer is usually on top of the
4945 * containing `<div>` and has a larger area. By default, the popup uses relative positioning.
4947 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
4948 // Parent constructor
4949 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
4951 // Mixin constructors
4952 OO
.ui
.mixin
.PopupElement
.call( this, $.extend( true, {}, config
, {
4954 $floatableContainer
: this.$element
4959 this.$overlay
= config
.$overlay
|| this.$element
;
4962 this.connect( this, { click
: 'onAction' } );
4966 .addClass( 'oo-ui-popupButtonWidget' )
4967 .attr( 'aria-haspopup', 'true' );
4969 .addClass( 'oo-ui-popupButtonWidget-popup' )
4970 .toggleClass( 'oo-ui-popupButtonWidget-framed-popup', this.isFramed() )
4971 .toggleClass( 'oo-ui-popupButtonWidget-frameless-popup', !this.isFramed() );
4972 this.$overlay
.append( this.popup
.$element
);
4977 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
4978 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
4983 * Handle the button action being triggered.
4987 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
4988 this.popup
.toggle();
4992 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
4994 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
4999 * @mixins OO.ui.mixin.GroupElement
5002 * @param {Object} [config] Configuration options
5004 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
5005 // Mixin constructors
5006 OO
.ui
.mixin
.GroupElement
.call( this, config
);
5011 OO
.mixinClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
5016 * Set the disabled state of the widget.
5018 * This will also update the disabled state of child widgets.
5020 * @param {boolean} disabled Disable widget
5023 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
5027 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
5028 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
5030 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
5032 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5033 this.items
[ i
].updateDisabled();
5041 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
5043 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
5044 * allows bidirectional communication.
5046 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
5054 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
5061 * Check if widget is disabled.
5063 * Checks parent if present, making disabled state inheritable.
5065 * @return {boolean} Widget is disabled
5067 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
5068 return this.disabled
||
5069 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
5073 * Set group element is in.
5075 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
5078 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
5080 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
5081 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
5083 // Initialize item disabled states
5084 this.updateDisabled();
5090 * OptionWidgets are special elements that can be selected and configured with data. The
5091 * data is often unique for each option, but it does not have to be. OptionWidgets are used
5092 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
5093 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
5095 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5098 * @extends OO.ui.Widget
5099 * @mixins OO.ui.mixin.ItemWidget
5100 * @mixins OO.ui.mixin.LabelElement
5101 * @mixins OO.ui.mixin.FlaggedElement
5102 * @mixins OO.ui.mixin.AccessKeyedElement
5105 * @param {Object} [config] Configuration options
5107 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
5108 // Configuration initialization
5109 config
= config
|| {};
5111 // Parent constructor
5112 OO
.ui
.OptionWidget
.parent
.call( this, config
);
5114 // Mixin constructors
5115 OO
.ui
.mixin
.ItemWidget
.call( this );
5116 OO
.ui
.mixin
.LabelElement
.call( this, config
);
5117 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
5118 OO
.ui
.mixin
.AccessKeyedElement
.call( this, config
);
5121 this.selected
= false;
5122 this.highlighted
= false;
5123 this.pressed
= false;
5127 .data( 'oo-ui-optionWidget', this )
5128 // Allow programmatic focussing (and by accesskey), but not tabbing
5129 .attr( 'tabindex', '-1' )
5130 .attr( 'role', 'option' )
5131 .attr( 'aria-selected', 'false' )
5132 .addClass( 'oo-ui-optionWidget' )
5133 .append( this.$label
);
5138 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
5139 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
5140 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
5141 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
5142 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
5144 /* Static Properties */
5147 * Whether this option can be selected. See #setSelected.
5151 * @property {boolean}
5153 OO
.ui
.OptionWidget
.static.selectable
= true;
5156 * Whether this option can be highlighted. See #setHighlighted.
5160 * @property {boolean}
5162 OO
.ui
.OptionWidget
.static.highlightable
= true;
5165 * Whether this option can be pressed. See #setPressed.
5169 * @property {boolean}
5171 OO
.ui
.OptionWidget
.static.pressable
= true;
5174 * Whether this option will be scrolled into view when it is selected.
5178 * @property {boolean}
5180 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
5185 * Check if the option can be selected.
5187 * @return {boolean} Item is selectable
5189 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
5190 return this.constructor.static.selectable
&& !this.isDisabled() && this.isVisible();
5194 * Check if the option can be highlighted. A highlight indicates that the option
5195 * may be selected when a user presses enter or clicks. Disabled items cannot
5198 * @return {boolean} Item is highlightable
5200 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
5201 return this.constructor.static.highlightable
&& !this.isDisabled() && this.isVisible();
5205 * Check if the option can be pressed. The pressed state occurs when a user mouses
5206 * down on an item, but has not yet let go of the mouse.
5208 * @return {boolean} Item is pressable
5210 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
5211 return this.constructor.static.pressable
&& !this.isDisabled() && this.isVisible();
5215 * Check if the option is selected.
5217 * @return {boolean} Item is selected
5219 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
5220 return this.selected
;
5224 * Check if the option is highlighted. A highlight indicates that the
5225 * item may be selected when a user presses enter or clicks.
5227 * @return {boolean} Item is highlighted
5229 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
5230 return this.highlighted
;
5234 * Check if the option is pressed. The pressed state occurs when a user mouses
5235 * down on an item, but has not yet let go of the mouse. The item may appear
5236 * selected, but it will not be selected until the user releases the mouse.
5238 * @return {boolean} Item is pressed
5240 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
5241 return this.pressed
;
5245 * Set the option’s selected state. In general, all modifications to the selection
5246 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
5247 * method instead of this method.
5249 * @param {boolean} [state=false] Select option
5252 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
5253 if ( this.constructor.static.selectable
) {
5254 this.selected
= !!state
;
5256 .toggleClass( 'oo-ui-optionWidget-selected', state
)
5257 .attr( 'aria-selected', state
.toString() );
5258 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
5259 this.scrollElementIntoView();
5261 this.updateThemeClasses();
5267 * Set the option’s highlighted state. In general, all programmatic
5268 * modifications to the highlight should be handled by the
5269 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
5270 * method instead of this method.
5272 * @param {boolean} [state=false] Highlight option
5275 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
5276 if ( this.constructor.static.highlightable
) {
5277 this.highlighted
= !!state
;
5278 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
5279 this.updateThemeClasses();
5285 * Set the option’s pressed state. In general, all
5286 * programmatic modifications to the pressed state should be handled by the
5287 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
5288 * method instead of this method.
5290 * @param {boolean} [state=false] Press option
5293 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
5294 if ( this.constructor.static.pressable
) {
5295 this.pressed
= !!state
;
5296 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
5297 this.updateThemeClasses();
5303 * Get text to match search strings against.
5305 * The default implementation returns the label text, but subclasses
5306 * can override this to provide more complex behavior.
5308 * @return {string|boolean} String to match search string against
5310 OO
.ui
.OptionWidget
.prototype.getMatchText = function () {
5311 var label
= this.getLabel();
5312 return typeof label
=== 'string' ? label
: this.$label
.text();
5316 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
5317 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
5318 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
5321 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
5322 * information, please see the [OOjs UI documentation on MediaWiki][1].
5325 * // Example of a select widget with three options
5326 * var select = new OO.ui.SelectWidget( {
5328 * new OO.ui.OptionWidget( {
5330 * label: 'Option One',
5332 * new OO.ui.OptionWidget( {
5334 * label: 'Option Two',
5336 * new OO.ui.OptionWidget( {
5338 * label: 'Option Three',
5342 * $( 'body' ).append( select.$element );
5344 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5348 * @extends OO.ui.Widget
5349 * @mixins OO.ui.mixin.GroupWidget
5352 * @param {Object} [config] Configuration options
5353 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
5354 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
5355 * the [OOjs UI documentation on MediaWiki] [2] for examples.
5356 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5358 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
5359 // Configuration initialization
5360 config
= config
|| {};
5362 // Parent constructor
5363 OO
.ui
.SelectWidget
.parent
.call( this, config
);
5365 // Mixin constructors
5366 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
5369 this.pressed
= false;
5370 this.selecting
= null;
5371 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
5372 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
5373 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
5374 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
5375 this.keyPressBuffer
= '';
5376 this.keyPressBufferTimer
= null;
5377 this.blockMouseOverEvents
= 0;
5380 this.connect( this, {
5384 focusin
: this.onFocus
.bind( this ),
5385 mousedown
: this.onMouseDown
.bind( this ),
5386 mouseover
: this.onMouseOver
.bind( this ),
5387 mouseleave
: this.onMouseLeave
.bind( this )
5392 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
5393 .attr( 'role', 'listbox' );
5394 if ( Array
.isArray( config
.items
) ) {
5395 this.addItems( config
.items
);
5401 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
5402 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
5409 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
5411 * @param {OO.ui.OptionWidget|null} item Highlighted item
5417 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
5418 * pressed state of an option.
5420 * @param {OO.ui.OptionWidget|null} item Pressed item
5426 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
5428 * @param {OO.ui.OptionWidget|null} item Selected item
5433 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
5434 * @param {OO.ui.OptionWidget} item Chosen item
5440 * An `add` event is emitted when options are added to the select with the #addItems method.
5442 * @param {OO.ui.OptionWidget[]} items Added items
5443 * @param {number} index Index of insertion point
5449 * A `remove` event is emitted when options are removed from the select with the #clearItems
5450 * or #removeItems methods.
5452 * @param {OO.ui.OptionWidget[]} items Removed items
5458 * Handle focus events
5461 * @param {jQuery.Event} event
5463 OO
.ui
.SelectWidget
.prototype.onFocus = function ( event
) {
5465 if ( event
.target
=== this.$element
[ 0 ] ) {
5466 // This widget was focussed, e.g. by the user tabbing to it.
5467 // The styles for focus state depend on one of the items being selected.
5468 if ( !this.getSelectedItem() ) {
5469 item
= this.getFirstSelectableItem();
5472 // One of the options got focussed (and the event bubbled up here).
5473 // They can't be tabbed to, but they can be activated using accesskeys.
5474 item
= this.getTargetItem( event
);
5478 if ( item
.constructor.static.highlightable
) {
5479 this.highlightItem( item
);
5481 this.selectItem( item
);
5485 if ( event
.target
!== this.$element
[ 0 ] ) {
5486 this.$element
.focus();
5491 * Handle mouse down events.
5494 * @param {jQuery.Event} e Mouse down event
5496 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
5499 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
5500 this.togglePressed( true );
5501 item
= this.getTargetItem( e
);
5502 if ( item
&& item
.isSelectable() ) {
5503 this.pressItem( item
);
5504 this.selecting
= item
;
5505 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
5506 this.getElementDocument().addEventListener( 'mousemove', this.onMouseMoveHandler
, true );
5513 * Handle mouse up events.
5516 * @param {MouseEvent} e Mouse up event
5518 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
5521 this.togglePressed( false );
5522 if ( !this.selecting
) {
5523 item
= this.getTargetItem( e
);
5524 if ( item
&& item
.isSelectable() ) {
5525 this.selecting
= item
;
5528 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
&& this.selecting
) {
5529 this.pressItem( null );
5530 this.chooseItem( this.selecting
);
5531 this.selecting
= null;
5534 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
5535 this.getElementDocument().removeEventListener( 'mousemove', this.onMouseMoveHandler
, true );
5541 * Handle mouse move events.
5544 * @param {MouseEvent} e Mouse move event
5546 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
5549 if ( !this.isDisabled() && this.pressed
) {
5550 item
= this.getTargetItem( e
);
5551 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
5552 this.pressItem( item
);
5553 this.selecting
= item
;
5559 * Handle mouse over events.
5562 * @param {jQuery.Event} e Mouse over event
5564 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
5566 if ( this.blockMouseOverEvents
) {
5569 if ( !this.isDisabled() ) {
5570 item
= this.getTargetItem( e
);
5571 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
5577 * Handle mouse leave events.
5580 * @param {jQuery.Event} e Mouse over event
5582 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
5583 if ( !this.isDisabled() ) {
5584 this.highlightItem( null );
5590 * Handle key down events.
5593 * @param {KeyboardEvent} e Key down event
5595 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
5598 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
5600 if ( !this.isDisabled() && this.isVisible() ) {
5601 switch ( e
.keyCode
) {
5602 case OO
.ui
.Keys
.ENTER
:
5603 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
5604 // Was only highlighted, now let's select it. No-op if already selected.
5605 this.chooseItem( currentItem
);
5610 case OO
.ui
.Keys
.LEFT
:
5611 this.clearKeyPressBuffer();
5612 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
5615 case OO
.ui
.Keys
.DOWN
:
5616 case OO
.ui
.Keys
.RIGHT
:
5617 this.clearKeyPressBuffer();
5618 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
5621 case OO
.ui
.Keys
.ESCAPE
:
5622 case OO
.ui
.Keys
.TAB
:
5623 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
5624 currentItem
.setHighlighted( false );
5626 this.unbindKeyDownListener();
5627 this.unbindKeyPressListener();
5628 // Don't prevent tabbing away / defocusing
5634 if ( nextItem
.constructor.static.highlightable
) {
5635 this.highlightItem( nextItem
);
5637 this.chooseItem( nextItem
);
5639 this.scrollItemIntoView( nextItem
);
5644 e
.stopPropagation();
5650 * Bind key down listener.
5654 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
5655 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler
, true );
5659 * Unbind key down listener.
5663 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
5664 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler
, true );
5668 * Scroll item into view, preventing spurious mouse highlight actions from happening.
5670 * @param {OO.ui.OptionWidget} item Item to scroll into view
5672 OO
.ui
.SelectWidget
.prototype.scrollItemIntoView = function ( item
) {
5674 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling
5675 // and around 100-150 ms after it is finished.
5676 this.blockMouseOverEvents
++;
5677 item
.scrollElementIntoView().done( function () {
5678 setTimeout( function () {
5679 widget
.blockMouseOverEvents
--;
5685 * Clear the key-press buffer
5689 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
5690 if ( this.keyPressBufferTimer
) {
5691 clearTimeout( this.keyPressBufferTimer
);
5692 this.keyPressBufferTimer
= null;
5694 this.keyPressBuffer
= '';
5698 * Handle key press events.
5701 * @param {KeyboardEvent} e Key press event
5703 OO
.ui
.SelectWidget
.prototype.onKeyPress = function ( e
) {
5704 var c
, filter
, item
;
5706 if ( !e
.charCode
) {
5707 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
5708 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
5713 if ( String
.fromCodePoint
) {
5714 c
= String
.fromCodePoint( e
.charCode
);
5716 c
= String
.fromCharCode( e
.charCode
);
5719 if ( this.keyPressBufferTimer
) {
5720 clearTimeout( this.keyPressBufferTimer
);
5722 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
5724 item
= this.getHighlightedItem() || this.getSelectedItem();
5726 if ( this.keyPressBuffer
=== c
) {
5727 // Common (if weird) special case: typing "xxxx" will cycle through all
5728 // the items beginning with "x".
5730 item
= this.getRelativeSelectableItem( item
, 1 );
5733 this.keyPressBuffer
+= c
;
5736 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
5737 if ( !item
|| !filter( item
) ) {
5738 item
= this.getRelativeSelectableItem( item
, 1, filter
);
5741 if ( this.isVisible() && item
.constructor.static.highlightable
) {
5742 this.highlightItem( item
);
5744 this.chooseItem( item
);
5746 this.scrollItemIntoView( item
);
5750 e
.stopPropagation();
5754 * Get a matcher for the specific string
5757 * @param {string} s String to match against items
5758 * @param {boolean} [exact=false] Only accept exact matches
5759 * @return {Function} function ( OO.ui.OptionWidget ) => boolean
5761 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
, exact
) {
5764 if ( s
.normalize
) {
5767 s
= exact
? s
.trim() : s
.replace( /^\s+/, '' );
5768 re
= '^\\s*' + s
.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
5772 re
= new RegExp( re
, 'i' );
5773 return function ( item
) {
5774 var matchText
= item
.getMatchText();
5775 if ( matchText
.normalize
) {
5776 matchText
= matchText
.normalize();
5778 return re
.test( matchText
);
5783 * Bind key press listener.
5787 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
5788 this.getElementWindow().addEventListener( 'keypress', this.onKeyPressHandler
, true );
5792 * Unbind key down listener.
5794 * If you override this, be sure to call this.clearKeyPressBuffer() from your
5799 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
5800 this.getElementWindow().removeEventListener( 'keypress', this.onKeyPressHandler
, true );
5801 this.clearKeyPressBuffer();
5805 * Visibility change handler
5808 * @param {boolean} visible
5810 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
5812 this.clearKeyPressBuffer();
5817 * Get the closest item to a jQuery.Event.
5820 * @param {jQuery.Event} e
5821 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
5823 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
5824 return $( e
.target
).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
5828 * Get selected item.
5830 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
5832 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
5835 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5836 if ( this.items
[ i
].isSelected() ) {
5837 return this.items
[ i
];
5844 * Get highlighted item.
5846 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
5848 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
5851 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5852 if ( this.items
[ i
].isHighlighted() ) {
5853 return this.items
[ i
];
5860 * Toggle pressed state.
5862 * Press is a state that occurs when a user mouses down on an item, but
5863 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
5864 * until the user releases the mouse.
5866 * @param {boolean} pressed An option is being pressed
5868 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
5869 if ( pressed
=== undefined ) {
5870 pressed
= !this.pressed
;
5872 if ( pressed
!== this.pressed
) {
5874 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
5875 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
5876 this.pressed
= pressed
;
5881 * Highlight an option. If the `item` param is omitted, no options will be highlighted
5882 * and any existing highlight will be removed. The highlight is mutually exclusive.
5884 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
5888 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
5889 var i
, len
, highlighted
,
5892 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5893 highlighted
= this.items
[ i
] === item
;
5894 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
5895 this.items
[ i
].setHighlighted( highlighted
);
5900 this.emit( 'highlight', item
);
5907 * Fetch an item by its label.
5909 * @param {string} label Label of the item to select.
5910 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
5911 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
5913 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
5915 len
= this.items
.length
,
5916 filter
= this.getItemMatcher( label
, true );
5918 for ( i
= 0; i
< len
; i
++ ) {
5919 item
= this.items
[ i
];
5920 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
5927 filter
= this.getItemMatcher( label
, false );
5928 for ( i
= 0; i
< len
; i
++ ) {
5929 item
= this.items
[ i
];
5930 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
5946 * Programmatically select an option by its label. If the item does not exist,
5947 * all options will be deselected.
5949 * @param {string} [label] Label of the item to select.
5950 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
5954 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
5955 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
5956 if ( label
=== undefined || !itemFromLabel
) {
5957 return this.selectItem();
5959 return this.selectItem( itemFromLabel
);
5963 * Programmatically select an option by its data. If the `data` parameter is omitted,
5964 * or if the item does not exist, all options will be deselected.
5966 * @param {Object|string} [data] Value of the item to select, omit to deselect all
5970 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
5971 var itemFromData
= this.getItemFromData( data
);
5972 if ( data
=== undefined || !itemFromData
) {
5973 return this.selectItem();
5975 return this.selectItem( itemFromData
);
5979 * Programmatically select an option by its reference. If the `item` parameter is omitted,
5980 * all options will be deselected.
5982 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
5986 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
5987 var i
, len
, selected
,
5990 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5991 selected
= this.items
[ i
] === item
;
5992 if ( this.items
[ i
].isSelected() !== selected
) {
5993 this.items
[ i
].setSelected( selected
);
5998 this.emit( 'select', item
);
6007 * Press is a state that occurs when a user mouses down on an item, but has not
6008 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
6009 * releases the mouse.
6011 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
6015 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
6016 var i
, len
, pressed
,
6019 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6020 pressed
= this.items
[ i
] === item
;
6021 if ( this.items
[ i
].isPressed() !== pressed
) {
6022 this.items
[ i
].setPressed( pressed
);
6027 this.emit( 'press', item
);
6036 * Note that ‘choose’ should never be modified programmatically. A user can choose
6037 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
6038 * use the #selectItem method.
6040 * This method is identical to #selectItem, but may vary in subclasses that take additional action
6041 * when users choose an item with the keyboard or mouse.
6043 * @param {OO.ui.OptionWidget} item Item to choose
6047 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
6049 this.selectItem( item
);
6050 this.emit( 'choose', item
);
6057 * Get an option by its position relative to the specified item (or to the start of the option array,
6058 * if item is `null`). The direction in which to search through the option array is specified with a
6059 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
6060 * `null` if there are no options in the array.
6062 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
6063 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
6064 * @param {Function} [filter] Only consider items for which this function returns
6065 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
6066 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
6068 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
, filter
) {
6069 var currentIndex
, nextIndex
, i
,
6070 increase
= direction
> 0 ? 1 : -1,
6071 len
= this.items
.length
;
6073 if ( item
instanceof OO
.ui
.OptionWidget
) {
6074 currentIndex
= this.items
.indexOf( item
);
6075 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
6077 // If no item is selected and moving forward, start at the beginning.
6078 // If moving backward, start at the end.
6079 nextIndex
= direction
> 0 ? 0 : len
- 1;
6082 for ( i
= 0; i
< len
; i
++ ) {
6083 item
= this.items
[ nextIndex
];
6085 item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() &&
6086 ( !filter
|| filter( item
) )
6090 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
6096 * Get the next selectable item or `null` if there are no selectable items.
6097 * Disabled options and menu-section markers and breaks are not selectable.
6099 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
6101 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
6102 return this.getRelativeSelectableItem( null, 1 );
6106 * Add an array of options to the select. Optionally, an index number can be used to
6107 * specify an insertion point.
6109 * @param {OO.ui.OptionWidget[]} items Items to add
6110 * @param {number} [index] Index to insert items after
6114 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
6116 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
6118 // Always provide an index, even if it was omitted
6119 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
6125 * Remove the specified array of options from the select. Options will be detached
6126 * from the DOM, not removed, so they can be reused later. To remove all options from
6127 * the select, you may wish to use the #clearItems method instead.
6129 * @param {OO.ui.OptionWidget[]} items Items to remove
6133 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
6136 // Deselect items being removed
6137 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
6139 if ( item
.isSelected() ) {
6140 this.selectItem( null );
6145 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
6147 this.emit( 'remove', items
);
6153 * Clear all options from the select. Options will be detached from the DOM, not removed,
6154 * so that they can be reused later. To remove a subset of options from the select, use
6155 * the #removeItems method.
6160 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
6161 var items
= this.items
.slice();
6164 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
6167 this.selectItem( null );
6169 this.emit( 'remove', items
);
6175 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
6176 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
6177 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
6178 * options. For more information about options and selects, please see the
6179 * [OOjs UI documentation on MediaWiki][1].
6182 * // Decorated options in a select widget
6183 * var select = new OO.ui.SelectWidget( {
6185 * new OO.ui.DecoratedOptionWidget( {
6187 * label: 'Option with icon',
6190 * new OO.ui.DecoratedOptionWidget( {
6192 * label: 'Option with indicator',
6197 * $( 'body' ).append( select.$element );
6199 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6202 * @extends OO.ui.OptionWidget
6203 * @mixins OO.ui.mixin.IconElement
6204 * @mixins OO.ui.mixin.IndicatorElement
6207 * @param {Object} [config] Configuration options
6209 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
6210 // Parent constructor
6211 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
6213 // Mixin constructors
6214 OO
.ui
.mixin
.IconElement
.call( this, config
);
6215 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
6219 .addClass( 'oo-ui-decoratedOptionWidget' )
6220 .prepend( this.$icon
)
6221 .append( this.$indicator
);
6226 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
6227 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
6228 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
6231 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
6232 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
6233 * the [OOjs UI documentation on MediaWiki] [1] for more information.
6235 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
6238 * @extends OO.ui.DecoratedOptionWidget
6241 * @param {Object} [config] Configuration options
6243 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
6244 // Configuration initialization
6245 config
= $.extend( { icon
: 'check' }, config
);
6247 // Parent constructor
6248 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
6252 .attr( 'role', 'menuitem' )
6253 .addClass( 'oo-ui-menuOptionWidget' );
6258 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
6260 /* Static Properties */
6266 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
6269 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
6270 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
6273 * var myDropdown = new OO.ui.DropdownWidget( {
6276 * new OO.ui.MenuSectionOptionWidget( {
6279 * new OO.ui.MenuOptionWidget( {
6281 * label: 'Welsh Corgi'
6283 * new OO.ui.MenuOptionWidget( {
6285 * label: 'Standard Poodle'
6287 * new OO.ui.MenuSectionOptionWidget( {
6290 * new OO.ui.MenuOptionWidget( {
6297 * $( 'body' ).append( myDropdown.$element );
6300 * @extends OO.ui.DecoratedOptionWidget
6303 * @param {Object} [config] Configuration options
6305 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
6306 // Parent constructor
6307 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
6310 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' );
6315 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
6317 /* Static Properties */
6323 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
6329 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
6332 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
6333 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
6334 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
6335 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
6336 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
6337 * and customized to be opened, closed, and displayed as needed.
6339 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
6340 * mouse outside the menu.
6342 * Menus also have support for keyboard interaction:
6344 * - Enter/Return key: choose and select a menu option
6345 * - Up-arrow key: highlight the previous menu option
6346 * - Down-arrow key: highlight the next menu option
6347 * - Esc key: hide the menu
6349 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
6350 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6353 * @extends OO.ui.SelectWidget
6354 * @mixins OO.ui.mixin.ClippableElement
6357 * @param {Object} [config] Configuration options
6358 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
6359 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
6360 * and {@link OO.ui.mixin.LookupElement LookupElement}
6361 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
6362 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiselectWidget CapsuleMultiselectWidget}
6363 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
6364 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
6365 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
6366 * that button, unless the button (or its parent widget) is passed in here.
6367 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
6368 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
6370 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
6371 // Configuration initialization
6372 config
= config
|| {};
6374 // Parent constructor
6375 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
6377 // Mixin constructors
6378 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
6381 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
6382 this.filterFromInput
= !!config
.filterFromInput
;
6383 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
6384 this.$widget
= config
.widget
? config
.widget
.$element
: null;
6385 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
6386 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
6390 .addClass( 'oo-ui-menuSelectWidget' )
6391 .attr( 'role', 'menu' );
6393 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
6394 // that reference properties not initialized at that time of parent class construction
6395 // TODO: Find a better way to handle post-constructor setup
6396 this.visible
= false;
6397 this.$element
.addClass( 'oo-ui-element-hidden' );
6402 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
6403 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
6408 * Handles document mouse down events.
6411 * @param {MouseEvent} e Mouse down event
6413 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
6415 !OO
.ui
.contains( this.$element
[ 0 ], e
.target
, true ) &&
6416 ( !this.$widget
|| !OO
.ui
.contains( this.$widget
[ 0 ], e
.target
, true ) )
6418 this.toggle( false );
6425 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
6426 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
6428 if ( !this.isDisabled() && this.isVisible() ) {
6429 switch ( e
.keyCode
) {
6430 case OO
.ui
.Keys
.LEFT
:
6431 case OO
.ui
.Keys
.RIGHT
:
6432 // Do nothing if a text field is associated, arrow keys will be handled natively
6433 if ( !this.$input
) {
6434 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
6437 case OO
.ui
.Keys
.ESCAPE
:
6438 case OO
.ui
.Keys
.TAB
:
6439 if ( currentItem
) {
6440 currentItem
.setHighlighted( false );
6442 this.toggle( false );
6443 // Don't prevent tabbing away, prevent defocusing
6444 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
6446 e
.stopPropagation();
6450 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
6457 * Update menu item visibility after input changes.
6461 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
6462 var i
, item
, visible
,
6464 len
= this.items
.length
,
6465 showAll
= !this.isVisible(),
6466 filter
= showAll
? null : this.getItemMatcher( this.$input
.val() );
6468 for ( i
= 0; i
< len
; i
++ ) {
6469 item
= this.items
[ i
];
6470 if ( item
instanceof OO
.ui
.OptionWidget
) {
6471 visible
= showAll
|| filter( item
);
6472 anyVisible
= anyVisible
|| visible
;
6473 item
.toggle( visible
);
6477 this.$element
.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible
);
6479 // Reevaluate clipping
6486 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
6487 if ( this.$input
) {
6488 this.$input
.on( 'keydown', this.onKeyDownHandler
);
6490 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyDownListener
.call( this );
6497 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
6498 if ( this.$input
) {
6499 this.$input
.off( 'keydown', this.onKeyDownHandler
);
6501 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyDownListener
.call( this );
6508 OO
.ui
.MenuSelectWidget
.prototype.bindKeyPressListener = function () {
6509 if ( this.$input
) {
6510 if ( this.filterFromInput
) {
6511 this.$input
.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
6514 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyPressListener
.call( this );
6521 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyPressListener = function () {
6522 if ( this.$input
) {
6523 if ( this.filterFromInput
) {
6524 this.$input
.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
6525 this.updateItemVisibility();
6528 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyPressListener
.call( this );
6535 * When a user chooses an item, the menu is closed.
6537 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
6538 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
6540 * @param {OO.ui.OptionWidget} item Item to choose
6543 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
6544 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
6545 this.toggle( false );
6552 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
6554 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
6556 // Reevaluate clipping
6565 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
6567 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
6569 // Reevaluate clipping
6578 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
6580 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
6582 // Reevaluate clipping
6591 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
6594 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
6595 change
= visible
!== this.isVisible();
6598 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
6602 this.bindKeyDownListener();
6603 this.bindKeyPressListener();
6605 this.toggleClipping( true );
6607 if ( this.getSelectedItem() ) {
6608 this.getSelectedItem().scrollElementIntoView( { duration
: 0 } );
6612 if ( this.autoHide
) {
6613 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
6616 this.unbindKeyDownListener();
6617 this.unbindKeyPressListener();
6618 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
6619 this.toggleClipping( false );
6627 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
6628 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
6629 * users can interact with it.
6631 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
6632 * OO.ui.DropdownInputWidget instead.
6635 * // Example: A DropdownWidget with a menu that contains three options
6636 * var dropDown = new OO.ui.DropdownWidget( {
6637 * label: 'Dropdown menu: Select a menu option',
6640 * new OO.ui.MenuOptionWidget( {
6644 * new OO.ui.MenuOptionWidget( {
6648 * new OO.ui.MenuOptionWidget( {
6656 * $( 'body' ).append( dropDown.$element );
6658 * dropDown.getMenu().selectItemByData( 'b' );
6660 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
6662 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
6664 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
6667 * @extends OO.ui.Widget
6668 * @mixins OO.ui.mixin.IconElement
6669 * @mixins OO.ui.mixin.IndicatorElement
6670 * @mixins OO.ui.mixin.LabelElement
6671 * @mixins OO.ui.mixin.TitledElement
6672 * @mixins OO.ui.mixin.TabIndexedElement
6675 * @param {Object} [config] Configuration options
6676 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
6677 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
6678 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
6679 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
6681 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
6682 // Configuration initialization
6683 config
= $.extend( { indicator
: 'down' }, config
);
6685 // Parent constructor
6686 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
6688 // Properties (must be set before TabIndexedElement constructor call)
6689 this.$handle
= this.$( '<span>' );
6690 this.$overlay
= config
.$overlay
|| this.$element
;
6692 // Mixin constructors
6693 OO
.ui
.mixin
.IconElement
.call( this, config
);
6694 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
6695 OO
.ui
.mixin
.LabelElement
.call( this, config
);
6696 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
6697 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
6700 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend( {
6702 $container
: this.$element
6707 click
: this.onClick
.bind( this ),
6708 keydown
: this.onKeyDown
.bind( this ),
6709 // Hack? Handle type-to-search when menu is not expanded and not handling its own events
6710 keypress
: this.menu
.onKeyPressHandler
,
6711 blur
: this.menu
.clearKeyPressBuffer
.bind( this.menu
)
6713 this.menu
.connect( this, {
6714 select
: 'onMenuSelect',
6715 toggle
: 'onMenuToggle'
6720 .addClass( 'oo-ui-dropdownWidget-handle' )
6721 .append( this.$icon
, this.$label
, this.$indicator
);
6723 .addClass( 'oo-ui-dropdownWidget' )
6724 .append( this.$handle
);
6725 this.$overlay
.append( this.menu
.$element
);
6730 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
6731 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
6732 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
6733 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
6734 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
6735 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
6742 * @return {OO.ui.MenuSelectWidget} Menu of widget
6744 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
6749 * Handles menu select events.
6752 * @param {OO.ui.MenuOptionWidget} item Selected menu item
6754 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
6758 this.setLabel( null );
6762 selectedLabel
= item
.getLabel();
6764 // If the label is a DOM element, clone it, because setLabel will append() it
6765 if ( selectedLabel
instanceof jQuery
) {
6766 selectedLabel
= selectedLabel
.clone();
6769 this.setLabel( selectedLabel
);
6773 * Handle menu toggle events.
6776 * @param {boolean} isVisible Menu toggle event
6778 OO
.ui
.DropdownWidget
.prototype.onMenuToggle = function ( isVisible
) {
6779 this.$element
.toggleClass( 'oo-ui-dropdownWidget-open', isVisible
);
6783 * Handle mouse click events.
6786 * @param {jQuery.Event} e Mouse click event
6788 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
6789 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
6796 * Handle key down events.
6799 * @param {jQuery.Event} e Key down event
6801 OO
.ui
.DropdownWidget
.prototype.onKeyDown = function ( e
) {
6803 !this.isDisabled() &&
6805 e
.which
=== OO
.ui
.Keys
.ENTER
||
6807 !this.menu
.isVisible() &&
6809 e
.which
=== OO
.ui
.Keys
.SPACE
||
6810 e
.which
=== OO
.ui
.Keys
.UP
||
6811 e
.which
=== OO
.ui
.Keys
.DOWN
6822 * RadioOptionWidget is an option widget that looks like a radio button.
6823 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
6824 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6826 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
6829 * @extends OO.ui.OptionWidget
6832 * @param {Object} [config] Configuration options
6834 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
6835 // Configuration initialization
6836 config
= config
|| {};
6838 // Properties (must be done before parent constructor which calls #setDisabled)
6839 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
6841 // Parent constructor
6842 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
6845 // Remove implicit role, we're handling it ourselves
6846 this.radio
.$input
.attr( 'role', 'presentation' );
6848 .addClass( 'oo-ui-radioOptionWidget' )
6849 .attr( 'role', 'radio' )
6850 .attr( 'aria-checked', 'false' )
6851 .removeAttr( 'aria-selected' )
6852 .prepend( this.radio
.$element
);
6857 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
6859 /* Static Properties */
6865 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
6871 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
6877 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
6883 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
6890 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
6891 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
6893 this.radio
.setSelected( state
);
6895 .attr( 'aria-checked', state
.toString() )
6896 .removeAttr( 'aria-selected' );
6904 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
6905 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
6907 this.radio
.setDisabled( this.isDisabled() );
6913 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
6914 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
6915 * an interface for adding, removing and selecting options.
6916 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
6918 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
6919 * OO.ui.RadioSelectInputWidget instead.
6922 * // A RadioSelectWidget with RadioOptions.
6923 * var option1 = new OO.ui.RadioOptionWidget( {
6925 * label: 'Selected radio option'
6928 * var option2 = new OO.ui.RadioOptionWidget( {
6930 * label: 'Unselected radio option'
6933 * var radioSelect=new OO.ui.RadioSelectWidget( {
6934 * items: [ option1, option2 ]
6937 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
6938 * radioSelect.selectItem( option1 );
6940 * $( 'body' ).append( radioSelect.$element );
6942 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6946 * @extends OO.ui.SelectWidget
6947 * @mixins OO.ui.mixin.TabIndexedElement
6950 * @param {Object} [config] Configuration options
6952 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
6953 // Parent constructor
6954 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
6956 // Mixin constructors
6957 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
6961 focus
: this.bindKeyDownListener
.bind( this ),
6962 blur
: this.unbindKeyDownListener
.bind( this )
6967 .addClass( 'oo-ui-radioSelectWidget' )
6968 .attr( 'role', 'radiogroup' );
6973 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
6974 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
6977 * MultioptionWidgets are special elements that can be selected and configured with data. The
6978 * data is often unique for each option, but it does not have to be. MultioptionWidgets are used
6979 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
6980 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
6982 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Multioptions
6985 * @extends OO.ui.Widget
6986 * @mixins OO.ui.mixin.ItemWidget
6987 * @mixins OO.ui.mixin.LabelElement
6990 * @param {Object} [config] Configuration options
6991 * @cfg {boolean} [selected=false] Whether the option is initially selected
6993 OO
.ui
.MultioptionWidget
= function OoUiMultioptionWidget( config
) {
6994 // Configuration initialization
6995 config
= config
|| {};
6997 // Parent constructor
6998 OO
.ui
.MultioptionWidget
.parent
.call( this, config
);
7000 // Mixin constructors
7001 OO
.ui
.mixin
.ItemWidget
.call( this );
7002 OO
.ui
.mixin
.LabelElement
.call( this, config
);
7005 this.selected
= null;
7009 .addClass( 'oo-ui-multioptionWidget' )
7010 .append( this.$label
);
7011 this.setSelected( config
.selected
);
7016 OO
.inheritClass( OO
.ui
.MultioptionWidget
, OO
.ui
.Widget
);
7017 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.ItemWidget
);
7018 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.LabelElement
);
7025 * A change event is emitted when the selected state of the option changes.
7027 * @param {boolean} selected Whether the option is now selected
7033 * Check if the option is selected.
7035 * @return {boolean} Item is selected
7037 OO
.ui
.MultioptionWidget
.prototype.isSelected = function () {
7038 return this.selected
;
7042 * Set the option’s selected state. In general, all modifications to the selection
7043 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
7044 * method instead of this method.
7046 * @param {boolean} [state=false] Select option
7049 OO
.ui
.MultioptionWidget
.prototype.setSelected = function ( state
) {
7051 if ( this.selected
!== state
) {
7052 this.selected
= state
;
7053 this.emit( 'change', state
);
7054 this.$element
.toggleClass( 'oo-ui-multioptionWidget-selected', state
);
7060 * MultiselectWidget allows selecting multiple options from a list.
7062 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
7064 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
7068 * @extends OO.ui.Widget
7069 * @mixins OO.ui.mixin.GroupWidget
7072 * @param {Object} [config] Configuration options
7073 * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
7075 OO
.ui
.MultiselectWidget
= function OoUiMultiselectWidget( config
) {
7076 // Parent constructor
7077 OO
.ui
.MultiselectWidget
.parent
.call( this, config
);
7079 // Configuration initialization
7080 config
= config
|| {};
7082 // Mixin constructors
7083 OO
.ui
.mixin
.GroupWidget
.call( this, config
);
7086 this.aggregate( { change
: 'select' } );
7087 // This is mostly for compatibility with CapsuleMultiselectWidget... normally, 'change' is emitted
7088 // by GroupElement only when items are added/removed
7089 this.connect( this, { select
: [ 'emit', 'change' ] } );
7092 if ( config
.items
) {
7093 this.addItems( config
.items
);
7095 this.$group
.addClass( 'oo-ui-multiselectWidget-group' );
7096 this.$element
.addClass( 'oo-ui-multiselectWidget' )
7097 .append( this.$group
);
7102 OO
.inheritClass( OO
.ui
.MultiselectWidget
, OO
.ui
.Widget
);
7103 OO
.mixinClass( OO
.ui
.MultiselectWidget
, OO
.ui
.mixin
.GroupWidget
);
7110 * A change event is emitted when the set of items changes, or an item is selected or deselected.
7116 * A select event is emitted when an item is selected or deselected.
7122 * Get options that are selected.
7124 * @return {OO.ui.MultioptionWidget[]} Selected options
7126 OO
.ui
.MultiselectWidget
.prototype.getSelectedItems = function () {
7127 return this.items
.filter( function ( item
) {
7128 return item
.isSelected();
7133 * Get the data of options that are selected.
7135 * @return {Object[]|string[]} Values of selected options
7137 OO
.ui
.MultiselectWidget
.prototype.getSelectedItemsData = function () {
7138 return this.getSelectedItems().map( function ( item
) {
7144 * Select options by reference. Options not mentioned in the `items` array will be deselected.
7146 * @param {OO.ui.MultioptionWidget[]} items Items to select
7149 OO
.ui
.MultiselectWidget
.prototype.selectItems = function ( items
) {
7150 this.items
.forEach( function ( item
) {
7151 var selected
= items
.indexOf( item
) !== -1;
7152 item
.setSelected( selected
);
7158 * Select items by their data. Options not mentioned in the `datas` array will be deselected.
7160 * @param {Object[]|string[]} datas Values of items to select
7163 OO
.ui
.MultiselectWidget
.prototype.selectItemsByData = function ( datas
) {
7166 items
= datas
.map( function ( data
) {
7167 return widget
.getItemFromData( data
);
7169 this.selectItems( items
);
7174 * CheckboxMultioptionWidget is an option widget that looks like a checkbox.
7175 * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
7176 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
7178 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
7181 * @extends OO.ui.MultioptionWidget
7184 * @param {Object} [config] Configuration options
7186 OO
.ui
.CheckboxMultioptionWidget
= function OoUiCheckboxMultioptionWidget( config
) {
7187 // Configuration initialization
7188 config
= config
|| {};
7190 // Properties (must be done before parent constructor which calls #setDisabled)
7191 this.checkbox
= new OO
.ui
.CheckboxInputWidget();
7193 // Parent constructor
7194 OO
.ui
.CheckboxMultioptionWidget
.parent
.call( this, config
);
7197 this.checkbox
.on( 'change', this.onCheckboxChange
.bind( this ) );
7198 this.$element
.on( 'keydown', this.onKeyDown
.bind( this ) );
7202 .addClass( 'oo-ui-checkboxMultioptionWidget' )
7203 .prepend( this.checkbox
.$element
);
7208 OO
.inheritClass( OO
.ui
.CheckboxMultioptionWidget
, OO
.ui
.MultioptionWidget
);
7210 /* Static Properties */
7216 OO
.ui
.CheckboxMultioptionWidget
.static.tagName
= 'label';
7221 * Handle checkbox selected state change.
7225 OO
.ui
.CheckboxMultioptionWidget
.prototype.onCheckboxChange = function () {
7226 this.setSelected( this.checkbox
.isSelected() );
7232 OO
.ui
.CheckboxMultioptionWidget
.prototype.setSelected = function ( state
) {
7233 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setSelected
.call( this, state
);
7234 this.checkbox
.setSelected( state
);
7241 OO
.ui
.CheckboxMultioptionWidget
.prototype.setDisabled = function ( disabled
) {
7242 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
7243 this.checkbox
.setDisabled( this.isDisabled() );
7250 OO
.ui
.CheckboxMultioptionWidget
.prototype.focus = function () {
7251 this.checkbox
.focus();
7255 * Handle key down events.
7258 * @param {jQuery.Event} e
7260 OO
.ui
.CheckboxMultioptionWidget
.prototype.onKeyDown = function ( e
) {
7262 element
= this.getElementGroup(),
7265 if ( e
.keyCode
=== OO
.ui
.Keys
.LEFT
|| e
.keyCode
=== OO
.ui
.Keys
.UP
) {
7266 nextItem
= element
.getRelativeFocusableItem( this, -1 );
7267 } else if ( e
.keyCode
=== OO
.ui
.Keys
.RIGHT
|| e
.keyCode
=== OO
.ui
.Keys
.DOWN
) {
7268 nextItem
= element
.getRelativeFocusableItem( this, 1 );
7278 * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
7279 * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
7280 * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
7281 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
7283 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7284 * OO.ui.CheckboxMultiselectInputWidget instead.
7287 * // A CheckboxMultiselectWidget with CheckboxMultioptions.
7288 * var option1 = new OO.ui.CheckboxMultioptionWidget( {
7291 * label: 'Selected checkbox'
7294 * var option2 = new OO.ui.CheckboxMultioptionWidget( {
7296 * label: 'Unselected checkbox'
7299 * var multiselect=new OO.ui.CheckboxMultiselectWidget( {
7300 * items: [ option1, option2 ]
7303 * $( 'body' ).append( multiselect.$element );
7305 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
7308 * @extends OO.ui.MultiselectWidget
7311 * @param {Object} [config] Configuration options
7313 OO
.ui
.CheckboxMultiselectWidget
= function OoUiCheckboxMultiselectWidget( config
) {
7314 // Parent constructor
7315 OO
.ui
.CheckboxMultiselectWidget
.parent
.call( this, config
);
7318 this.$lastClicked
= null;
7321 this.$group
.on( 'click', this.onClick
.bind( this ) );
7325 .addClass( 'oo-ui-checkboxMultiselectWidget' );
7330 OO
.inheritClass( OO
.ui
.CheckboxMultiselectWidget
, OO
.ui
.MultiselectWidget
);
7335 * Get an option by its position relative to the specified item (or to the start of the option array,
7336 * if item is `null`). The direction in which to search through the option array is specified with a
7337 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
7338 * `null` if there are no options in the array.
7340 * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
7341 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
7342 * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items in the select
7344 OO
.ui
.CheckboxMultiselectWidget
.prototype.getRelativeFocusableItem = function ( item
, direction
) {
7345 var currentIndex
, nextIndex
, i
,
7346 increase
= direction
> 0 ? 1 : -1,
7347 len
= this.items
.length
;
7350 currentIndex
= this.items
.indexOf( item
);
7351 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
7353 // If no item is selected and moving forward, start at the beginning.
7354 // If moving backward, start at the end.
7355 nextIndex
= direction
> 0 ? 0 : len
- 1;
7358 for ( i
= 0; i
< len
; i
++ ) {
7359 item
= this.items
[ nextIndex
];
7360 if ( item
&& !item
.isDisabled() ) {
7363 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
7369 * Handle click events on checkboxes.
7371 * @param {jQuery.Event} e
7373 OO
.ui
.CheckboxMultiselectWidget
.prototype.onClick = function ( e
) {
7374 var $options
, lastClickedIndex
, nowClickedIndex
, i
, direction
, wasSelected
, items
,
7375 $lastClicked
= this.$lastClicked
,
7376 $nowClicked
= $( e
.target
).closest( '.oo-ui-checkboxMultioptionWidget' )
7377 .not( '.oo-ui-widget-disabled' );
7379 // Allow selecting multiple options at once by Shift-clicking them
7380 if ( $lastClicked
&& $nowClicked
.length
&& e
.shiftKey
) {
7381 $options
= this.$group
.find( '.oo-ui-checkboxMultioptionWidget' );
7382 lastClickedIndex
= $options
.index( $lastClicked
);
7383 nowClickedIndex
= $options
.index( $nowClicked
);
7384 // If it's the same item, either the user is being silly, or it's a fake event generated by the
7385 // browser. In either case we don't need custom handling.
7386 if ( nowClickedIndex
!== lastClickedIndex
) {
7388 wasSelected
= items
[ nowClickedIndex
].isSelected();
7389 direction
= nowClickedIndex
> lastClickedIndex
? 1 : -1;
7391 // This depends on the DOM order of the items and the order of the .items array being the same.
7392 for ( i
= lastClickedIndex
; i
!== nowClickedIndex
; i
+= direction
) {
7393 if ( !items
[ i
].isDisabled() ) {
7394 items
[ i
].setSelected( !wasSelected
);
7397 // For the now-clicked element, use immediate timeout to allow the browser to do its own
7398 // handling first, then set our value. The order in which events happen is different for
7399 // clicks on the <input> and on the <label> and there are additional fake clicks fired for
7400 // non-click actions that change the checkboxes.
7402 setTimeout( function () {
7403 if ( !items
[ nowClickedIndex
].isDisabled() ) {
7404 items
[ nowClickedIndex
].setSelected( !wasSelected
);
7410 if ( $nowClicked
.length
) {
7411 this.$lastClicked
= $nowClicked
;
7416 * FloatingMenuSelectWidget is a menu that will stick under a specified
7417 * container, even when it is inserted elsewhere in the document (for example,
7418 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
7419 * menu from being clipped too aggresively.
7421 * The menu's position is automatically calculated and maintained when the menu
7422 * is toggled or the window is resized.
7424 * See OO.ui.ComboBoxInputWidget for an example of a widget that uses this class.
7427 * @extends OO.ui.MenuSelectWidget
7428 * @mixins OO.ui.mixin.FloatableElement
7431 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
7432 * Deprecated, omit this parameter and specify `$container` instead.
7433 * @param {Object} [config] Configuration options
7434 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
7436 OO
.ui
.FloatingMenuSelectWidget
= function OoUiFloatingMenuSelectWidget( inputWidget
, config
) {
7437 // Allow 'inputWidget' parameter and config for backwards compatibility
7438 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
7439 config
= inputWidget
;
7440 inputWidget
= config
.inputWidget
;
7443 // Configuration initialization
7444 config
= config
|| {};
7446 // Parent constructor
7447 OO
.ui
.FloatingMenuSelectWidget
.parent
.call( this, config
);
7449 // Properties (must be set before mixin constructors)
7450 this.inputWidget
= inputWidget
; // For backwards compatibility
7451 this.$container
= config
.$container
|| this.inputWidget
.$element
;
7453 // Mixins constructors
7454 OO
.ui
.mixin
.FloatableElement
.call( this, $.extend( {}, config
, { $floatableContainer
: this.$container
} ) );
7457 this.$element
.addClass( 'oo-ui-floatingMenuSelectWidget' );
7458 // For backwards compatibility
7459 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
7464 OO
.inheritClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
7465 OO
.mixinClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.mixin
.FloatableElement
);
7472 OO
.ui
.FloatingMenuSelectWidget
.prototype.toggle = function ( visible
) {
7474 visible
= visible
=== undefined ? !this.isVisible() : !!visible
;
7475 change
= visible
!== this.isVisible();
7477 if ( change
&& visible
) {
7478 // Make sure the width is set before the parent method runs.
7479 this.setIdealSize( this.$container
.width() );
7483 // This will call this.clip(), which is nonsensical since we're not positioned yet...
7484 OO
.ui
.FloatingMenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
7487 this.togglePositioning( this.isVisible() );
7494 * The old name for the FloatingMenuSelectWidget widget, provided for backwards-compatibility.
7497 * @extends OO.ui.FloatingMenuSelectWidget
7500 * @deprecated since v0.12.5.
7502 OO
.ui
.TextInputMenuSelectWidget
= function OoUiTextInputMenuSelectWidget() {
7503 OO
.ui
.warnDeprecation( 'TextInputMenuSelectWidget is deprecated. Use the FloatingMenuSelectWidget instead.' );
7504 // Parent constructor
7505 OO
.ui
.TextInputMenuSelectWidget
.parent
.apply( this, arguments
);
7508 OO
.inheritClass( OO
.ui
.TextInputMenuSelectWidget
, OO
.ui
.FloatingMenuSelectWidget
);
7511 * Progress bars visually display the status of an operation, such as a download,
7512 * and can be either determinate or indeterminate:
7514 * - **determinate** process bars show the percent of an operation that is complete.
7516 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
7517 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
7518 * not use percentages.
7520 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
7523 * // Examples of determinate and indeterminate progress bars.
7524 * var progressBar1 = new OO.ui.ProgressBarWidget( {
7527 * var progressBar2 = new OO.ui.ProgressBarWidget();
7529 * // Create a FieldsetLayout to layout progress bars
7530 * var fieldset = new OO.ui.FieldsetLayout;
7531 * fieldset.addItems( [
7532 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
7533 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
7535 * $( 'body' ).append( fieldset.$element );
7538 * @extends OO.ui.Widget
7541 * @param {Object} [config] Configuration options
7542 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
7543 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
7544 * By default, the progress bar is indeterminate.
7546 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
7547 // Configuration initialization
7548 config
= config
|| {};
7550 // Parent constructor
7551 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
7554 this.$bar
= $( '<div>' );
7555 this.progress
= null;
7558 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
7559 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
7562 role
: 'progressbar',
7564 'aria-valuemax': 100
7566 .addClass( 'oo-ui-progressBarWidget' )
7567 .append( this.$bar
);
7572 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
7574 /* Static Properties */
7580 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
7585 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
7587 * @return {number|boolean} Progress percent
7589 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
7590 return this.progress
;
7594 * Set the percent of the process completed or `false` for an indeterminate process.
7596 * @param {number|boolean} progress Progress percent or `false` for indeterminate
7598 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
7599 this.progress
= progress
;
7601 if ( progress
!== false ) {
7602 this.$bar
.css( 'width', this.progress
+ '%' );
7603 this.$element
.attr( 'aria-valuenow', this.progress
);
7605 this.$bar
.css( 'width', '' );
7606 this.$element
.removeAttr( 'aria-valuenow' );
7608 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress
=== false );
7612 * InputWidget is the base class for all input widgets, which
7613 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
7614 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
7615 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
7617 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7621 * @extends OO.ui.Widget
7622 * @mixins OO.ui.mixin.FlaggedElement
7623 * @mixins OO.ui.mixin.TabIndexedElement
7624 * @mixins OO.ui.mixin.TitledElement
7625 * @mixins OO.ui.mixin.AccessKeyedElement
7628 * @param {Object} [config] Configuration options
7629 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
7630 * @cfg {string} [value=''] The value of the input.
7631 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
7632 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
7633 * before it is accepted.
7635 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
7636 // Configuration initialization
7637 config
= config
|| {};
7639 // Parent constructor
7640 OO
.ui
.InputWidget
.parent
.call( this, config
);
7643 // See #reusePreInfuseDOM about config.$input
7644 this.$input
= config
.$input
|| this.getInputElement( config
);
7646 this.inputFilter
= config
.inputFilter
;
7648 // Mixin constructors
7649 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
7650 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
7651 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
7652 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$input
} ) );
7655 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
7659 .addClass( 'oo-ui-inputWidget-input' )
7660 .attr( 'name', config
.name
)
7661 .prop( 'disabled', this.isDisabled() );
7663 .addClass( 'oo-ui-inputWidget' )
7664 .append( this.$input
);
7665 this.setValue( config
.value
);
7667 this.setDir( config
.dir
);
7673 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
7674 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
7675 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
7676 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
7677 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
7679 /* Static Properties */
7685 OO
.ui
.InputWidget
.static.supportsSimpleLabel
= true;
7687 /* Static Methods */
7692 OO
.ui
.InputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
7693 config
= OO
.ui
.InputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
7694 // Reusing $input lets browsers preserve inputted values across page reloads (T114134)
7695 config
.$input
= $( node
).find( '.oo-ui-inputWidget-input' );
7702 OO
.ui
.InputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
7703 var state
= OO
.ui
.InputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
7704 if ( config
.$input
&& config
.$input
.length
) {
7705 state
.value
= config
.$input
.val();
7706 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
7707 state
.focus
= config
.$input
.is( ':focus' );
7717 * A change event is emitted when the value of the input changes.
7719 * @param {string} value
7725 * Get input element.
7727 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
7728 * different circumstances. The element must have a `value` property (like form elements).
7731 * @param {Object} config Configuration options
7732 * @return {jQuery} Input element
7734 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
7735 return $( '<input>' );
7739 * Get input element's ID.
7741 * If the element already has an ID then that is returned, otherwise unique ID is
7742 * generated, set on the element, and returned.
7744 * @return {string} The ID of the element
7746 OO
.ui
.InputWidget
.prototype.getInputId = function () {
7747 var id
= this.$input
.attr( 'id' );
7749 if ( id
=== undefined ) {
7750 id
= OO
.ui
.generateElementId();
7751 this.$input
.attr( 'id', id
);
7758 * Handle potentially value-changing events.
7761 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
7763 OO
.ui
.InputWidget
.prototype.onEdit = function () {
7765 if ( !this.isDisabled() ) {
7766 // Allow the stack to clear so the value will be updated
7767 setTimeout( function () {
7768 widget
.setValue( widget
.$input
.val() );
7774 * Get the value of the input.
7776 * @return {string} Input value
7778 OO
.ui
.InputWidget
.prototype.getValue = function () {
7779 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
7780 // it, and we won't know unless they're kind enough to trigger a 'change' event.
7781 var value
= this.$input
.val();
7782 if ( this.value
!== value
) {
7783 this.setValue( value
);
7789 * Set the directionality of the input.
7791 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
7794 OO
.ui
.InputWidget
.prototype.setDir = function ( dir
) {
7795 this.$input
.prop( 'dir', dir
);
7800 * Set the value of the input.
7802 * @param {string} value New value
7806 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
7807 value
= this.cleanUpValue( value
);
7808 // Update the DOM if it has changed. Note that with cleanUpValue, it
7809 // is possible for the DOM value to change without this.value changing.
7810 if ( this.$input
.val() !== value
) {
7811 this.$input
.val( value
);
7813 if ( this.value
!== value
) {
7815 this.emit( 'change', this.value
);
7821 * Clean up incoming value.
7823 * Ensures value is a string, and converts undefined and null to empty string.
7826 * @param {string} value Original value
7827 * @return {string} Cleaned up value
7829 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
7830 if ( value
=== undefined || value
=== null ) {
7832 } else if ( this.inputFilter
) {
7833 return this.inputFilter( String( value
) );
7835 return String( value
);
7840 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
7841 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
7844 OO
.ui
.InputWidget
.prototype.simulateLabelClick = function () {
7845 OO
.ui
.warnDeprecation( 'InputWidget: simulateLabelClick() is deprecated.' );
7846 if ( !this.isDisabled() ) {
7847 if ( this.$input
.is( ':checkbox, :radio' ) ) {
7848 this.$input
.click();
7850 if ( this.$input
.is( ':input' ) ) {
7851 this.$input
[ 0 ].focus();
7859 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
7860 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
7861 if ( this.$input
) {
7862 this.$input
.prop( 'disabled', this.isDisabled() );
7872 OO
.ui
.InputWidget
.prototype.focus = function () {
7873 this.$input
[ 0 ].focus();
7882 OO
.ui
.InputWidget
.prototype.blur = function () {
7883 this.$input
[ 0 ].blur();
7890 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
7891 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
7892 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
7893 this.setValue( state
.value
);
7895 if ( state
.focus
) {
7901 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
7902 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
7903 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
7904 * HTML `<button>` (the default) or an HTML `<input>` tags. See the
7905 * [OOjs UI documentation on MediaWiki] [1] for more information.
7908 * // A ButtonInputWidget rendered as an HTML button, the default.
7909 * var button = new OO.ui.ButtonInputWidget( {
7910 * label: 'Input button',
7914 * $( 'body' ).append( button.$element );
7916 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
7919 * @extends OO.ui.InputWidget
7920 * @mixins OO.ui.mixin.ButtonElement
7921 * @mixins OO.ui.mixin.IconElement
7922 * @mixins OO.ui.mixin.IndicatorElement
7923 * @mixins OO.ui.mixin.LabelElement
7924 * @mixins OO.ui.mixin.TitledElement
7927 * @param {Object} [config] Configuration options
7928 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
7929 * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
7930 * Widgets configured to be an `<input>` do not support {@link #icon icons} and {@link #indicator indicators},
7931 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
7932 * be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
7934 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
7935 // Configuration initialization
7936 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
7938 // See InputWidget#reusePreInfuseDOM about config.$input
7939 if ( config
.$input
) {
7940 config
.$input
.empty();
7943 // Properties (must be set before parent constructor, which calls #setValue)
7944 this.useInputTag
= config
.useInputTag
;
7946 // Parent constructor
7947 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
7949 // Mixin constructors
7950 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
7951 OO
.ui
.mixin
.IconElement
.call( this, config
);
7952 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
7953 OO
.ui
.mixin
.LabelElement
.call( this, config
);
7954 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
7957 if ( !config
.useInputTag
) {
7958 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
7960 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
7965 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
7966 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
7967 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
7968 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
7969 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
7970 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
7972 /* Static Properties */
7975 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
7976 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
7981 OO
.ui
.ButtonInputWidget
.static.supportsSimpleLabel
= false;
7989 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
7991 type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ? config
.type
: 'button';
7992 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
7998 * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
8000 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
8001 * text, or `null` for no label
8004 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
8005 if ( typeof label
=== 'function' ) {
8006 label
= OO
.ui
.resolveMsg( label
);
8009 if ( this.useInputTag
) {
8010 // Discard non-plaintext labels
8011 if ( typeof label
!== 'string' ) {
8015 this.$input
.val( label
);
8018 return OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
8022 * Set the value of the input.
8024 * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
8025 * they do not support {@link #value values}.
8027 * @param {string} value New value
8030 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
8031 if ( !this.useInputTag
) {
8032 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
8038 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
8039 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
8040 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
8041 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
8043 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
8046 * // An example of selected, unselected, and disabled checkbox inputs
8047 * var checkbox1=new OO.ui.CheckboxInputWidget( {
8051 * var checkbox2=new OO.ui.CheckboxInputWidget( {
8054 * var checkbox3=new OO.ui.CheckboxInputWidget( {
8058 * // Create a fieldset layout with fields for each checkbox.
8059 * var fieldset = new OO.ui.FieldsetLayout( {
8060 * label: 'Checkboxes'
8062 * fieldset.addItems( [
8063 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
8064 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
8065 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
8067 * $( 'body' ).append( fieldset.$element );
8069 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8072 * @extends OO.ui.InputWidget
8075 * @param {Object} [config] Configuration options
8076 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
8078 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
8079 // Configuration initialization
8080 config
= config
|| {};
8082 // Parent constructor
8083 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
8087 .addClass( 'oo-ui-checkboxInputWidget' )
8088 // Required for pretty styling in MediaWiki theme
8089 .append( $( '<span>' ) );
8090 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
8095 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
8097 /* Static Methods */
8102 OO
.ui
.CheckboxInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8103 var state
= OO
.ui
.CheckboxInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8104 state
.checked
= config
.$input
.prop( 'checked' );
8114 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
8115 return $( '<input>' ).attr( 'type', 'checkbox' );
8121 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
8123 if ( !this.isDisabled() ) {
8124 // Allow the stack to clear so the value will be updated
8125 setTimeout( function () {
8126 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
8132 * Set selection state of this checkbox.
8134 * @param {boolean} state `true` for selected
8137 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
8139 if ( this.selected
!== state
) {
8140 this.selected
= state
;
8141 this.$input
.prop( 'checked', this.selected
);
8142 this.emit( 'change', this.selected
);
8148 * Check if this checkbox is selected.
8150 * @return {boolean} Checkbox is selected
8152 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
8153 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
8154 // it, and we won't know unless they're kind enough to trigger a 'change' event.
8155 var selected
= this.$input
.prop( 'checked' );
8156 if ( this.selected
!== selected
) {
8157 this.setSelected( selected
);
8159 return this.selected
;
8165 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
8166 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
8167 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
8168 this.setSelected( state
.checked
);
8173 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
8174 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
8175 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
8176 * more information about input widgets.
8178 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
8179 * are no options. If no `value` configuration option is provided, the first option is selected.
8180 * If you need a state representing no value (no option being selected), use a DropdownWidget.
8182 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
8185 * // Example: A DropdownInputWidget with three options
8186 * var dropdownInput = new OO.ui.DropdownInputWidget( {
8188 * { data: 'a', label: 'First' },
8189 * { data: 'b', label: 'Second'},
8190 * { data: 'c', label: 'Third' }
8193 * $( 'body' ).append( dropdownInput.$element );
8195 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8198 * @extends OO.ui.InputWidget
8199 * @mixins OO.ui.mixin.TitledElement
8202 * @param {Object} [config] Configuration options
8203 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
8204 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
8206 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
8207 // Configuration initialization
8208 config
= config
|| {};
8210 // See InputWidget#reusePreInfuseDOM about config.$input
8211 if ( config
.$input
) {
8212 config
.$input
.addClass( 'oo-ui-element-hidden' );
8215 // Properties (must be done before parent constructor which calls #setDisabled)
8216 this.dropdownWidget
= new OO
.ui
.DropdownWidget( config
.dropdown
);
8218 // Parent constructor
8219 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
8221 // Mixin constructors
8222 OO
.ui
.mixin
.TitledElement
.call( this, config
);
8225 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
8228 this.setOptions( config
.options
|| [] );
8230 .addClass( 'oo-ui-dropdownInputWidget' )
8231 .append( this.dropdownWidget
.$element
);
8236 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
8237 OO
.mixinClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.mixin
.TitledElement
);
8245 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
8246 return $( '<input>' ).attr( 'type', 'hidden' );
8250 * Handles menu select events.
8253 * @param {OO.ui.MenuOptionWidget} item Selected menu item
8255 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
8256 this.setValue( item
.getData() );
8262 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
8263 value
= this.cleanUpValue( value
);
8264 this.dropdownWidget
.getMenu().selectItemByData( value
);
8265 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
8272 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
8273 this.dropdownWidget
.setDisabled( state
);
8274 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
8279 * Set the options available for this input.
8281 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
8284 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
8286 value
= this.getValue(),
8289 // Rebuild the dropdown menu
8290 this.dropdownWidget
.getMenu()
8292 .addItems( options
.map( function ( opt
) {
8293 var optValue
= widget
.cleanUpValue( opt
.data
);
8294 return new OO
.ui
.MenuOptionWidget( {
8296 label
: opt
.label
!== undefined ? opt
.label
: optValue
8300 // Restore the previous value, or reset to something sensible
8301 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
8302 // Previous value is still available, ensure consistency with the dropdown
8303 this.setValue( value
);
8305 // No longer valid, reset
8306 if ( options
.length
) {
8307 this.setValue( options
[ 0 ].data
);
8317 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
8318 this.dropdownWidget
.getMenu().toggle( true );
8325 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
8326 this.dropdownWidget
.getMenu().toggle( false );
8331 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
8332 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
8333 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
8334 * please see the [OOjs UI documentation on MediaWiki][1].
8336 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
8339 * // An example of selected, unselected, and disabled radio inputs
8340 * var radio1 = new OO.ui.RadioInputWidget( {
8344 * var radio2 = new OO.ui.RadioInputWidget( {
8347 * var radio3 = new OO.ui.RadioInputWidget( {
8351 * // Create a fieldset layout with fields for each radio button.
8352 * var fieldset = new OO.ui.FieldsetLayout( {
8353 * label: 'Radio inputs'
8355 * fieldset.addItems( [
8356 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
8357 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
8358 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
8360 * $( 'body' ).append( fieldset.$element );
8362 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8365 * @extends OO.ui.InputWidget
8368 * @param {Object} [config] Configuration options
8369 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
8371 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
8372 // Configuration initialization
8373 config
= config
|| {};
8375 // Parent constructor
8376 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
8380 .addClass( 'oo-ui-radioInputWidget' )
8381 // Required for pretty styling in MediaWiki theme
8382 .append( $( '<span>' ) );
8383 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
8388 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
8390 /* Static Methods */
8395 OO
.ui
.RadioInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8396 var state
= OO
.ui
.RadioInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8397 state
.checked
= config
.$input
.prop( 'checked' );
8407 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
8408 return $( '<input>' ).attr( 'type', 'radio' );
8414 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
8415 // RadioInputWidget doesn't track its state.
8419 * Set selection state of this radio button.
8421 * @param {boolean} state `true` for selected
8424 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
8425 // RadioInputWidget doesn't track its state.
8426 this.$input
.prop( 'checked', state
);
8431 * Check if this radio button is selected.
8433 * @return {boolean} Radio is selected
8435 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
8436 return this.$input
.prop( 'checked' );
8442 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
8443 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
8444 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
8445 this.setSelected( state
.checked
);
8450 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
8451 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
8452 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
8453 * more information about input widgets.
8455 * This and OO.ui.DropdownInputWidget support the same configuration options.
8458 * // Example: A RadioSelectInputWidget with three options
8459 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
8461 * { data: 'a', label: 'First' },
8462 * { data: 'b', label: 'Second'},
8463 * { data: 'c', label: 'Third' }
8466 * $( 'body' ).append( radioSelectInput.$element );
8468 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8471 * @extends OO.ui.InputWidget
8474 * @param {Object} [config] Configuration options
8475 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
8477 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
8478 // Configuration initialization
8479 config
= config
|| {};
8481 // Properties (must be done before parent constructor which calls #setDisabled)
8482 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
8484 // Parent constructor
8485 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
8488 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
8491 this.setOptions( config
.options
|| [] );
8493 .addClass( 'oo-ui-radioSelectInputWidget' )
8494 .append( this.radioSelectWidget
.$element
);
8499 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
8501 /* Static Properties */
8507 OO
.ui
.RadioSelectInputWidget
.static.supportsSimpleLabel
= false;
8509 /* Static Methods */
8514 OO
.ui
.RadioSelectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8515 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8516 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
8523 OO
.ui
.RadioSelectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
8524 config
= OO
.ui
.RadioSelectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
8525 // Cannot reuse the `<input type=radio>` set
8526 delete config
.$input
;
8536 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
8537 return $( '<input>' ).attr( 'type', 'hidden' );
8541 * Handles menu select events.
8544 * @param {OO.ui.RadioOptionWidget} item Selected menu item
8546 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
8547 this.setValue( item
.getData() );
8553 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
8554 value
= this.cleanUpValue( value
);
8555 this.radioSelectWidget
.selectItemByData( value
);
8556 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
8563 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
8564 this.radioSelectWidget
.setDisabled( state
);
8565 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
8570 * Set the options available for this input.
8572 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
8575 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
8577 value
= this.getValue(),
8580 // Rebuild the radioSelect menu
8581 this.radioSelectWidget
8583 .addItems( options
.map( function ( opt
) {
8584 var optValue
= widget
.cleanUpValue( opt
.data
);
8585 return new OO
.ui
.RadioOptionWidget( {
8587 label
: opt
.label
!== undefined ? opt
.label
: optValue
8591 // Restore the previous value, or reset to something sensible
8592 if ( this.radioSelectWidget
.getItemFromData( value
) ) {
8593 // Previous value is still available, ensure consistency with the radioSelect
8594 this.setValue( value
);
8596 // No longer valid, reset
8597 if ( options
.length
) {
8598 this.setValue( options
[ 0 ].data
);
8606 * CheckboxMultiselectInputWidget is a
8607 * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
8608 * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
8609 * HTML `<input type=checkbox>` tags. Please see the [OOjs UI documentation on MediaWiki][1] for
8610 * more information about input widgets.
8613 * // Example: A CheckboxMultiselectInputWidget with three options
8614 * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
8616 * { data: 'a', label: 'First' },
8617 * { data: 'b', label: 'Second'},
8618 * { data: 'c', label: 'Third' }
8621 * $( 'body' ).append( multiselectInput.$element );
8623 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8626 * @extends OO.ui.InputWidget
8629 * @param {Object} [config] Configuration options
8630 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: …, disabled: … }`
8632 OO
.ui
.CheckboxMultiselectInputWidget
= function OoUiCheckboxMultiselectInputWidget( config
) {
8633 // Configuration initialization
8634 config
= config
|| {};
8636 // Properties (must be done before parent constructor which calls #setDisabled)
8637 this.checkboxMultiselectWidget
= new OO
.ui
.CheckboxMultiselectWidget();
8639 // Parent constructor
8640 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.call( this, config
);
8643 this.inputName
= config
.name
;
8647 .addClass( 'oo-ui-checkboxMultiselectInputWidget' )
8648 .append( this.checkboxMultiselectWidget
.$element
);
8649 // We don't use this.$input, but rather the CheckboxInputWidgets inside each option
8650 this.$input
.detach();
8651 this.setOptions( config
.options
|| [] );
8652 // Have to repeat this from parent, as we need options to be set up for this to make sense
8653 this.setValue( config
.value
);
8658 OO
.inheritClass( OO
.ui
.CheckboxMultiselectInputWidget
, OO
.ui
.InputWidget
);
8660 /* Static Properties */
8666 OO
.ui
.CheckboxMultiselectInputWidget
.static.supportsSimpleLabel
= false;
8668 /* Static Methods */
8673 OO
.ui
.CheckboxMultiselectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8674 var state
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8675 state
.value
= $( node
).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
8676 .toArray().map( function ( el
) { return el
.value
; } );
8683 OO
.ui
.CheckboxMultiselectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
8684 config
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
8685 // Cannot reuse the `<input type=checkbox>` set
8686 delete config
.$input
;
8696 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getInputElement = function () {
8698 return $( '<div>' );
8704 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getValue = function () {
8705 var value
= this.$element
.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
8706 .toArray().map( function ( el
) { return el
.value
; } );
8707 if ( this.value
!== value
) {
8708 this.setValue( value
);
8716 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setValue = function ( value
) {
8717 value
= this.cleanUpValue( value
);
8718 this.checkboxMultiselectWidget
.selectItemsByData( value
);
8719 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setValue
.call( this, value
);
8724 * Clean up incoming value.
8726 * @param {string[]} value Original value
8727 * @return {string[]} Cleaned up value
8729 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.cleanUpValue = function ( value
) {
8732 if ( !Array
.isArray( value
) ) {
8735 for ( i
= 0; i
< value
.length
; i
++ ) {
8737 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( this, value
[ i
] );
8738 // Remove options that we don't have here
8739 if ( !this.checkboxMultiselectWidget
.getItemFromData( singleValue
) ) {
8742 cleanValue
.push( singleValue
);
8750 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setDisabled = function ( state
) {
8751 this.checkboxMultiselectWidget
.setDisabled( state
);
8752 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
8757 * Set the options available for this input.
8759 * @param {Object[]} options Array of menu options in the format `{ data: …, label: …, disabled: … }`
8762 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setOptions = function ( options
) {
8765 // Rebuild the checkboxMultiselectWidget menu
8766 this.checkboxMultiselectWidget
8768 .addItems( options
.map( function ( opt
) {
8769 var optValue
, item
, optDisabled
;
8771 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( widget
, opt
.data
);
8772 optDisabled
= opt
.disabled
!== undefined ? opt
.disabled
: false;
8773 item
= new OO
.ui
.CheckboxMultioptionWidget( {
8775 label
: opt
.label
!== undefined ? opt
.label
: optValue
,
8776 disabled
: optDisabled
8778 // Set the 'name' and 'value' for form submission
8779 item
.checkbox
.$input
.attr( 'name', widget
.inputName
);
8780 item
.checkbox
.setValue( optValue
);
8784 // Re-set the value, checking the checkboxes as needed.
8785 // This will also get rid of any stale options that we just removed.
8786 this.setValue( this.getValue() );
8792 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
8793 * size of the field as well as its presentation. In addition, these widgets can be configured
8794 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
8795 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
8796 * which modifies incoming values rather than validating them.
8797 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
8799 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
8802 * // Example of a text input widget
8803 * var textInput = new OO.ui.TextInputWidget( {
8804 * value: 'Text input'
8806 * $( 'body' ).append( textInput.$element );
8808 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8811 * @extends OO.ui.InputWidget
8812 * @mixins OO.ui.mixin.IconElement
8813 * @mixins OO.ui.mixin.IndicatorElement
8814 * @mixins OO.ui.mixin.PendingElement
8815 * @mixins OO.ui.mixin.LabelElement
8818 * @param {Object} [config] Configuration options
8819 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
8820 * 'email', 'url', 'date', 'month' or 'number'. Ignored if `multiline` is true.
8822 * Some values of `type` result in additional behaviors:
8824 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
8825 * empties the text field
8826 * @cfg {string} [placeholder] Placeholder text
8827 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
8828 * instruct the browser to focus this widget.
8829 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
8830 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
8831 * @cfg {boolean} [multiline=false] Allow multiple lines of text
8832 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
8833 * specifies minimum number of rows to display.
8834 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
8835 * Use the #maxRows config to specify a maximum number of displayed rows.
8836 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
8837 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
8838 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
8839 * the value or placeholder text: `'before'` or `'after'`
8840 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
8841 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
8842 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
8843 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
8844 * (the value must contain only numbers); when RegExp, a regular expression that must match the
8845 * value for it to be considered valid; when Function, a function receiving the value as parameter
8846 * that must return true, or promise resolving to true, for it to be considered valid.
8848 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
8849 // Configuration initialization
8850 config
= $.extend( {
8852 labelPosition
: 'after'
8855 if ( config
.type
=== 'search' ) {
8856 OO
.ui
.warnDeprecation( 'TextInputWidget: config.type=\'search\' is deprecated. Use the SearchInputWidget instead. See T148471 for details.' );
8857 if ( config
.icon
=== undefined ) {
8858 config
.icon
= 'search';
8860 // indicator: 'clear' is set dynamically later, depending on value
8863 // Parent constructor
8864 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
8866 // Mixin constructors
8867 OO
.ui
.mixin
.IconElement
.call( this, config
);
8868 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
8869 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
8870 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8873 this.type
= this.getSaneType( config
);
8874 this.readOnly
= false;
8875 this.required
= false;
8876 this.multiline
= !!config
.multiline
;
8877 this.autosize
= !!config
.autosize
;
8878 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
8879 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
8880 this.validate
= null;
8881 this.styleHeight
= null;
8882 this.scrollWidth
= null;
8884 // Clone for resizing
8885 if ( this.autosize
) {
8886 this.$clone
= this.$input
8888 .insertAfter( this.$input
)
8889 .attr( 'aria-hidden', 'true' )
8890 .addClass( 'oo-ui-element-hidden' );
8893 this.setValidation( config
.validate
);
8894 this.setLabelPosition( config
.labelPosition
);
8898 keypress
: this.onKeyPress
.bind( this ),
8899 blur
: this.onBlur
.bind( this ),
8900 focus
: this.onFocus
.bind( this )
8902 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
8903 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
8904 this.on( 'labelChange', this.updatePosition
.bind( this ) );
8905 this.connect( this, {
8907 disable
: 'onDisable'
8909 this.on( 'change', OO
.ui
.debounce( this.onDebouncedChange
.bind( this ), 250 ) );
8913 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
8914 .append( this.$icon
, this.$indicator
);
8915 this.setReadOnly( !!config
.readOnly
);
8916 this.setRequired( !!config
.required
);
8917 this.updateSearchIndicator();
8918 if ( config
.placeholder
!== undefined ) {
8919 this.$input
.attr( 'placeholder', config
.placeholder
);
8921 if ( config
.maxLength
!== undefined ) {
8922 this.$input
.attr( 'maxlength', config
.maxLength
);
8924 if ( config
.autofocus
) {
8925 this.$input
.attr( 'autofocus', 'autofocus' );
8927 if ( config
.autocomplete
=== false ) {
8928 this.$input
.attr( 'autocomplete', 'off' );
8929 // Turning off autocompletion also disables "form caching" when the user navigates to a
8930 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
8932 beforeunload: function () {
8933 this.$input
.removeAttr( 'autocomplete' );
8935 pageshow: function () {
8936 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
8937 // whole page... it shouldn't hurt, though.
8938 this.$input
.attr( 'autocomplete', 'off' );
8942 if ( this.multiline
&& config
.rows
) {
8943 this.$input
.attr( 'rows', config
.rows
);
8945 if ( this.label
|| config
.autosize
) {
8946 this.isWaitingToBeAttached
= true;
8947 this.installParentChangeDetector();
8953 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
8954 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
8955 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
8956 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
8957 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
8959 /* Static Properties */
8961 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
8966 /* Static Methods */
8971 OO
.ui
.TextInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8972 var state
= OO
.ui
.TextInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8973 if ( config
.multiline
) {
8974 state
.scrollTop
= config
.$input
.scrollTop();
8982 * An `enter` event is emitted when the user presses 'enter' inside the text box.
8984 * Not emitted if the input is multiline.
8990 * A `resize` event is emitted when autosize is set and the widget resizes
8998 * Handle icon mouse down events.
9001 * @param {jQuery.Event} e Mouse down event
9003 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
9004 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
9005 this.$input
[ 0 ].focus();
9011 * Handle indicator mouse down events.
9014 * @param {jQuery.Event} e Mouse down event
9016 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
9017 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
9018 if ( this.type
=== 'search' ) {
9019 // Clear the text field
9020 this.setValue( '' );
9022 this.$input
[ 0 ].focus();
9028 * Handle key press events.
9031 * @param {jQuery.Event} e Key press event
9032 * @fires enter If enter key is pressed and input is not multiline
9034 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
9035 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
9036 this.emit( 'enter', e
);
9041 * Handle blur events.
9044 * @param {jQuery.Event} e Blur event
9046 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
9047 this.setValidityFlag();
9051 * Handle focus events.
9054 * @param {jQuery.Event} e Focus event
9056 OO
.ui
.TextInputWidget
.prototype.onFocus = function () {
9057 if ( this.isWaitingToBeAttached
) {
9058 // If we've received focus, then we must be attached to the document, and if
9059 // isWaitingToBeAttached is still true, that means the handler never fired. Fire it now.
9060 this.onElementAttach();
9062 this.setValidityFlag( true );
9066 * Handle element attach events.
9069 * @param {jQuery.Event} e Element attach event
9071 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
9072 this.isWaitingToBeAttached
= false;
9073 // Any previously calculated size is now probably invalid if we reattached elsewhere
9074 this.valCache
= null;
9076 this.positionLabel();
9080 * Handle change events.
9082 * @param {string} value
9085 OO
.ui
.TextInputWidget
.prototype.onChange = function () {
9086 this.updateSearchIndicator();
9091 * Handle debounced change events.
9093 * @param {string} value
9096 OO
.ui
.TextInputWidget
.prototype.onDebouncedChange = function () {
9097 this.setValidityFlag();
9101 * Handle disable events.
9103 * @param {boolean} disabled Element is disabled
9106 OO
.ui
.TextInputWidget
.prototype.onDisable = function () {
9107 this.updateSearchIndicator();
9111 * Check if the input is {@link #readOnly read-only}.
9115 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
9116 return this.readOnly
;
9120 * Set the {@link #readOnly read-only} state of the input.
9122 * @param {boolean} state Make input read-only
9125 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
9126 this.readOnly
= !!state
;
9127 this.$input
.prop( 'readOnly', this.readOnly
);
9128 this.updateSearchIndicator();
9133 * Check if the input is {@link #required required}.
9137 OO
.ui
.TextInputWidget
.prototype.isRequired = function () {
9138 return this.required
;
9142 * Set the {@link #required required} state of the input.
9144 * @param {boolean} state Make input required
9147 OO
.ui
.TextInputWidget
.prototype.setRequired = function ( state
) {
9148 this.required
= !!state
;
9149 if ( this.required
) {
9151 .attr( 'required', 'required' )
9152 .attr( 'aria-required', 'true' );
9153 if ( this.getIndicator() === null ) {
9154 this.setIndicator( 'required' );
9158 .removeAttr( 'required' )
9159 .removeAttr( 'aria-required' );
9160 if ( this.getIndicator() === 'required' ) {
9161 this.setIndicator( null );
9164 this.updateSearchIndicator();
9169 * Support function for making #onElementAttach work across browsers.
9171 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
9172 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
9174 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
9175 * first time that the element gets attached to the documented.
9177 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
9178 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
9179 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
9182 if ( MutationObserver
) {
9183 // The new way. If only it wasn't so ugly.
9185 if ( this.isElementAttached() ) {
9186 // Widget is attached already, do nothing. This breaks the functionality of this function when
9187 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
9188 // would require observation of the whole document, which would hurt performance of other,
9189 // more important code.
9193 // Find topmost node in the tree
9194 topmostNode
= this.$element
[ 0 ];
9195 while ( topmostNode
.parentNode
) {
9196 topmostNode
= topmostNode
.parentNode
;
9199 // We have no way to detect the $element being attached somewhere without observing the entire
9200 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
9201 // parent node of $element, and instead detect when $element is removed from it (and thus
9202 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
9203 // doesn't get attached, we end up back here and create the parent.
9205 mutationObserver
= new MutationObserver( function ( mutations
) {
9206 var i
, j
, removedNodes
;
9207 for ( i
= 0; i
< mutations
.length
; i
++ ) {
9208 removedNodes
= mutations
[ i
].removedNodes
;
9209 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
9210 if ( removedNodes
[ j
] === topmostNode
) {
9211 setTimeout( onRemove
, 0 );
9218 onRemove = function () {
9219 // If the node was attached somewhere else, report it
9220 if ( widget
.isElementAttached() ) {
9221 widget
.onElementAttach();
9223 mutationObserver
.disconnect();
9224 widget
.installParentChangeDetector();
9227 // Create a fake parent and observe it
9228 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
9229 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
9231 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
9232 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
9233 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
9238 * Automatically adjust the size of the text input.
9240 * This only affects #multiline inputs that are {@link #autosize autosized}.
9245 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
9246 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
,
9247 idealHeight
, newHeight
, scrollWidth
, property
;
9249 if ( this.isWaitingToBeAttached
) {
9250 // #onElementAttach will be called soon, which calls this method
9254 if ( this.multiline
&& this.$input
.val() !== this.valCache
) {
9255 if ( this.autosize
) {
9257 .val( this.$input
.val() )
9258 .attr( 'rows', this.minRows
)
9259 // Set inline height property to 0 to measure scroll height
9260 .css( 'height', 0 );
9262 this.$clone
.removeClass( 'oo-ui-element-hidden' );
9264 this.valCache
= this.$input
.val();
9266 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
9268 // Remove inline height property to measure natural heights
9269 this.$clone
.css( 'height', '' );
9270 innerHeight
= this.$clone
.innerHeight();
9271 outerHeight
= this.$clone
.outerHeight();
9273 // Measure max rows height
9275 .attr( 'rows', this.maxRows
)
9276 .css( 'height', 'auto' )
9278 maxInnerHeight
= this.$clone
.innerHeight();
9280 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
9281 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
9282 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
9283 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
9285 this.$clone
.addClass( 'oo-ui-element-hidden' );
9287 // Only apply inline height when expansion beyond natural height is needed
9288 // Use the difference between the inner and outer height as a buffer
9289 newHeight
= idealHeight
> innerHeight
? idealHeight
+ ( outerHeight
- innerHeight
) : '';
9290 if ( newHeight
!== this.styleHeight
) {
9291 this.$input
.css( 'height', newHeight
);
9292 this.styleHeight
= newHeight
;
9293 this.emit( 'resize' );
9296 scrollWidth
= this.$input
[ 0 ].offsetWidth
- this.$input
[ 0 ].clientWidth
;
9297 if ( scrollWidth
!== this.scrollWidth
) {
9298 property
= this.$element
.css( 'direction' ) === 'rtl' ? 'left' : 'right';
9300 this.$label
.css( { right
: '', left
: '' } );
9301 this.$indicator
.css( { right
: '', left
: '' } );
9303 if ( scrollWidth
) {
9304 this.$indicator
.css( property
, scrollWidth
);
9305 if ( this.labelPosition
=== 'after' ) {
9306 this.$label
.css( property
, scrollWidth
);
9310 this.scrollWidth
= scrollWidth
;
9311 this.positionLabel();
9321 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
9322 if ( config
.multiline
) {
9323 return $( '<textarea>' );
9324 } else if ( this.getSaneType( config
) === 'number' ) {
9325 return $( '<input>' )
9326 .attr( 'step', 'any' )
9327 .attr( 'type', 'number' );
9329 return $( '<input>' ).attr( 'type', this.getSaneType( config
) );
9334 * Get sanitized value for 'type' for given config.
9336 * @param {Object} config Configuration options
9337 * @return {string|null}
9340 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
9341 var allowedTypes
= [
9351 return allowedTypes
.indexOf( config
.type
) !== -1 ? config
.type
: 'text';
9355 * Check if the input supports multiple lines.
9359 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
9360 return !!this.multiline
;
9364 * Check if the input automatically adjusts its size.
9368 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
9369 return !!this.autosize
;
9373 * Focus the input and select a specified range within the text.
9375 * @param {number} from Select from offset
9376 * @param {number} [to] Select to offset, defaults to from
9379 OO
.ui
.TextInputWidget
.prototype.selectRange = function ( from, to
) {
9380 var isBackwards
, start
, end
,
9381 input
= this.$input
[ 0 ];
9385 isBackwards
= to
< from;
9386 start
= isBackwards
? to
: from;
9387 end
= isBackwards
? from : to
;
9392 input
.setSelectionRange( start
, end
, isBackwards
? 'backward' : 'forward' );
9394 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
9395 // Rather than expensively check if the input is attached every time, just check
9396 // if it was the cause of an error being thrown. If not, rethrow the error.
9397 if ( this.getElementDocument().body
.contains( input
) ) {
9405 * Get an object describing the current selection range in a directional manner
9407 * @return {Object} Object containing 'from' and 'to' offsets
9409 OO
.ui
.TextInputWidget
.prototype.getRange = function () {
9410 var input
= this.$input
[ 0 ],
9411 start
= input
.selectionStart
,
9412 end
= input
.selectionEnd
,
9413 isBackwards
= input
.selectionDirection
=== 'backward';
9416 from: isBackwards
? end
: start
,
9417 to
: isBackwards
? start
: end
9422 * Get the length of the text input value.
9424 * This could differ from the length of #getValue if the
9425 * value gets filtered
9427 * @return {number} Input length
9429 OO
.ui
.TextInputWidget
.prototype.getInputLength = function () {
9430 return this.$input
[ 0 ].value
.length
;
9434 * Focus the input and select the entire text.
9438 OO
.ui
.TextInputWidget
.prototype.select = function () {
9439 return this.selectRange( 0, this.getInputLength() );
9443 * Focus the input and move the cursor to the start.
9447 OO
.ui
.TextInputWidget
.prototype.moveCursorToStart = function () {
9448 return this.selectRange( 0 );
9452 * Focus the input and move the cursor to the end.
9456 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
9457 return this.selectRange( this.getInputLength() );
9461 * Insert new content into the input.
9463 * @param {string} content Content to be inserted
9466 OO
.ui
.TextInputWidget
.prototype.insertContent = function ( content
) {
9468 range
= this.getRange(),
9469 value
= this.getValue();
9471 start
= Math
.min( range
.from, range
.to
);
9472 end
= Math
.max( range
.from, range
.to
);
9474 this.setValue( value
.slice( 0, start
) + content
+ value
.slice( end
) );
9475 this.selectRange( start
+ content
.length
);
9480 * Insert new content either side of a selection.
9482 * @param {string} pre Content to be inserted before the selection
9483 * @param {string} post Content to be inserted after the selection
9486 OO
.ui
.TextInputWidget
.prototype.encapsulateContent = function ( pre
, post
) {
9488 range
= this.getRange(),
9489 offset
= pre
.length
;
9491 start
= Math
.min( range
.from, range
.to
);
9492 end
= Math
.max( range
.from, range
.to
);
9494 this.selectRange( start
).insertContent( pre
);
9495 this.selectRange( offset
+ end
).insertContent( post
);
9497 this.selectRange( offset
+ start
, offset
+ end
);
9502 * Set the validation pattern.
9504 * The validation pattern is either a regular expression, a function, or the symbolic name of a
9505 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
9506 * value must contain only numbers).
9508 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
9509 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
9511 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
9512 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
9513 this.validate
= validate
;
9515 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
9520 * Sets the 'invalid' flag appropriately.
9522 * @param {boolean} [isValid] Optionally override validation result
9524 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
9526 setFlag = function ( valid
) {
9528 widget
.$input
.attr( 'aria-invalid', 'true' );
9530 widget
.$input
.removeAttr( 'aria-invalid' );
9532 widget
.setFlags( { invalid
: !valid
} );
9535 if ( isValid
!== undefined ) {
9538 this.getValidity().then( function () {
9547 * Get the validity of current value.
9549 * This method returns a promise that resolves if the value is valid and rejects if
9550 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
9552 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
9554 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
9557 function rejectOrResolve( valid
) {
9559 return $.Deferred().resolve().promise();
9561 return $.Deferred().reject().promise();
9565 if ( this.validate
instanceof Function
) {
9566 result
= this.validate( this.getValue() );
9567 if ( result
&& $.isFunction( result
.promise
) ) {
9568 return result
.promise().then( function ( valid
) {
9569 return rejectOrResolve( valid
);
9572 return rejectOrResolve( result
);
9575 return rejectOrResolve( this.getValue().match( this.validate
) );
9580 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
9582 * @param {string} labelPosition Label position, 'before' or 'after'
9585 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
9586 this.labelPosition
= labelPosition
;
9588 // If there is no label and we only change the position, #updatePosition is a no-op,
9589 // but it takes really a lot of work to do nothing.
9590 this.updatePosition();
9596 * Update the position of the inline label.
9598 * This method is called by #setLabelPosition, and can also be called on its own if
9599 * something causes the label to be mispositioned.
9603 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
9604 var after
= this.labelPosition
=== 'after';
9607 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
9608 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
9610 this.valCache
= null;
9611 this.scrollWidth
= null;
9613 this.positionLabel();
9619 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
9620 * already empty or when it's not editable.
9622 OO
.ui
.TextInputWidget
.prototype.updateSearchIndicator = function () {
9623 if ( this.type
=== 'search' ) {
9624 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
9625 this.setIndicator( null );
9627 this.setIndicator( 'clear' );
9633 * Position the label by setting the correct padding on the input.
9638 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
9639 var after
, rtl
, property
;
9641 if ( this.isWaitingToBeAttached
) {
9642 // #onElementAttach will be called soon, which calls this method
9648 // Clear old values if present
9650 'padding-right': '',
9655 this.$element
.append( this.$label
);
9657 this.$label
.detach();
9661 after
= this.labelPosition
=== 'after';
9662 rtl
= this.$element
.css( 'direction' ) === 'rtl';
9663 property
= after
=== rtl
? 'padding-left' : 'padding-right';
9665 this.$input
.css( property
, this.$label
.outerWidth( true ) + ( after
? this.scrollWidth
: 0 ) );
9673 OO
.ui
.TextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
9674 OO
.ui
.TextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
9675 if ( state
.scrollTop
!== undefined ) {
9676 this.$input
.scrollTop( state
.scrollTop
);
9682 * @extends OO.ui.TextInputWidget
9685 * @param {Object} [config] Configuration options
9687 OO
.ui
.SearchInputWidget
= function OoUiSearchInputWidget( config
) {
9688 config
= $.extend( {
9692 // Set type to text so that TextInputWidget doesn't
9693 // get stuck in an infinite loop.
9694 config
.type
= 'text';
9696 // Parent constructor
9697 OO
.ui
.SearchInputWidget
.parent
.call( this, config
);
9700 this.$element
.addClass( 'oo-ui-textInputWidget-type-search' );
9701 this.updateSearchIndicator();
9702 this.connect( this, {
9703 disable
: 'onDisable'
9709 OO
.inheritClass( OO
.ui
.SearchInputWidget
, OO
.ui
.TextInputWidget
);
9717 OO
.ui
.SearchInputWidget
.prototype.getInputElement = function () {
9718 return $( '<input>' ).attr( 'type', 'search' );
9724 OO
.ui
.SearchInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
9725 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
9726 // Clear the text field
9727 this.setValue( '' );
9728 this.$input
[ 0 ].focus();
9734 * Update the 'clear' indicator displayed on type: 'search' text
9735 * fields, hiding it when the field is already empty or when it's not
9738 OO
.ui
.SearchInputWidget
.prototype.updateSearchIndicator = function () {
9739 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
9740 this.setIndicator( null );
9742 this.setIndicator( 'clear' );
9749 OO
.ui
.SearchInputWidget
.prototype.onChange = function () {
9750 OO
.ui
.SearchInputWidget
.parent
.prototype.onChange
.call( this );
9751 this.updateSearchIndicator();
9755 * Handle disable events.
9757 * @param {boolean} disabled Element is disabled
9760 OO
.ui
.SearchInputWidget
.prototype.onDisable = function () {
9761 this.updateSearchIndicator();
9767 OO
.ui
.SearchInputWidget
.prototype.setReadOnly = function ( state
) {
9768 OO
.ui
.SearchInputWidget
.parent
.prototype.setReadOnly
.call( this, state
);
9769 this.updateSearchIndicator();
9774 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
9775 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
9776 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
9778 * - by typing a value in the text input field. If the value exactly matches the value of a menu
9779 * option, that option will appear to be selected.
9780 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
9783 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9785 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
9788 * // Example: A ComboBoxInputWidget.
9789 * var comboBox = new OO.ui.ComboBoxInputWidget( {
9790 * label: 'ComboBoxInputWidget',
9791 * value: 'Option 1',
9794 * new OO.ui.MenuOptionWidget( {
9796 * label: 'Option One'
9798 * new OO.ui.MenuOptionWidget( {
9800 * label: 'Option Two'
9802 * new OO.ui.MenuOptionWidget( {
9804 * label: 'Option Three'
9806 * new OO.ui.MenuOptionWidget( {
9808 * label: 'Option Four'
9810 * new OO.ui.MenuOptionWidget( {
9812 * label: 'Option Five'
9817 * $( 'body' ).append( comboBox.$element );
9819 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
9822 * @extends OO.ui.TextInputWidget
9825 * @param {Object} [config] Configuration options
9826 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9827 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
9828 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
9829 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
9830 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
9832 OO
.ui
.ComboBoxInputWidget
= function OoUiComboBoxInputWidget( config
) {
9833 // Configuration initialization
9834 config
= $.extend( {
9838 // ComboBoxInputWidget shouldn't support multiline
9839 config
.multiline
= false;
9841 // Parent constructor
9842 OO
.ui
.ComboBoxInputWidget
.parent
.call( this, config
);
9845 this.$overlay
= config
.$overlay
|| this.$element
;
9846 this.dropdownButton
= new OO
.ui
.ButtonWidget( {
9847 classes
: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ],
9849 disabled
: this.disabled
9851 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
9855 $container
: this.$element
,
9856 disabled
: this.isDisabled()
9862 this.connect( this, {
9863 change
: 'onInputChange',
9864 enter
: 'onInputEnter'
9866 this.dropdownButton
.connect( this, {
9867 click
: 'onDropdownButtonClick'
9869 this.menu
.connect( this, {
9870 choose
: 'onMenuChoose',
9871 add
: 'onMenuItemsChange',
9872 remove
: 'onMenuItemsChange'
9878 'aria-autocomplete': 'list'
9880 // Do not override options set via config.menu.items
9881 if ( config
.options
!== undefined ) {
9882 this.setOptions( config
.options
);
9884 this.$field
= $( '<div>' )
9885 .addClass( 'oo-ui-comboBoxInputWidget-field' )
9886 .append( this.$input
, this.dropdownButton
.$element
);
9888 .addClass( 'oo-ui-comboBoxInputWidget' )
9889 .append( this.$field
);
9890 this.$overlay
.append( this.menu
.$element
);
9891 this.onMenuItemsChange();
9896 OO
.inheritClass( OO
.ui
.ComboBoxInputWidget
, OO
.ui
.TextInputWidget
);
9901 * Get the combobox's menu.
9903 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
9905 OO
.ui
.ComboBoxInputWidget
.prototype.getMenu = function () {
9910 * Get the combobox's text input widget.
9912 * @return {OO.ui.TextInputWidget} Text input widget
9914 OO
.ui
.ComboBoxInputWidget
.prototype.getInput = function () {
9919 * Handle input change events.
9922 * @param {string} value New value
9924 OO
.ui
.ComboBoxInputWidget
.prototype.onInputChange = function ( value
) {
9925 var match
= this.menu
.getItemFromData( value
);
9927 this.menu
.selectItem( match
);
9928 if ( this.menu
.getHighlightedItem() ) {
9929 this.menu
.highlightItem( match
);
9932 if ( !this.isDisabled() ) {
9933 this.menu
.toggle( true );
9938 * Handle input enter events.
9942 OO
.ui
.ComboBoxInputWidget
.prototype.onInputEnter = function () {
9943 if ( !this.isDisabled() ) {
9944 this.menu
.toggle( false );
9949 * Handle button click events.
9953 OO
.ui
.ComboBoxInputWidget
.prototype.onDropdownButtonClick = function () {
9955 this.$input
[ 0 ].focus();
9959 * Handle menu choose events.
9962 * @param {OO.ui.OptionWidget} item Chosen item
9964 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuChoose = function ( item
) {
9965 this.setValue( item
.getData() );
9969 * Handle menu item change events.
9973 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuItemsChange = function () {
9974 var match
= this.menu
.getItemFromData( this.getValue() );
9975 this.menu
.selectItem( match
);
9976 if ( this.menu
.getHighlightedItem() ) {
9977 this.menu
.highlightItem( match
);
9979 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu
.isEmpty() );
9985 OO
.ui
.ComboBoxInputWidget
.prototype.setDisabled = function ( disabled
) {
9987 OO
.ui
.ComboBoxInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
9989 if ( this.dropdownButton
) {
9990 this.dropdownButton
.setDisabled( this.isDisabled() );
9993 this.menu
.setDisabled( this.isDisabled() );
10000 * Set the options available for this input.
10002 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10005 OO
.ui
.ComboBoxInputWidget
.prototype.setOptions = function ( options
) {
10008 .addItems( options
.map( function ( opt
) {
10009 return new OO
.ui
.MenuOptionWidget( {
10011 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
10019 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
10020 * which is a widget that is specified by reference before any optional configuration settings.
10022 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
10024 * - **left**: The label is placed before the field-widget and aligned with the left margin.
10025 * A left-alignment is used for forms with many fields.
10026 * - **right**: The label is placed before the field-widget and aligned to the right margin.
10027 * A right-alignment is used for long but familiar forms which users tab through,
10028 * verifying the current field with a quick glance at the label.
10029 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
10030 * that users fill out from top to bottom.
10031 * - **inline**: The label is placed after the field-widget and aligned to the left.
10032 * An inline-alignment is best used with checkboxes or radio buttons.
10034 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
10035 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
10037 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
10040 * @extends OO.ui.Layout
10041 * @mixins OO.ui.mixin.LabelElement
10042 * @mixins OO.ui.mixin.TitledElement
10045 * @param {OO.ui.Widget} fieldWidget Field widget
10046 * @param {Object} [config] Configuration options
10047 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
10048 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
10049 * The array may contain strings or OO.ui.HtmlSnippet instances.
10050 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
10051 * The array may contain strings or OO.ui.HtmlSnippet instances.
10052 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
10053 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
10054 * For important messages, you are advised to use `notices`, as they are always shown.
10056 * @throws {Error} An error is thrown if no widget is specified
10058 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
10059 // Allow passing positional parameters inside the config object
10060 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
10061 config
= fieldWidget
;
10062 fieldWidget
= config
.fieldWidget
;
10065 // Make sure we have required constructor arguments
10066 if ( fieldWidget
=== undefined ) {
10067 throw new Error( 'Widget not found' );
10070 // Configuration initialization
10071 config
= $.extend( { align
: 'left' }, config
);
10073 // Parent constructor
10074 OO
.ui
.FieldLayout
.parent
.call( this, config
);
10076 // Mixin constructors
10077 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, {
10078 $label
: $( '<label>' )
10080 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
10083 this.fieldWidget
= fieldWidget
;
10086 this.$field
= $( '<div>' );
10087 this.$messages
= $( '<ul>' );
10088 this.$header
= $( '<div>' );
10089 this.$body
= $( '<div>' );
10091 if ( config
.help
) {
10092 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
10096 classes
: [ 'oo-ui-fieldLayout-help' ],
10100 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
10101 this.popupButtonWidget
.getPopup().$body
.html( config
.help
.toString() );
10103 this.popupButtonWidget
.getPopup().$body
.text( config
.help
);
10105 this.$help
= this.popupButtonWidget
.$element
;
10107 this.$help
= $( [] );
10111 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
10114 if ( fieldWidget
.constructor.static.supportsSimpleLabel
) {
10115 this.$label
.attr( 'for', this.fieldWidget
.getInputId() );
10118 .addClass( 'oo-ui-fieldLayout' )
10119 .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget
.isDisabled() )
10120 .append( this.$body
);
10121 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
10122 this.$header
.addClass( 'oo-ui-fieldLayout-header' );
10123 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
10125 .addClass( 'oo-ui-fieldLayout-field' )
10126 .append( this.fieldWidget
.$element
);
10128 this.setErrors( config
.errors
|| [] );
10129 this.setNotices( config
.notices
|| [] );
10130 this.setAlignment( config
.align
);
10135 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
10136 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
10137 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
10142 * Handle field disable events.
10145 * @param {boolean} value Field is disabled
10147 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
10148 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
10152 * Get the widget contained by the field.
10154 * @return {OO.ui.Widget} Field widget
10156 OO
.ui
.FieldLayout
.prototype.getField = function () {
10157 return this.fieldWidget
;
10162 * @param {string} kind 'error' or 'notice'
10163 * @param {string|OO.ui.HtmlSnippet} text
10166 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
10167 var $listItem
, $icon
, message
;
10168 $listItem
= $( '<li>' );
10169 if ( kind
=== 'error' ) {
10170 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
10171 } else if ( kind
=== 'notice' ) {
10172 $icon
= new OO
.ui
.IconWidget( { icon
: 'info' } ).$element
;
10176 message
= new OO
.ui
.LabelWidget( { label
: text
} );
10178 .append( $icon
, message
.$element
)
10179 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
10184 * Set the field alignment mode.
10187 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
10190 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
10191 if ( value
!== this.align
) {
10192 // Default to 'left'
10193 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
10196 // Reorder elements
10197 if ( value
=== 'top' ) {
10198 this.$header
.append( this.$label
, this.$help
);
10199 this.$body
.append( this.$header
, this.$field
);
10200 } else if ( value
=== 'inline' ) {
10201 this.$header
.append( this.$label
, this.$help
);
10202 this.$body
.append( this.$field
, this.$header
);
10204 this.$header
.append( this.$label
);
10205 this.$body
.append( this.$header
, this.$help
, this.$field
);
10207 // Set classes. The following classes can be used here:
10208 // * oo-ui-fieldLayout-align-left
10209 // * oo-ui-fieldLayout-align-right
10210 // * oo-ui-fieldLayout-align-top
10211 // * oo-ui-fieldLayout-align-inline
10212 if ( this.align
) {
10213 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
10215 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
10216 this.align
= value
;
10223 * Set the list of error messages.
10225 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
10226 * The array may contain strings or OO.ui.HtmlSnippet instances.
10229 OO
.ui
.FieldLayout
.prototype.setErrors = function ( errors
) {
10230 this.errors
= errors
.slice();
10231 this.updateMessages();
10236 * Set the list of notice messages.
10238 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
10239 * The array may contain strings or OO.ui.HtmlSnippet instances.
10242 OO
.ui
.FieldLayout
.prototype.setNotices = function ( notices
) {
10243 this.notices
= notices
.slice();
10244 this.updateMessages();
10249 * Update the rendering of error and notice messages.
10253 OO
.ui
.FieldLayout
.prototype.updateMessages = function () {
10255 this.$messages
.empty();
10257 if ( this.errors
.length
|| this.notices
.length
) {
10258 this.$body
.after( this.$messages
);
10260 this.$messages
.remove();
10264 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
10265 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
10267 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
10268 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
10273 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
10274 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
10275 * is required and is specified before any optional configuration settings.
10277 * Labels can be aligned in one of four ways:
10279 * - **left**: The label is placed before the field-widget and aligned with the left margin.
10280 * A left-alignment is used for forms with many fields.
10281 * - **right**: The label is placed before the field-widget and aligned to the right margin.
10282 * A right-alignment is used for long but familiar forms which users tab through,
10283 * verifying the current field with a quick glance at the label.
10284 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
10285 * that users fill out from top to bottom.
10286 * - **inline**: The label is placed after the field-widget and aligned to the left.
10287 * An inline-alignment is best used with checkboxes or radio buttons.
10289 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
10290 * text is specified.
10293 * // Example of an ActionFieldLayout
10294 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
10295 * new OO.ui.TextInputWidget( {
10296 * placeholder: 'Field widget'
10298 * new OO.ui.ButtonWidget( {
10302 * label: 'An ActionFieldLayout. This label is aligned top',
10304 * help: 'This is help text'
10308 * $( 'body' ).append( actionFieldLayout.$element );
10311 * @extends OO.ui.FieldLayout
10314 * @param {OO.ui.Widget} fieldWidget Field widget
10315 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
10316 * @param {Object} config
10318 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
10319 // Allow passing positional parameters inside the config object
10320 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
10321 config
= fieldWidget
;
10322 fieldWidget
= config
.fieldWidget
;
10323 buttonWidget
= config
.buttonWidget
;
10326 // Parent constructor
10327 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
10330 this.buttonWidget
= buttonWidget
;
10331 this.$button
= $( '<div>' );
10332 this.$input
= $( '<div>' );
10336 .addClass( 'oo-ui-actionFieldLayout' );
10338 .addClass( 'oo-ui-actionFieldLayout-button' )
10339 .append( this.buttonWidget
.$element
);
10341 .addClass( 'oo-ui-actionFieldLayout-input' )
10342 .append( this.fieldWidget
.$element
);
10344 .append( this.$input
, this.$button
);
10349 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
10352 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
10353 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
10354 * configured with a label as well. For more information and examples,
10355 * please see the [OOjs UI documentation on MediaWiki][1].
10358 * // Example of a fieldset layout
10359 * var input1 = new OO.ui.TextInputWidget( {
10360 * placeholder: 'A text input field'
10363 * var input2 = new OO.ui.TextInputWidget( {
10364 * placeholder: 'A text input field'
10367 * var fieldset = new OO.ui.FieldsetLayout( {
10368 * label: 'Example of a fieldset layout'
10371 * fieldset.addItems( [
10372 * new OO.ui.FieldLayout( input1, {
10373 * label: 'Field One'
10375 * new OO.ui.FieldLayout( input2, {
10376 * label: 'Field Two'
10379 * $( 'body' ).append( fieldset.$element );
10381 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
10384 * @extends OO.ui.Layout
10385 * @mixins OO.ui.mixin.IconElement
10386 * @mixins OO.ui.mixin.LabelElement
10387 * @mixins OO.ui.mixin.GroupElement
10390 * @param {Object} [config] Configuration options
10391 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
10392 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
10393 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
10394 * For important messages, you are advised to use `notices`, as they are always shown.
10396 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
10397 // Configuration initialization
10398 config
= config
|| {};
10400 // Parent constructor
10401 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
10403 // Mixin constructors
10404 OO
.ui
.mixin
.IconElement
.call( this, config
);
10405 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: $( '<div>' ) } ) );
10406 OO
.ui
.mixin
.GroupElement
.call( this, config
);
10409 this.$header
= $( '<div>' );
10410 if ( config
.help
) {
10411 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
10415 classes
: [ 'oo-ui-fieldsetLayout-help' ],
10419 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
10420 this.popupButtonWidget
.getPopup().$body
.html( config
.help
.toString() );
10422 this.popupButtonWidget
.getPopup().$body
.text( config
.help
);
10424 this.$help
= this.popupButtonWidget
.$element
;
10426 this.$help
= $( [] );
10431 .addClass( 'oo-ui-fieldsetLayout-header' )
10432 .append( this.$icon
, this.$label
, this.$help
);
10433 this.$group
.addClass( 'oo-ui-fieldsetLayout-group' );
10435 .addClass( 'oo-ui-fieldsetLayout' )
10436 .prepend( this.$header
, this.$group
);
10437 if ( Array
.isArray( config
.items
) ) {
10438 this.addItems( config
.items
);
10444 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
10445 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
10446 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
10447 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
10449 /* Static Properties */
10455 OO
.ui
.FieldsetLayout
.static.tagName
= 'fieldset';
10458 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
10459 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
10460 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
10461 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
10463 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
10464 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
10465 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
10466 * some fancier controls. Some controls have both regular and InputWidget variants, for example
10467 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
10468 * often have simplified APIs to match the capabilities of HTML forms.
10469 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
10471 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
10472 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
10475 * // Example of a form layout that wraps a fieldset layout
10476 * var input1 = new OO.ui.TextInputWidget( {
10477 * placeholder: 'Username'
10479 * var input2 = new OO.ui.TextInputWidget( {
10480 * placeholder: 'Password',
10483 * var submit = new OO.ui.ButtonInputWidget( {
10487 * var fieldset = new OO.ui.FieldsetLayout( {
10488 * label: 'A form layout'
10490 * fieldset.addItems( [
10491 * new OO.ui.FieldLayout( input1, {
10492 * label: 'Username',
10495 * new OO.ui.FieldLayout( input2, {
10496 * label: 'Password',
10499 * new OO.ui.FieldLayout( submit )
10501 * var form = new OO.ui.FormLayout( {
10502 * items: [ fieldset ],
10503 * action: '/api/formhandler',
10506 * $( 'body' ).append( form.$element );
10509 * @extends OO.ui.Layout
10510 * @mixins OO.ui.mixin.GroupElement
10513 * @param {Object} [config] Configuration options
10514 * @cfg {string} [method] HTML form `method` attribute
10515 * @cfg {string} [action] HTML form `action` attribute
10516 * @cfg {string} [enctype] HTML form `enctype` attribute
10517 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
10519 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
10522 // Configuration initialization
10523 config
= config
|| {};
10525 // Parent constructor
10526 OO
.ui
.FormLayout
.parent
.call( this, config
);
10528 // Mixin constructors
10529 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
10532 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
10534 // Make sure the action is safe
10535 action
= config
.action
;
10536 if ( action
!== undefined && !OO
.ui
.isSafeUrl( action
) ) {
10537 action
= './' + action
;
10542 .addClass( 'oo-ui-formLayout' )
10544 method
: config
.method
,
10546 enctype
: config
.enctype
10548 if ( Array
.isArray( config
.items
) ) {
10549 this.addItems( config
.items
);
10555 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
10556 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
10561 * A 'submit' event is emitted when the form is submitted.
10566 /* Static Properties */
10572 OO
.ui
.FormLayout
.static.tagName
= 'form';
10577 * Handle form submit events.
10580 * @param {jQuery.Event} e Submit event
10583 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
10584 if ( this.emit( 'submit' ) ) {
10590 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
10591 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
10594 * // Example of a panel layout
10595 * var panel = new OO.ui.PanelLayout( {
10599 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
10601 * $( 'body' ).append( panel.$element );
10604 * @extends OO.ui.Layout
10607 * @param {Object} [config] Configuration options
10608 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
10609 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10610 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10611 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10613 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
10614 // Configuration initialization
10615 config
= $.extend( {
10622 // Parent constructor
10623 OO
.ui
.PanelLayout
.parent
.call( this, config
);
10626 this.$element
.addClass( 'oo-ui-panelLayout' );
10627 if ( config
.scrollable
) {
10628 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
10630 if ( config
.padded
) {
10631 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
10633 if ( config
.expanded
) {
10634 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
10636 if ( config
.framed
) {
10637 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
10643 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
10648 * Focus the panel layout
10650 * The default implementation just focuses the first focusable element in the panel
10652 OO
.ui
.PanelLayout
.prototype.focus = function () {
10653 OO
.ui
.findFocusable( this.$element
).focus();
10657 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
10658 * items), with small margins between them. Convenient when you need to put a number of block-level
10659 * widgets on a single line next to each other.
10661 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
10664 * // HorizontalLayout with a text input and a label
10665 * var layout = new OO.ui.HorizontalLayout( {
10667 * new OO.ui.LabelWidget( { label: 'Label' } ),
10668 * new OO.ui.TextInputWidget( { value: 'Text' } )
10671 * $( 'body' ).append( layout.$element );
10674 * @extends OO.ui.Layout
10675 * @mixins OO.ui.mixin.GroupElement
10678 * @param {Object} [config] Configuration options
10679 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
10681 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
10682 // Configuration initialization
10683 config
= config
|| {};
10685 // Parent constructor
10686 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
10688 // Mixin constructors
10689 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
10692 this.$element
.addClass( 'oo-ui-horizontalLayout' );
10693 if ( Array
.isArray( config
.items
) ) {
10694 this.addItems( config
.items
);
10700 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
10701 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);