3 * https://www.mediawiki.org/wiki/OOjs_UI
5 * Copyright 2011–2016 OOjs UI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: 2016-04-07T15:12:41Z
16 * Namespace for all classes, static methods and static properties.
48 * Constants for MouseEvent.which
52 OO
.ui
.MouseButtons
= {
64 * Generate a unique ID for element
66 * @return {string} [id]
68 OO
.ui
.generateElementId = function () {
70 return 'oojsui-' + OO
.ui
.elementId
;
74 * Check if an element is focusable.
75 * Inspired from :focusable in jQueryUI v1.11.4 - 2015-04-14
77 * @param {jQuery} $element Element to test
80 OO
.ui
.isFocusableElement = function ( $element
) {
82 element
= $element
[ 0 ];
84 // Anything disabled is not focusable
85 if ( element
.disabled
) {
89 // Check if the element is visible
91 // This is quicker than calling $element.is( ':visible' )
92 $.expr
.filters
.visible( element
) &&
93 // Check that all parents are visible
94 !$element
.parents().addBack().filter( function () {
95 return $.css( this, 'visibility' ) === 'hidden';
101 // Check if the element is ContentEditable, which is the string 'true'
102 if ( element
.contentEditable
=== 'true' ) {
106 // Anything with a non-negative numeric tabIndex is focusable.
107 // Use .prop to avoid browser bugs
108 if ( $element
.prop( 'tabIndex' ) >= 0 ) {
112 // Some element types are naturally focusable
113 // (indexOf is much faster than regex in Chrome and about the
114 // same in FF: https://jsperf.com/regex-vs-indexof-array2)
115 nodeName
= element
.nodeName
.toLowerCase();
116 if ( [ 'input', 'select', 'textarea', 'button', 'object' ].indexOf( nodeName
) !== -1 ) {
120 // Links and areas are focusable if they have an href
121 if ( ( nodeName
=== 'a' || nodeName
=== 'area' ) && $element
.attr( 'href' ) !== undefined ) {
129 * Find a focusable child
131 * @param {jQuery} $container Container to search in
132 * @param {boolean} [backwards] Search backwards
133 * @return {jQuery} Focusable child, an empty jQuery object if none found
135 OO
.ui
.findFocusable = function ( $container
, backwards
) {
136 var $focusable
= $( [] ),
137 // $focusableCandidates is a superset of things that
138 // could get matched by isFocusableElement
139 $focusableCandidates
= $container
140 .find( 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]' );
143 $focusableCandidates
= Array
.prototype.reverse
.call( $focusableCandidates
);
146 $focusableCandidates
.each( function () {
147 var $this = $( this );
148 if ( OO
.ui
.isFocusableElement( $this ) ) {
157 * Get the user's language and any fallback languages.
159 * These language codes are used to localize user interface elements in the user's language.
161 * In environments that provide a localization system, this function should be overridden to
162 * return the user's language(s). The default implementation returns English (en) only.
164 * @return {string[]} Language codes, in descending order of priority
166 OO
.ui
.getUserLanguages = function () {
171 * Get a value in an object keyed by language code.
173 * @param {Object.<string,Mixed>} obj Object keyed by language code
174 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
175 * @param {string} [fallback] Fallback code, used if no matching language can be found
176 * @return {Mixed} Local value
178 OO
.ui
.getLocalValue = function ( obj
, lang
, fallback
) {
181 // Requested language
185 // Known user language
186 langs
= OO
.ui
.getUserLanguages();
187 for ( i
= 0, len
= langs
.length
; i
< len
; i
++ ) {
194 if ( obj
[ fallback
] ) {
195 return obj
[ fallback
];
197 // First existing language
198 for ( lang
in obj
) {
206 * Check if a node is contained within another node
208 * Similar to jQuery#contains except a list of containers can be supplied
209 * and a boolean argument allows you to include the container in the match list
211 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
212 * @param {HTMLElement} contained Node to find
213 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
214 * @return {boolean} The node is in the list of target nodes
216 OO
.ui
.contains = function ( containers
, contained
, matchContainers
) {
218 if ( !Array
.isArray( containers
) ) {
219 containers
= [ containers
];
221 for ( i
= containers
.length
- 1; i
>= 0; i
-- ) {
222 if ( ( matchContainers
&& contained
=== containers
[ i
] ) || $.contains( containers
[ i
], contained
) ) {
230 * Return a function, that, as long as it continues to be invoked, will not
231 * be triggered. The function will be called after it stops being called for
232 * N milliseconds. If `immediate` is passed, trigger the function on the
233 * leading edge, instead of the trailing.
235 * Ported from: http://underscorejs.org/underscore.js
237 * @param {Function} func
238 * @param {number} wait
239 * @param {boolean} immediate
242 OO
.ui
.debounce = function ( func
, wait
, immediate
) {
247 later = function () {
250 func
.apply( context
, args
);
253 if ( immediate
&& !timeout
) {
254 func
.apply( context
, args
);
256 if ( !timeout
|| wait
) {
257 clearTimeout( timeout
);
258 timeout
= setTimeout( later
, wait
);
264 * Returns a function, that, when invoked, will only be triggered at most once
265 * during a given window of time. If called again during that window, it will
266 * wait until the window ends and then trigger itself again.
268 * As it's not knowable to the caller whether the function will actually run
269 * when the wrapper is called, return values from the function are entirely
272 * @param {Function} func
273 * @param {number} wait
276 OO
.ui
.throttle = function ( func
, wait
) {
277 var context
, args
, timeout
,
281 previous
= OO
.ui
.now();
282 func
.apply( context
, args
);
285 // Check how long it's been since the last time the function was
286 // called, and whether it's more or less than the requested throttle
287 // period. If it's less, run the function immediately. If it's more,
288 // set a timeout for the remaining time -- but don't replace an
289 // existing timeout, since that'd indefinitely prolong the wait.
290 var remaining
= wait
- ( OO
.ui
.now() - previous
);
293 if ( remaining
<= 0 ) {
294 // Note: unless wait was ridiculously large, this means we'll
295 // automatically run the first time the function was called in a
296 // given period. (If you provide a wait period larger than the
297 // current Unix timestamp, you *deserve* unexpected behavior.)
298 clearTimeout( timeout
);
300 } else if ( !timeout
) {
301 timeout
= setTimeout( run
, remaining
);
307 * A (possibly faster) way to get the current timestamp as an integer
309 * @return {number} Current timestamp
311 OO
.ui
.now
= Date
.now
|| function () {
312 return new Date().getTime();
316 * Proxy for `node.addEventListener( eventName, handler, true )`.
318 * @param {HTMLElement} node
319 * @param {string} eventName
320 * @param {Function} handler
321 * @deprecated since 0.15.0
323 OO
.ui
.addCaptureEventListener = function ( node
, eventName
, handler
) {
324 node
.addEventListener( eventName
, handler
, true );
328 * Proxy for `node.removeEventListener( eventName, handler, true )`.
330 * @param {HTMLElement} node
331 * @param {string} eventName
332 * @param {Function} handler
333 * @deprecated since 0.15.0
335 OO
.ui
.removeCaptureEventListener = function ( node
, eventName
, handler
) {
336 node
.removeEventListener( eventName
, handler
, true );
340 * Reconstitute a JavaScript object corresponding to a widget created by
341 * the PHP implementation.
343 * This is an alias for `OO.ui.Element.static.infuse()`.
345 * @param {string|HTMLElement|jQuery} idOrNode
346 * A DOM id (if a string) or node for the widget to infuse.
347 * @return {OO.ui.Element}
348 * The `OO.ui.Element` corresponding to this (infusable) document node.
350 OO
.ui
.infuse = function ( idOrNode
) {
351 return OO
.ui
.Element
.static.infuse( idOrNode
);
356 * Message store for the default implementation of OO.ui.msg
358 * Environments that provide a localization system should not use this, but should override
359 * OO.ui.msg altogether.
364 // Tool tip for a button that moves items in a list down one place
365 'ooui-outline-control-move-down': 'Move item down',
366 // Tool tip for a button that moves items in a list up one place
367 'ooui-outline-control-move-up': 'Move item up',
368 // Tool tip for a button that removes items from a list
369 'ooui-outline-control-remove': 'Remove item',
370 // Label for the toolbar group that contains a list of all other available tools
371 'ooui-toolbar-more': 'More',
372 // Label for the fake tool that expands the full list of tools in a toolbar group
373 'ooui-toolgroup-expand': 'More',
374 // Label for the fake tool that collapses the full list of tools in a toolbar group
375 'ooui-toolgroup-collapse': 'Fewer',
376 // Default label for the accept button of a confirmation dialog
377 'ooui-dialog-message-accept': 'OK',
378 // Default label for the reject button of a confirmation dialog
379 'ooui-dialog-message-reject': 'Cancel',
380 // Title for process dialog error description
381 'ooui-dialog-process-error': 'Something went wrong',
382 // Label for process dialog dismiss error button, visible when describing errors
383 'ooui-dialog-process-dismiss': 'Dismiss',
384 // Label for process dialog retry action button, visible when describing only recoverable errors
385 'ooui-dialog-process-retry': 'Try again',
386 // Label for process dialog retry action button, visible when describing only warnings
387 'ooui-dialog-process-continue': 'Continue',
388 // Label for the file selection widget's select file button
389 'ooui-selectfile-button-select': 'Select a file',
390 // Label for the file selection widget if file selection is not supported
391 'ooui-selectfile-not-supported': 'File selection is not supported',
392 // Label for the file selection widget when no file is currently selected
393 'ooui-selectfile-placeholder': 'No file is selected',
394 // Label for the file selection widget's drop target
395 'ooui-selectfile-dragdrop-placeholder': 'Drop file here'
399 * Get a localized message.
401 * In environments that provide a localization system, this function should be overridden to
402 * return the message translated in the user's language. The default implementation always returns
405 * After the message key, message parameters may optionally be passed. In the default implementation,
406 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
407 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
408 * they support unnamed, ordered message parameters.
410 * @param {string} key Message key
411 * @param {...Mixed} [params] Message parameters
412 * @return {string} Translated message with parameters substituted
414 OO
.ui
.msg = function ( key
) {
415 var message
= messages
[ key
],
416 params
= Array
.prototype.slice
.call( arguments
, 1 );
417 if ( typeof message
=== 'string' ) {
418 // Perform $1 substitution
419 message
= message
.replace( /\$(\d+)/g, function ( unused
, n
) {
420 var i
= parseInt( n
, 10 );
421 return params
[ i
- 1 ] !== undefined ? params
[ i
- 1 ] : '$' + n
;
424 // Return placeholder if message not found
425 message
= '[' + key
+ ']';
432 * Package a message and arguments for deferred resolution.
434 * Use this when you are statically specifying a message and the message may not yet be present.
436 * @param {string} key Message key
437 * @param {...Mixed} [params] Message parameters
438 * @return {Function} Function that returns the resolved message when executed
440 OO
.ui
.deferMsg = function () {
441 var args
= arguments
;
443 return OO
.ui
.msg
.apply( OO
.ui
, args
);
450 * If the message is a function it will be executed, otherwise it will pass through directly.
452 * @param {Function|string} msg Deferred message, or message text
453 * @return {string} Resolved message
455 OO
.ui
.resolveMsg = function ( msg
) {
456 if ( $.isFunction( msg
) ) {
463 * @param {string} url
466 OO
.ui
.isSafeUrl = function ( url
) {
467 // Keep this function in sync with php/Tag.php
468 var i
, protocolWhitelist
;
470 function stringStartsWith( haystack
, needle
) {
471 return haystack
.substr( 0, needle
.length
) === needle
;
474 protocolWhitelist
= [
475 'bitcoin', 'ftp', 'ftps', 'geo', 'git', 'gopher', 'http', 'https', 'irc', 'ircs',
476 'magnet', 'mailto', 'mms', 'news', 'nntp', 'redis', 'sftp', 'sip', 'sips', 'sms', 'ssh',
477 'svn', 'tel', 'telnet', 'urn', 'worldwind', 'xmpp'
484 for ( i
= 0; i
< protocolWhitelist
.length
; i
++ ) {
485 if ( stringStartsWith( url
, protocolWhitelist
[ i
] + ':' ) ) {
490 // This matches '//' too
491 if ( stringStartsWith( url
, '/' ) || stringStartsWith( url
, './' ) ) {
494 if ( stringStartsWith( url
, '?' ) || stringStartsWith( url
, '#' ) ) {
506 * Namespace for OOjs UI mixins.
508 * Mixins are named according to the type of object they are intended to
509 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
510 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
511 * is intended to be mixed in to an instance of OO.ui.Widget.
519 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
520 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
521 * connected to them and can't be interacted with.
527 * @param {Object} [config] Configuration options
528 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
529 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
531 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
532 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
533 * @cfg {string} [text] Text to insert
534 * @cfg {Array} [content] An array of content elements to append (after #text).
535 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
536 * Instances of OO.ui.Element will have their $element appended.
537 * @cfg {jQuery} [$content] Content elements to append (after #text).
538 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
539 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
540 * Data can also be specified with the #setData method.
542 OO
.ui
.Element
= function OoUiElement( config
) {
543 // Configuration initialization
544 config
= config
|| {};
549 this.data
= config
.data
;
550 this.$element
= config
.$element
||
551 $( document
.createElement( this.getTagName() ) );
552 this.elementGroup
= null;
553 this.debouncedUpdateThemeClassesHandler
= OO
.ui
.debounce( this.debouncedUpdateThemeClasses
);
556 if ( Array
.isArray( config
.classes
) ) {
557 this.$element
.addClass( config
.classes
.join( ' ' ) );
560 this.$element
.attr( 'id', config
.id
);
563 this.$element
.text( config
.text
);
565 if ( config
.content
) {
566 // The `content` property treats plain strings as text; use an
567 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
568 // appropriate $element appended.
569 this.$element
.append( config
.content
.map( function ( v
) {
570 if ( typeof v
=== 'string' ) {
571 // Escape string so it is properly represented in HTML.
572 return document
.createTextNode( v
);
573 } else if ( v
instanceof OO
.ui
.HtmlSnippet
) {
576 } else if ( v
instanceof OO
.ui
.Element
) {
582 if ( config
.$content
) {
583 // The `$content` property treats plain strings as HTML.
584 this.$element
.append( config
.$content
);
590 OO
.initClass( OO
.ui
.Element
);
592 /* Static Properties */
595 * The name of the HTML tag used by the element.
597 * The static value may be ignored if the #getTagName method is overridden.
603 OO
.ui
.Element
.static.tagName
= 'div';
608 * Reconstitute a JavaScript object corresponding to a widget created
609 * by the PHP implementation.
611 * @param {string|HTMLElement|jQuery} idOrNode
612 * A DOM id (if a string) or node for the widget to infuse.
613 * @return {OO.ui.Element}
614 * The `OO.ui.Element` corresponding to this (infusable) document node.
615 * For `Tag` objects emitted on the HTML side (used occasionally for content)
616 * the value returned is a newly-created Element wrapping around the existing
619 OO
.ui
.Element
.static.infuse = function ( idOrNode
) {
620 var obj
= OO
.ui
.Element
.static.unsafeInfuse( idOrNode
, false );
621 // Verify that the type matches up.
622 // FIXME: uncomment after T89721 is fixed (see T90929)
624 if ( !( obj instanceof this['class'] ) ) {
625 throw new Error( 'Infusion type mismatch!' );
632 * Implementation helper for `infuse`; skips the type check and has an
633 * extra property so that only the top-level invocation touches the DOM.
636 * @param {string|HTMLElement|jQuery} idOrNode
637 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
638 * when the top-level widget of this infusion is inserted into DOM,
639 * replacing the original node; or false for top-level invocation.
640 * @return {OO.ui.Element}
642 OO
.ui
.Element
.static.unsafeInfuse = function ( idOrNode
, domPromise
) {
643 // look for a cached result of a previous infusion.
644 var id
, $elem
, data
, cls
, parts
, parent
, obj
, top
, state
, infusedChildren
;
645 if ( typeof idOrNode
=== 'string' ) {
647 $elem
= $( document
.getElementById( id
) );
649 $elem
= $( idOrNode
);
650 id
= $elem
.attr( 'id' );
652 if ( !$elem
.length
) {
653 throw new Error( 'Widget not found: ' + id
);
655 if ( $elem
[ 0 ].oouiInfused
) {
656 $elem
= $elem
[ 0 ].oouiInfused
;
658 data
= $elem
.data( 'ooui-infused' );
661 if ( data
=== true ) {
662 throw new Error( 'Circular dependency! ' + id
);
665 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
666 state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
667 // restore dynamic state after the new element is re-inserted into DOM under infused parent
668 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
669 infusedChildren
= $elem
.data( 'ooui-infused-children' );
670 if ( infusedChildren
&& infusedChildren
.length
) {
671 infusedChildren
.forEach( function ( data
) {
672 var state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
673 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
679 data
= $elem
.attr( 'data-ooui' );
681 throw new Error( 'No infusion data found: ' + id
);
684 data
= $.parseJSON( data
);
688 if ( !( data
&& data
._
) ) {
689 throw new Error( 'No valid infusion data found: ' + id
);
691 if ( data
._
=== 'Tag' ) {
692 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
693 return new OO
.ui
.Element( { $element
: $elem
} );
695 parts
= data
._
.split( '.' );
696 cls
= OO
.getProp
.apply( OO
, [ window
].concat( parts
) );
697 if ( cls
=== undefined ) {
698 // The PHP output might be old and not including the "OO.ui" prefix
699 // TODO: Remove this back-compat after next major release
700 cls
= OO
.getProp
.apply( OO
, [ OO
.ui
].concat( parts
) );
701 if ( cls
=== undefined ) {
702 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
706 // Verify that we're creating an OO.ui.Element instance
709 while ( parent
!== undefined ) {
710 if ( parent
=== OO
.ui
.Element
) {
715 parent
= parent
.parent
;
718 if ( parent
!== OO
.ui
.Element
) {
719 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
722 if ( domPromise
=== false ) {
724 domPromise
= top
.promise();
726 $elem
.data( 'ooui-infused', true ); // prevent loops
727 data
.id
= id
; // implicit
728 infusedChildren
= [];
729 data
= OO
.copy( data
, null, function deserialize( value
) {
731 if ( OO
.isPlainObject( value
) ) {
733 infused
= OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, domPromise
);
734 infusedChildren
.push( infused
);
735 // Flatten the structure
736 infusedChildren
.push
.apply( infusedChildren
, infused
.$element
.data( 'ooui-infused-children' ) || [] );
737 infused
.$element
.removeData( 'ooui-infused-children' );
740 if ( value
.html
!== undefined ) {
741 return new OO
.ui
.HtmlSnippet( value
.html
);
745 // allow widgets to reuse parts of the DOM
746 data
= cls
.static.reusePreInfuseDOM( $elem
[ 0 ], data
);
747 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
748 state
= cls
.static.gatherPreInfuseState( $elem
[ 0 ], data
);
750 // jscs:disable requireCapitalizedConstructors
751 obj
= new cls( data
);
752 // jscs:enable requireCapitalizedConstructors
753 // now replace old DOM with this new DOM.
755 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
756 // so only mutate the DOM if we need to.
757 if ( $elem
[ 0 ] !== obj
.$element
[ 0 ] ) {
758 $elem
.replaceWith( obj
.$element
);
759 // This element is now gone from the DOM, but if anyone is holding a reference to it,
760 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
761 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
762 $elem
[ 0 ].oouiInfused
= obj
.$element
;
766 obj
.$element
.data( 'ooui-infused', obj
);
767 obj
.$element
.data( 'ooui-infused-children', infusedChildren
);
768 // set the 'data-ooui' attribute so we can identify infused widgets
769 obj
.$element
.attr( 'data-ooui', '' );
770 // restore dynamic state after the new element is inserted into DOM
771 domPromise
.done( obj
.restorePreInfuseState
.bind( obj
, state
) );
776 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
778 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
779 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
780 * constructor, which will be given the enhanced config.
783 * @param {HTMLElement} node
784 * @param {Object} config
787 OO
.ui
.Element
.static.reusePreInfuseDOM = function ( node
, config
) {
792 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of a HTML DOM node
793 * (and its children) that represent an Element of the same class and the given configuration,
794 * generated by the PHP implementation.
796 * This method is called just before `node` is detached from the DOM. The return value of this
797 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
798 * is inserted into DOM to replace `node`.
801 * @param {HTMLElement} node
802 * @param {Object} config
805 OO
.ui
.Element
.static.gatherPreInfuseState = function () {
810 * Get a jQuery function within a specific document.
813 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
814 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
816 * @return {Function} Bound jQuery function
818 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
819 function wrapper( selector
) {
820 return $( selector
, wrapper
.context
);
823 wrapper
.context
= this.getDocument( context
);
826 wrapper
.$iframe
= $iframe
;
833 * Get the document of an element.
836 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
837 * @return {HTMLDocument|null} Document object
839 OO
.ui
.Element
.static.getDocument = function ( obj
) {
840 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
841 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
842 // Empty jQuery selections might have a context
849 ( obj
.nodeType
=== 9 && obj
) ||
854 * Get the window of an element or document.
857 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
858 * @return {Window} Window object
860 OO
.ui
.Element
.static.getWindow = function ( obj
) {
861 var doc
= this.getDocument( obj
);
862 return doc
.defaultView
;
866 * Get the direction of an element or document.
869 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
870 * @return {string} Text direction, either 'ltr' or 'rtl'
872 OO
.ui
.Element
.static.getDir = function ( obj
) {
875 if ( obj
instanceof jQuery
) {
878 isDoc
= obj
.nodeType
=== 9;
879 isWin
= obj
.document
!== undefined;
880 if ( isDoc
|| isWin
) {
886 return $( obj
).css( 'direction' );
890 * Get the offset between two frames.
892 * TODO: Make this function not use recursion.
895 * @param {Window} from Window of the child frame
896 * @param {Window} [to=window] Window of the parent frame
897 * @param {Object} [offset] Offset to start with, used internally
898 * @return {Object} Offset object, containing left and top properties
900 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
901 var i
, len
, frames
, frame
, rect
;
907 offset
= { top
: 0, left
: 0 };
909 if ( from.parent
=== from ) {
913 // Get iframe element
914 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
915 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
916 if ( frames
[ i
].contentWindow
=== from ) {
922 // Recursively accumulate offset values
924 rect
= frame
.getBoundingClientRect();
925 offset
.left
+= rect
.left
;
926 offset
.top
+= rect
.top
;
928 this.getFrameOffset( from.parent
, offset
);
935 * Get the offset between two elements.
937 * The two elements may be in a different frame, but in that case the frame $element is in must
938 * be contained in the frame $anchor is in.
941 * @param {jQuery} $element Element whose position to get
942 * @param {jQuery} $anchor Element to get $element's position relative to
943 * @return {Object} Translated position coordinates, containing top and left properties
945 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
946 var iframe
, iframePos
,
947 pos
= $element
.offset(),
948 anchorPos
= $anchor
.offset(),
949 elementDocument
= this.getDocument( $element
),
950 anchorDocument
= this.getDocument( $anchor
);
952 // If $element isn't in the same document as $anchor, traverse up
953 while ( elementDocument
!== anchorDocument
) {
954 iframe
= elementDocument
.defaultView
.frameElement
;
956 throw new Error( '$element frame is not contained in $anchor frame' );
958 iframePos
= $( iframe
).offset();
959 pos
.left
+= iframePos
.left
;
960 pos
.top
+= iframePos
.top
;
961 elementDocument
= iframe
.ownerDocument
;
963 pos
.left
-= anchorPos
.left
;
964 pos
.top
-= anchorPos
.top
;
969 * Get element border sizes.
972 * @param {HTMLElement} el Element to measure
973 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
975 OO
.ui
.Element
.static.getBorders = function ( el
) {
976 var doc
= el
.ownerDocument
,
977 win
= doc
.defaultView
,
978 style
= win
.getComputedStyle( el
, null ),
980 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
981 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
982 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
983 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
994 * Get dimensions of an element or window.
997 * @param {HTMLElement|Window} el Element to measure
998 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1000 OO
.ui
.Element
.static.getDimensions = function ( el
) {
1002 doc
= el
.ownerDocument
|| el
.document
,
1003 win
= doc
.defaultView
;
1005 if ( win
=== el
|| el
=== doc
.documentElement
) {
1008 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
1010 top
: $win
.scrollTop(),
1011 left
: $win
.scrollLeft()
1013 scrollbar
: { right
: 0, bottom
: 0 },
1017 bottom
: $win
.innerHeight(),
1018 right
: $win
.innerWidth()
1024 borders
: this.getBorders( el
),
1026 top
: $el
.scrollTop(),
1027 left
: $el
.scrollLeft()
1030 right
: $el
.innerWidth() - el
.clientWidth
,
1031 bottom
: $el
.innerHeight() - el
.clientHeight
1033 rect
: el
.getBoundingClientRect()
1039 * Get scrollable object parent
1041 * documentElement can't be used to get or set the scrollTop
1042 * property on Blink. Changing and testing its value lets us
1043 * use 'body' or 'documentElement' based on what is working.
1045 * https://code.google.com/p/chromium/issues/detail?id=303131
1048 * @param {HTMLElement} el Element to find scrollable parent for
1049 * @return {HTMLElement} Scrollable parent
1051 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1052 var scrollTop
, body
;
1054 if ( OO
.ui
.scrollableElement
=== undefined ) {
1055 body
= el
.ownerDocument
.body
;
1056 scrollTop
= body
.scrollTop
;
1059 if ( body
.scrollTop
=== 1 ) {
1060 body
.scrollTop
= scrollTop
;
1061 OO
.ui
.scrollableElement
= 'body';
1063 OO
.ui
.scrollableElement
= 'documentElement';
1067 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1071 * Get closest scrollable container.
1073 * Traverses up until either a scrollable element or the root is reached, in which case the window
1077 * @param {HTMLElement} el Element to find scrollable container for
1078 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1079 * @return {HTMLElement} Closest scrollable container
1081 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1083 // props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
1084 props
= [ 'overflow-x', 'overflow-y' ],
1085 $parent
= $( el
).parent();
1087 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1088 props
= [ 'overflow-' + dimension
];
1091 while ( $parent
.length
) {
1092 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1093 return $parent
[ 0 ];
1097 val
= $parent
.css( props
[ i
] );
1098 if ( val
=== 'auto' || val
=== 'scroll' ) {
1099 return $parent
[ 0 ];
1102 $parent
= $parent
.parent();
1104 return this.getDocument( el
).body
;
1108 * Scroll element into view.
1111 * @param {HTMLElement} el Element to scroll into view
1112 * @param {Object} [config] Configuration options
1113 * @param {string} [config.duration='fast'] jQuery animation duration value
1114 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1115 * to scroll in both directions
1116 * @param {Function} [config.complete] Function to call when scrolling completes.
1117 * Deprecated since 0.15.4, use the return promise instead.
1118 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1120 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1121 var position
, animations
, callback
, container
, $container
, elementDimensions
, containerDimensions
, $window
,
1122 deferred
= $.Deferred();
1124 // Configuration initialization
1125 config
= config
|| {};
1128 callback
= typeof config
.complete
=== 'function' && config
.complete
;
1129 container
= this.getClosestScrollableContainer( el
, config
.direction
);
1130 $container
= $( container
);
1131 elementDimensions
= this.getDimensions( el
);
1132 containerDimensions
= this.getDimensions( container
);
1133 $window
= $( this.getWindow( el
) );
1135 // Compute the element's position relative to the container
1136 if ( $container
.is( 'html, body' ) ) {
1137 // If the scrollable container is the root, this is easy
1139 top
: elementDimensions
.rect
.top
,
1140 bottom
: $window
.innerHeight() - elementDimensions
.rect
.bottom
,
1141 left
: elementDimensions
.rect
.left
,
1142 right
: $window
.innerWidth() - elementDimensions
.rect
.right
1145 // Otherwise, we have to subtract el's coordinates from container's coordinates
1147 top
: elementDimensions
.rect
.top
- ( containerDimensions
.rect
.top
+ containerDimensions
.borders
.top
),
1148 bottom
: containerDimensions
.rect
.bottom
- containerDimensions
.borders
.bottom
- containerDimensions
.scrollbar
.bottom
- elementDimensions
.rect
.bottom
,
1149 left
: elementDimensions
.rect
.left
- ( containerDimensions
.rect
.left
+ containerDimensions
.borders
.left
),
1150 right
: containerDimensions
.rect
.right
- containerDimensions
.borders
.right
- containerDimensions
.scrollbar
.right
- elementDimensions
.rect
.right
1154 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1155 if ( position
.top
< 0 ) {
1156 animations
.scrollTop
= containerDimensions
.scroll
.top
+ position
.top
;
1157 } else if ( position
.top
> 0 && position
.bottom
< 0 ) {
1158 animations
.scrollTop
= containerDimensions
.scroll
.top
+ Math
.min( position
.top
, -position
.bottom
);
1161 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1162 if ( position
.left
< 0 ) {
1163 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ position
.left
;
1164 } else if ( position
.left
> 0 && position
.right
< 0 ) {
1165 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ Math
.min( position
.left
, -position
.right
);
1168 if ( !$.isEmptyObject( animations
) ) {
1169 $container
.stop( true ).animate( animations
, config
.duration
=== undefined ? 'fast' : config
.duration
);
1170 $container
.queue( function ( next
) {
1183 return deferred
.promise();
1187 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1188 * and reserve space for them, because it probably doesn't.
1190 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1191 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1192 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1193 * and then reattach (or show) them back.
1196 * @param {HTMLElement} el Element to reconsider the scrollbars on
1198 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1199 var i
, len
, scrollLeft
, scrollTop
, nodes
= [];
1200 // Save scroll position
1201 scrollLeft
= el
.scrollLeft
;
1202 scrollTop
= el
.scrollTop
;
1203 // Detach all children
1204 while ( el
.firstChild
) {
1205 nodes
.push( el
.firstChild
);
1206 el
.removeChild( el
.firstChild
);
1209 void el
.offsetHeight
;
1210 // Reattach all children
1211 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1212 el
.appendChild( nodes
[ i
] );
1214 // Restore scroll position (no-op if scrollbars disappeared)
1215 el
.scrollLeft
= scrollLeft
;
1216 el
.scrollTop
= scrollTop
;
1222 * Toggle visibility of an element.
1224 * @param {boolean} [show] Make element visible, omit to toggle visibility
1228 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1229 show
= show
=== undefined ? !this.visible
: !!show
;
1231 if ( show
!== this.isVisible() ) {
1232 this.visible
= show
;
1233 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1234 this.emit( 'toggle', show
);
1241 * Check if element is visible.
1243 * @return {boolean} element is visible
1245 OO
.ui
.Element
.prototype.isVisible = function () {
1246 return this.visible
;
1252 * @return {Mixed} Element data
1254 OO
.ui
.Element
.prototype.getData = function () {
1261 * @param {Mixed} data Element data
1264 OO
.ui
.Element
.prototype.setData = function ( data
) {
1270 * Check if element supports one or more methods.
1272 * @param {string|string[]} methods Method or list of methods to check
1273 * @return {boolean} All methods are supported
1275 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1279 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1280 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1281 if ( $.isFunction( this[ methods
[ i
] ] ) ) {
1286 return methods
.length
=== support
;
1290 * Update the theme-provided classes.
1292 * @localdoc This is called in element mixins and widget classes any time state changes.
1293 * Updating is debounced, minimizing overhead of changing multiple attributes and
1294 * guaranteeing that theme updates do not occur within an element's constructor
1296 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1297 this.debouncedUpdateThemeClassesHandler();
1302 * @localdoc This method is called directly from the QUnit tests instead of #updateThemeClasses, to
1303 * make them synchronous.
1305 OO
.ui
.Element
.prototype.debouncedUpdateThemeClasses = function () {
1306 OO
.ui
.theme
.updateElementClasses( this );
1310 * Get the HTML tag name.
1312 * Override this method to base the result on instance information.
1314 * @return {string} HTML tag name
1316 OO
.ui
.Element
.prototype.getTagName = function () {
1317 return this.constructor.static.tagName
;
1321 * Check if the element is attached to the DOM
1323 * @return {boolean} The element is attached to the DOM
1325 OO
.ui
.Element
.prototype.isElementAttached = function () {
1326 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1330 * Get the DOM document.
1332 * @return {HTMLDocument} Document object
1334 OO
.ui
.Element
.prototype.getElementDocument = function () {
1335 // Don't cache this in other ways either because subclasses could can change this.$element
1336 return OO
.ui
.Element
.static.getDocument( this.$element
);
1340 * Get the DOM window.
1342 * @return {Window} Window object
1344 OO
.ui
.Element
.prototype.getElementWindow = function () {
1345 return OO
.ui
.Element
.static.getWindow( this.$element
);
1349 * Get closest scrollable container.
1351 * @return {HTMLElement} Closest scrollable container
1353 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1354 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1358 * Get group element is in.
1360 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1362 OO
.ui
.Element
.prototype.getElementGroup = function () {
1363 return this.elementGroup
;
1367 * Set group element is in.
1369 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1372 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1373 this.elementGroup
= group
;
1378 * Scroll element into view.
1380 * @param {Object} [config] Configuration options
1381 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1383 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1384 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1388 * Restore the pre-infusion dynamic state for this widget.
1390 * This method is called after #$element has been inserted into DOM. The parameter is the return
1391 * value of #gatherPreInfuseState.
1394 * @param {Object} state
1396 OO
.ui
.Element
.prototype.restorePreInfuseState = function () {
1400 * Wraps an HTML snippet for use with configuration values which default
1401 * to strings. This bypasses the default html-escaping done to string
1407 * @param {string} [content] HTML content
1409 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
1411 this.content
= content
;
1416 OO
.initClass( OO
.ui
.HtmlSnippet
);
1423 * @return {string} Unchanged HTML snippet.
1425 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
1426 return this.content
;
1430 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1431 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1432 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1433 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1434 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1438 * @extends OO.ui.Element
1439 * @mixins OO.EventEmitter
1442 * @param {Object} [config] Configuration options
1444 OO
.ui
.Layout
= function OoUiLayout( config
) {
1445 // Configuration initialization
1446 config
= config
|| {};
1448 // Parent constructor
1449 OO
.ui
.Layout
.parent
.call( this, config
);
1451 // Mixin constructors
1452 OO
.EventEmitter
.call( this );
1455 this.$element
.addClass( 'oo-ui-layout' );
1460 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1461 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1464 * Widgets are compositions of one or more OOjs UI elements that users can both view
1465 * and interact with. All widgets can be configured and modified via a standard API,
1466 * and their state can change dynamically according to a model.
1470 * @extends OO.ui.Element
1471 * @mixins OO.EventEmitter
1474 * @param {Object} [config] Configuration options
1475 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1476 * appearance reflects this state.
1478 OO
.ui
.Widget
= function OoUiWidget( config
) {
1479 // Initialize config
1480 config
= $.extend( { disabled
: false }, config
);
1482 // Parent constructor
1483 OO
.ui
.Widget
.parent
.call( this, config
);
1485 // Mixin constructors
1486 OO
.EventEmitter
.call( this );
1489 this.disabled
= null;
1490 this.wasDisabled
= null;
1493 this.$element
.addClass( 'oo-ui-widget' );
1494 this.setDisabled( !!config
.disabled
);
1499 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1500 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1502 /* Static Properties */
1505 * Whether this widget will behave reasonably when wrapped in a HTML `<label>`. If this is true,
1506 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
1511 * @property {boolean}
1513 OO
.ui
.Widget
.static.supportsSimpleLabel
= false;
1520 * A 'disable' event is emitted when the disabled state of the widget changes
1521 * (i.e. on disable **and** enable).
1523 * @param {boolean} disabled Widget is disabled
1529 * A 'toggle' event is emitted when the visibility of the widget changes.
1531 * @param {boolean} visible Widget is visible
1537 * Check if the widget is disabled.
1539 * @return {boolean} Widget is disabled
1541 OO
.ui
.Widget
.prototype.isDisabled = function () {
1542 return this.disabled
;
1546 * Set the 'disabled' state of the widget.
1548 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1550 * @param {boolean} disabled Disable widget
1553 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
1556 this.disabled
= !!disabled
;
1557 isDisabled
= this.isDisabled();
1558 if ( isDisabled
!== this.wasDisabled
) {
1559 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
1560 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
1561 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
1562 this.emit( 'disable', isDisabled
);
1563 this.updateThemeClasses();
1565 this.wasDisabled
= isDisabled
;
1571 * Update the disabled state, in case of changes in parent widget.
1575 OO
.ui
.Widget
.prototype.updateDisabled = function () {
1576 this.setDisabled( this.disabled
);
1587 * @param {Object} [config] Configuration options
1589 OO
.ui
.Theme
= function OoUiTheme( config
) {
1590 // Configuration initialization
1591 config
= config
|| {};
1596 OO
.initClass( OO
.ui
.Theme
);
1601 * Get a list of classes to be applied to a widget.
1603 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
1604 * otherwise state transitions will not work properly.
1606 * @param {OO.ui.Element} element Element for which to get classes
1607 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1609 OO
.ui
.Theme
.prototype.getElementClasses = function () {
1610 return { on
: [], off
: [] };
1614 * Update CSS classes provided by the theme.
1616 * For elements with theme logic hooks, this should be called any time there's a state change.
1618 * @param {OO.ui.Element} element Element for which to update classes
1619 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1621 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
1622 var $elements
= $( [] ),
1623 classes
= this.getElementClasses( element
);
1625 if ( element
.$icon
) {
1626 $elements
= $elements
.add( element
.$icon
);
1628 if ( element
.$indicator
) {
1629 $elements
= $elements
.add( element
.$indicator
);
1633 .removeClass( classes
.off
.join( ' ' ) )
1634 .addClass( classes
.on
.join( ' ' ) );
1638 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
1639 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
1640 * order in which users will navigate through the focusable elements via the "tab" key.
1643 * // TabIndexedElement is mixed into the ButtonWidget class
1644 * // to provide a tabIndex property.
1645 * var button1 = new OO.ui.ButtonWidget( {
1649 * var button2 = new OO.ui.ButtonWidget( {
1653 * var button3 = new OO.ui.ButtonWidget( {
1657 * var button4 = new OO.ui.ButtonWidget( {
1661 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
1667 * @param {Object} [config] Configuration options
1668 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
1669 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
1670 * functionality will be applied to it instead.
1671 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
1672 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
1673 * to remove the element from the tab-navigation flow.
1675 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
1676 // Configuration initialization
1677 config
= $.extend( { tabIndex
: 0 }, config
);
1680 this.$tabIndexed
= null;
1681 this.tabIndex
= null;
1684 this.connect( this, { disable
: 'onTabIndexedElementDisable' } );
1687 this.setTabIndex( config
.tabIndex
);
1688 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
1693 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
1698 * Set the element that should use the tabindex functionality.
1700 * This method is used to retarget a tabindex mixin so that its functionality applies
1701 * to the specified element. If an element is currently using the functionality, the mixin’s
1702 * effect on that element is removed before the new element is set up.
1704 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
1707 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
1708 var tabIndex
= this.tabIndex
;
1709 // Remove attributes from old $tabIndexed
1710 this.setTabIndex( null );
1711 // Force update of new $tabIndexed
1712 this.$tabIndexed
= $tabIndexed
;
1713 this.tabIndex
= tabIndex
;
1714 return this.updateTabIndex();
1718 * Set the value of the tabindex.
1720 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
1723 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
1724 tabIndex
= typeof tabIndex
=== 'number' ? tabIndex
: null;
1726 if ( this.tabIndex
!== tabIndex
) {
1727 this.tabIndex
= tabIndex
;
1728 this.updateTabIndex();
1735 * Update the `tabindex` attribute, in case of changes to tab index or
1741 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
1742 if ( this.$tabIndexed
) {
1743 if ( this.tabIndex
!== null ) {
1744 // Do not index over disabled elements
1745 this.$tabIndexed
.attr( {
1746 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
1747 // Support: ChromeVox and NVDA
1748 // These do not seem to inherit aria-disabled from parent elements
1749 'aria-disabled': this.isDisabled().toString()
1752 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
1759 * Handle disable events.
1762 * @param {boolean} disabled Element is disabled
1764 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
1765 this.updateTabIndex();
1769 * Get the value of the tabindex.
1771 * @return {number|null} Tabindex value
1773 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
1774 return this.tabIndex
;
1778 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
1779 * interface element that can be configured with access keys for accessibility.
1780 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
1782 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
1788 * @param {Object} [config] Configuration options
1789 * @cfg {jQuery} [$button] The button element created by the class.
1790 * If this configuration is omitted, the button element will use a generated `<a>`.
1791 * @cfg {boolean} [framed=true] Render the button with a frame
1793 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
1794 // Configuration initialization
1795 config
= config
|| {};
1798 this.$button
= null;
1800 this.active
= false;
1801 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
1802 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
1803 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
1804 this.onKeyUpHandler
= this.onKeyUp
.bind( this );
1805 this.onClickHandler
= this.onClick
.bind( this );
1806 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
1809 this.$element
.addClass( 'oo-ui-buttonElement' );
1810 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
1811 this.setButtonElement( config
.$button
|| $( '<a>' ) );
1816 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
1818 /* Static Properties */
1821 * Cancel mouse down events.
1823 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
1824 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
1825 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
1830 * @property {boolean}
1832 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
1837 * A 'click' event is emitted when the button element is clicked.
1845 * Set the button element.
1847 * This method is used to retarget a button mixin so that its functionality applies to
1848 * the specified button element instead of the one created by the class. If a button element
1849 * is already set, the method will remove the mixin’s effect on that element.
1851 * @param {jQuery} $button Element to use as button
1853 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
1854 if ( this.$button
) {
1856 .removeClass( 'oo-ui-buttonElement-button' )
1857 .removeAttr( 'role accesskey' )
1859 mousedown
: this.onMouseDownHandler
,
1860 keydown
: this.onKeyDownHandler
,
1861 click
: this.onClickHandler
,
1862 keypress
: this.onKeyPressHandler
1866 this.$button
= $button
1867 .addClass( 'oo-ui-buttonElement-button' )
1868 .attr( { role
: 'button' } )
1870 mousedown
: this.onMouseDownHandler
,
1871 keydown
: this.onKeyDownHandler
,
1872 click
: this.onClickHandler
,
1873 keypress
: this.onKeyPressHandler
1878 * Handles mouse down events.
1881 * @param {jQuery.Event} e Mouse down event
1883 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
1884 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
1887 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
1888 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
1889 // reliably remove the pressed class
1890 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
1891 // Prevent change of focus unless specifically configured otherwise
1892 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
1898 * Handles mouse up events.
1901 * @param {MouseEvent} e Mouse up event
1903 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp = function ( e
) {
1904 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
1907 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
1908 // Stop listening for mouseup, since we only needed this once
1909 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
1913 * Handles mouse click events.
1916 * @param {jQuery.Event} e Mouse click event
1919 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
1920 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
1921 if ( this.emit( 'click' ) ) {
1928 * Handles key down events.
1931 * @param {jQuery.Event} e Key down event
1933 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
1934 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
1937 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
1938 // Run the keyup handler no matter where the key is when the button is let go, so we can
1939 // reliably remove the pressed class
1940 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler
, true );
1944 * Handles key up events.
1947 * @param {KeyboardEvent} e Key up event
1949 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyUp = function ( e
) {
1950 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
1953 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
1954 // Stop listening for keyup, since we only needed this once
1955 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler
, true );
1959 * Handles key press events.
1962 * @param {jQuery.Event} e Key press event
1965 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
1966 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
1967 if ( this.emit( 'click' ) ) {
1974 * Check if button has a frame.
1976 * @return {boolean} Button is framed
1978 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
1983 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
1985 * @param {boolean} [framed] Make button framed, omit to toggle
1988 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
1989 framed
= framed
=== undefined ? !this.framed
: !!framed
;
1990 if ( framed
!== this.framed
) {
1991 this.framed
= framed
;
1993 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
1994 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
1995 this.updateThemeClasses();
2002 * Set the button's active state.
2004 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
2005 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
2006 * for other button types.
2008 * @param {boolean} value Make button active
2011 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
2012 this.active
= !!value
;
2013 this.$element
.toggleClass( 'oo-ui-buttonElement-active', this.active
);
2018 * Check if the button is active
2020 * @return {boolean} The button is active
2022 OO
.ui
.mixin
.ButtonElement
.prototype.isActive = function () {
2027 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
2028 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
2029 * items from the group is done through the interface the class provides.
2030 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2032 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
2038 * @param {Object} [config] Configuration options
2039 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
2040 * is omitted, the group element will use a generated `<div>`.
2042 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
2043 // Configuration initialization
2044 config
= config
|| {};
2049 this.aggregateItemEvents
= {};
2052 this.setGroupElement( config
.$group
|| $( '<div>' ) );
2060 * A change event is emitted when the set of selected items changes.
2062 * @param {OO.ui.Element[]} items Items currently in the group
2068 * Set the group element.
2070 * If an element is already set, items will be moved to the new element.
2072 * @param {jQuery} $group Element to use as group
2074 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
2077 this.$group
= $group
;
2078 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2079 this.$group
.append( this.items
[ i
].$element
);
2084 * Check if a group contains no items.
2086 * @return {boolean} Group is empty
2088 OO
.ui
.mixin
.GroupElement
.prototype.isEmpty = function () {
2089 return !this.items
.length
;
2093 * Get all items in the group.
2095 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
2096 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
2099 * @return {OO.ui.Element[]} An array of items.
2101 OO
.ui
.mixin
.GroupElement
.prototype.getItems = function () {
2102 return this.items
.slice( 0 );
2106 * Get an item by its data.
2108 * Only the first item with matching data will be returned. To return all matching items,
2109 * use the #getItemsFromData method.
2111 * @param {Object} data Item data to search for
2112 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2114 OO
.ui
.mixin
.GroupElement
.prototype.getItemFromData = function ( data
) {
2116 hash
= OO
.getHash( data
);
2118 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2119 item
= this.items
[ i
];
2120 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2129 * Get items by their data.
2131 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
2133 * @param {Object} data Item data to search for
2134 * @return {OO.ui.Element[]} Items with equivalent data
2136 OO
.ui
.mixin
.GroupElement
.prototype.getItemsFromData = function ( data
) {
2138 hash
= OO
.getHash( data
),
2141 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2142 item
= this.items
[ i
];
2143 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2152 * Aggregate the events emitted by the group.
2154 * When events are aggregated, the group will listen to all contained items for the event,
2155 * and then emit the event under a new name. The new event will contain an additional leading
2156 * parameter containing the item that emitted the original event. Other arguments emitted from
2157 * the original event are passed through.
2159 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
2160 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
2161 * A `null` value will remove aggregated events.
2163 * @throws {Error} An error is thrown if aggregation already exists.
2165 OO
.ui
.mixin
.GroupElement
.prototype.aggregate = function ( events
) {
2166 var i
, len
, item
, add
, remove
, itemEvent
, groupEvent
;
2168 for ( itemEvent
in events
) {
2169 groupEvent
= events
[ itemEvent
];
2171 // Remove existing aggregated event
2172 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
2173 // Don't allow duplicate aggregations
2175 throw new Error( 'Duplicate item event aggregation for ' + itemEvent
);
2177 // Remove event aggregation from existing items
2178 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2179 item
= this.items
[ i
];
2180 if ( item
.connect
&& item
.disconnect
) {
2182 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
2183 item
.disconnect( this, remove
);
2186 // Prevent future items from aggregating event
2187 delete this.aggregateItemEvents
[ itemEvent
];
2190 // Add new aggregate event
2192 // Make future items aggregate event
2193 this.aggregateItemEvents
[ itemEvent
] = groupEvent
;
2194 // Add event aggregation to existing items
2195 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2196 item
= this.items
[ i
];
2197 if ( item
.connect
&& item
.disconnect
) {
2199 add
[ itemEvent
] = [ 'emit', groupEvent
, item
];
2200 item
.connect( this, add
);
2208 * Add items to the group.
2210 * Items will be added to the end of the group array unless the optional `index` parameter specifies
2211 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
2213 * @param {OO.ui.Element[]} items An array of items to add to the group
2214 * @param {number} [index] Index of the insertion point
2217 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
2218 var i
, len
, item
, event
, events
, currentIndex
,
2221 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
2224 // Check if item exists then remove it first, effectively "moving" it
2225 currentIndex
= this.items
.indexOf( item
);
2226 if ( currentIndex
>= 0 ) {
2227 this.removeItems( [ item
] );
2228 // Adjust index to compensate for removal
2229 if ( currentIndex
< index
) {
2234 if ( item
.connect
&& item
.disconnect
&& !$.isEmptyObject( this.aggregateItemEvents
) ) {
2236 for ( event
in this.aggregateItemEvents
) {
2237 events
[ event
] = [ 'emit', this.aggregateItemEvents
[ event
], item
];
2239 item
.connect( this, events
);
2241 item
.setElementGroup( this );
2242 itemElements
.push( item
.$element
.get( 0 ) );
2245 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
2246 this.$group
.append( itemElements
);
2247 this.items
.push
.apply( this.items
, items
);
2248 } else if ( index
=== 0 ) {
2249 this.$group
.prepend( itemElements
);
2250 this.items
.unshift
.apply( this.items
, items
);
2252 this.items
[ index
].$element
.before( itemElements
);
2253 this.items
.splice
.apply( this.items
, [ index
, 0 ].concat( items
) );
2256 this.emit( 'change', this.getItems() );
2261 * Remove the specified items from a group.
2263 * Removed items are detached (not removed) from the DOM so that they may be reused.
2264 * To remove all items from a group, you may wish to use the #clearItems method instead.
2266 * @param {OO.ui.Element[]} items An array of items to remove
2269 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
2270 var i
, len
, item
, index
, remove
, itemEvent
;
2272 // Remove specific items
2273 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
2275 index
= this.items
.indexOf( item
);
2276 if ( index
!== -1 ) {
2278 item
.connect
&& item
.disconnect
&&
2279 !$.isEmptyObject( this.aggregateItemEvents
)
2282 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
2283 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
2285 item
.disconnect( this, remove
);
2287 item
.setElementGroup( null );
2288 this.items
.splice( index
, 1 );
2289 item
.$element
.detach();
2293 this.emit( 'change', this.getItems() );
2298 * Clear all items from the group.
2300 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2301 * To remove only a subset of items from a group, use the #removeItems method.
2305 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
2306 var i
, len
, item
, remove
, itemEvent
;
2309 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2310 item
= this.items
[ i
];
2312 item
.connect
&& item
.disconnect
&&
2313 !$.isEmptyObject( this.aggregateItemEvents
)
2316 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
2317 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
2319 item
.disconnect( this, remove
);
2321 item
.setElementGroup( null );
2322 item
.$element
.detach();
2325 this.emit( 'change', this.getItems() );
2331 * IconElement is often mixed into other classes to generate an icon.
2332 * Icons are graphics, about the size of normal text. They are used to aid the user
2333 * in locating a control or to convey information in a space-efficient way. See the
2334 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
2335 * included in the library.
2337 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2343 * @param {Object} [config] Configuration options
2344 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2345 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2346 * the icon element be set to an existing icon instead of the one generated by this class, set a
2347 * value using a jQuery selection. For example:
2349 * // Use a <div> tag instead of a <span>
2351 * // Use an existing icon element instead of the one generated by the class
2352 * $icon: this.$element
2353 * // Use an icon element from a child widget
2354 * $icon: this.childwidget.$element
2355 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
2356 * symbolic names. A map is used for i18n purposes and contains a `default` icon
2357 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
2358 * by the user's language.
2360 * Example of an i18n map:
2362 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2363 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
2364 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2365 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
2366 * text. The icon title is displayed when users move the mouse over the icon.
2368 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
2369 // Configuration initialization
2370 config
= config
|| {};
2375 this.iconTitle
= null;
2378 this.setIcon( config
.icon
|| this.constructor.static.icon
);
2379 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
2380 this.setIconElement( config
.$icon
|| $( '<span>' ) );
2385 OO
.initClass( OO
.ui
.mixin
.IconElement
);
2387 /* Static Properties */
2390 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
2391 * for i18n purposes and contains a `default` icon name and additional names keyed by
2392 * language code. The `default` name is used when no icon is keyed by the user's language.
2394 * Example of an i18n map:
2396 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2398 * Note: the static property will be overridden if the #icon configuration is used.
2402 * @property {Object|string}
2404 OO
.ui
.mixin
.IconElement
.static.icon
= null;
2407 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2408 * function that returns title text, or `null` for no title.
2410 * The static property will be overridden if the #iconTitle configuration is used.
2414 * @property {string|Function|null}
2416 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
2421 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2422 * applies to the specified icon element instead of the one created by the class. If an icon
2423 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2424 * and mixin methods will no longer affect the element.
2426 * @param {jQuery} $icon Element to use as icon
2428 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
2431 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
2432 .removeAttr( 'title' );
2436 .addClass( 'oo-ui-iconElement-icon' )
2437 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
2438 if ( this.iconTitle
!== null ) {
2439 this.$icon
.attr( 'title', this.iconTitle
);
2442 this.updateThemeClasses();
2446 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
2447 * The icon parameter can also be set to a map of icon names. See the #icon config setting
2450 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
2451 * by language code, or `null` to remove the icon.
2454 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
2455 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
2456 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
2458 if ( this.icon
!== icon
) {
2460 if ( this.icon
!== null ) {
2461 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
2463 if ( icon
!== null ) {
2464 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
2470 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
2471 this.updateThemeClasses();
2477 * Set the icon title. Use `null` to remove the title.
2479 * @param {string|Function|null} iconTitle A text string used as the icon title,
2480 * a function that returns title text, or `null` for no title.
2483 OO
.ui
.mixin
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
2484 iconTitle
= typeof iconTitle
=== 'function' ||
2485 ( typeof iconTitle
=== 'string' && iconTitle
.length
) ?
2486 OO
.ui
.resolveMsg( iconTitle
) : null;
2488 if ( this.iconTitle
!== iconTitle
) {
2489 this.iconTitle
= iconTitle
;
2491 if ( this.iconTitle
!== null ) {
2492 this.$icon
.attr( 'title', iconTitle
);
2494 this.$icon
.removeAttr( 'title' );
2503 * Get the symbolic name of the icon.
2505 * @return {string} Icon name
2507 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
2512 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
2514 * @return {string} Icon title text
2516 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
2517 return this.iconTitle
;
2521 * IndicatorElement is often mixed into other classes to generate an indicator.
2522 * Indicators are small graphics that are generally used in two ways:
2524 * - To draw attention to the status of an item. For example, an indicator might be
2525 * used to show that an item in a list has errors that need to be resolved.
2526 * - To clarify the function of a control that acts in an exceptional way (a button
2527 * that opens a menu instead of performing an action directly, for example).
2529 * For a list of indicators included in the library, please see the
2530 * [OOjs UI documentation on MediaWiki] [1].
2532 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2538 * @param {Object} [config] Configuration options
2539 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
2540 * configuration is omitted, the indicator element will use a generated `<span>`.
2541 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2542 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
2544 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2545 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
2546 * or a function that returns title text. The indicator title is displayed when users move
2547 * the mouse over the indicator.
2549 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
2550 // Configuration initialization
2551 config
= config
|| {};
2554 this.$indicator
= null;
2555 this.indicator
= null;
2556 this.indicatorTitle
= null;
2559 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
2560 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
2561 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
2566 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
2568 /* Static Properties */
2571 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2572 * The static property will be overridden if the #indicator configuration is used.
2576 * @property {string|null}
2578 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
2581 * A text string used as the indicator title, a function that returns title text, or `null`
2582 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
2586 * @property {string|Function|null}
2588 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
2593 * Set the indicator element.
2595 * If an element is already set, it will be cleaned up before setting up the new element.
2597 * @param {jQuery} $indicator Element to use as indicator
2599 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
2600 if ( this.$indicator
) {
2602 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
2603 .removeAttr( 'title' );
2606 this.$indicator
= $indicator
2607 .addClass( 'oo-ui-indicatorElement-indicator' )
2608 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
2609 if ( this.indicatorTitle
!== null ) {
2610 this.$indicator
.attr( 'title', this.indicatorTitle
);
2613 this.updateThemeClasses();
2617 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
2619 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
2622 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
2623 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
2625 if ( this.indicator
!== indicator
) {
2626 if ( this.$indicator
) {
2627 if ( this.indicator
!== null ) {
2628 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
2630 if ( indicator
!== null ) {
2631 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
2634 this.indicator
= indicator
;
2637 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
2638 this.updateThemeClasses();
2644 * Set the indicator title.
2646 * The title is displayed when a user moves the mouse over the indicator.
2648 * @param {string|Function|null} indicatorTitle Indicator title text, a function that returns text, or
2649 * `null` for no indicator title
2652 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
2653 indicatorTitle
= typeof indicatorTitle
=== 'function' ||
2654 ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ?
2655 OO
.ui
.resolveMsg( indicatorTitle
) : null;
2657 if ( this.indicatorTitle
!== indicatorTitle
) {
2658 this.indicatorTitle
= indicatorTitle
;
2659 if ( this.$indicator
) {
2660 if ( this.indicatorTitle
!== null ) {
2661 this.$indicator
.attr( 'title', indicatorTitle
);
2663 this.$indicator
.removeAttr( 'title' );
2672 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2674 * @return {string} Symbolic name of indicator
2676 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
2677 return this.indicator
;
2681 * Get the indicator title.
2683 * The title is displayed when a user moves the mouse over the indicator.
2685 * @return {string} Indicator title text
2687 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
2688 return this.indicatorTitle
;
2692 * LabelElement is often mixed into other classes to generate a label, which
2693 * helps identify the function of an interface element.
2694 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
2696 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2702 * @param {Object} [config] Configuration options
2703 * @cfg {jQuery} [$label] The label element created by the class. If this
2704 * configuration is omitted, the label element will use a generated `<span>`.
2705 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
2706 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
2707 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
2708 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2710 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
2711 // Configuration initialization
2712 config
= config
|| {};
2719 this.setLabel( config
.label
|| this.constructor.static.label
);
2720 this.setLabelElement( config
.$label
|| $( '<span>' ) );
2725 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
2730 * @event labelChange
2731 * @param {string} value
2734 /* Static Properties */
2737 * The label text. The label can be specified as a plaintext string, a function that will
2738 * produce a string in the future, or `null` for no label. The static value will
2739 * be overridden if a label is specified with the #label config option.
2743 * @property {string|Function|null}
2745 OO
.ui
.mixin
.LabelElement
.static.label
= null;
2747 /* Static methods */
2750 * Highlight the first occurrence of the query in the given text
2752 * @param {string} text Text
2753 * @param {string} query Query to find
2754 * @return {jQuery} Text with the first match of the query
2755 * sub-string wrapped in highlighted span
2757 OO
.ui
.mixin
.LabelElement
.static.highlightQuery = function ( text
, query
) {
2758 var $result
= $( '<span>' ),
2759 offset
= text
.toLowerCase().indexOf( query
.toLowerCase() );
2761 if ( !query
.length
|| offset
=== -1 ) {
2762 return $result
.text( text
);
2765 document
.createTextNode( text
.slice( 0, offset
) ),
2767 .addClass( 'oo-ui-labelElement-label-highlight' )
2768 .text( text
.slice( offset
, offset
+ query
.length
) ),
2769 document
.createTextNode( text
.slice( offset
+ query
.length
) )
2771 return $result
.contents();
2777 * Set the label element.
2779 * If an element is already set, it will be cleaned up before setting up the new element.
2781 * @param {jQuery} $label Element to use as label
2783 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
2784 if ( this.$label
) {
2785 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
2788 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
2789 this.setLabelContent( this.label
);
2795 * An empty string will result in the label being hidden. A string containing only whitespace will
2796 * be converted to a single ` `.
2798 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
2799 * text; or null for no label
2802 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
2803 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
2804 label
= ( ( typeof label
=== 'string' || label
instanceof jQuery
) && label
.length
) || ( label
instanceof OO
.ui
.HtmlSnippet
&& label
.toString().length
) ? label
: null;
2806 if ( this.label
!== label
) {
2807 if ( this.$label
) {
2808 this.setLabelContent( label
);
2811 this.emit( 'labelChange' );
2814 this.$element
.toggleClass( 'oo-ui-labelElement', !!this.label
);
2820 * Set the label as plain text with a highlighted query
2822 * @param {string} text Text label to set
2823 * @param {string} query Substring of text to highlight
2826 OO
.ui
.mixin
.LabelElement
.prototype.setHighlightedQuery = function ( text
, query
) {
2827 return this.setLabel( this.constructor.static.highlightQuery( text
, query
) );
2833 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
2834 * text; or null for no label
2836 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
2844 * @deprecated since 0.16.0
2846 OO
.ui
.mixin
.LabelElement
.prototype.fitLabel = function () {
2851 * Set the content of the label.
2853 * Do not call this method until after the label element has been set by #setLabelElement.
2856 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
2857 * text; or null for no label
2859 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
2860 if ( typeof label
=== 'string' ) {
2861 if ( label
.match( /^\s*$/ ) ) {
2862 // Convert whitespace only string to a single non-breaking space
2863 this.$label
.html( ' ' );
2865 this.$label
.text( label
);
2867 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
2868 this.$label
.html( label
.toString() );
2869 } else if ( label
instanceof jQuery
) {
2870 this.$label
.empty().append( label
);
2872 this.$label
.empty();
2877 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
2878 * additional functionality to an element created by another class. The class provides
2879 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
2880 * which are used to customize the look and feel of a widget to better describe its
2881 * importance and functionality.
2883 * The library currently contains the following styling flags for general use:
2885 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
2886 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
2887 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
2889 * The flags affect the appearance of the buttons:
2892 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
2893 * var button1 = new OO.ui.ButtonWidget( {
2894 * label: 'Constructive',
2895 * flags: 'constructive'
2897 * var button2 = new OO.ui.ButtonWidget( {
2898 * label: 'Destructive',
2899 * flags: 'destructive'
2901 * var button3 = new OO.ui.ButtonWidget( {
2902 * label: 'Progressive',
2903 * flags: 'progressive'
2905 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
2907 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
2908 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
2910 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
2916 * @param {Object} [config] Configuration options
2917 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
2918 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
2919 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
2920 * @cfg {jQuery} [$flagged] The flagged element. By default,
2921 * the flagged functionality is applied to the element created by the class ($element).
2922 * If a different element is specified, the flagged functionality will be applied to it instead.
2924 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
2925 // Configuration initialization
2926 config
= config
|| {};
2930 this.$flagged
= null;
2933 this.setFlags( config
.flags
);
2934 this.setFlaggedElement( config
.$flagged
|| this.$element
);
2941 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
2942 * parameter contains the name of each modified flag and indicates whether it was
2945 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
2946 * that the flag was added, `false` that the flag was removed.
2952 * Set the flagged element.
2954 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
2955 * If an element is already set, the method will remove the mixin’s effect on that element.
2957 * @param {jQuery} $flagged Element that should be flagged
2959 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
2960 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
2961 return 'oo-ui-flaggedElement-' + flag
;
2964 if ( this.$flagged
) {
2965 this.$flagged
.removeClass( classNames
);
2968 this.$flagged
= $flagged
.addClass( classNames
);
2972 * Check if the specified flag is set.
2974 * @param {string} flag Name of flag
2975 * @return {boolean} The flag is set
2977 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
2978 // This may be called before the constructor, thus before this.flags is set
2979 return this.flags
&& ( flag
in this.flags
);
2983 * Get the names of all flags set.
2985 * @return {string[]} Flag names
2987 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
2988 // This may be called before the constructor, thus before this.flags is set
2989 return Object
.keys( this.flags
|| {} );
2998 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
2999 var flag
, className
,
3002 classPrefix
= 'oo-ui-flaggedElement-';
3004 for ( flag
in this.flags
) {
3005 className
= classPrefix
+ flag
;
3006 changes
[ flag
] = false;
3007 delete this.flags
[ flag
];
3008 remove
.push( className
);
3011 if ( this.$flagged
) {
3012 this.$flagged
.removeClass( remove
.join( ' ' ) );
3015 this.updateThemeClasses();
3016 this.emit( 'flag', changes
);
3022 * Add one or more flags.
3024 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
3025 * or an object keyed by flag name with a boolean value that indicates whether the flag should
3026 * be added (`true`) or removed (`false`).
3030 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
3031 var i
, len
, flag
, className
,
3035 classPrefix
= 'oo-ui-flaggedElement-';
3037 if ( typeof flags
=== 'string' ) {
3038 className
= classPrefix
+ flags
;
3040 if ( !this.flags
[ flags
] ) {
3041 this.flags
[ flags
] = true;
3042 add
.push( className
);
3044 } else if ( Array
.isArray( flags
) ) {
3045 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
3047 className
= classPrefix
+ flag
;
3049 if ( !this.flags
[ flag
] ) {
3050 changes
[ flag
] = true;
3051 this.flags
[ flag
] = true;
3052 add
.push( className
);
3055 } else if ( OO
.isPlainObject( flags
) ) {
3056 for ( flag
in flags
) {
3057 className
= classPrefix
+ flag
;
3058 if ( flags
[ flag
] ) {
3060 if ( !this.flags
[ flag
] ) {
3061 changes
[ flag
] = true;
3062 this.flags
[ flag
] = true;
3063 add
.push( className
);
3067 if ( this.flags
[ flag
] ) {
3068 changes
[ flag
] = false;
3069 delete this.flags
[ flag
];
3070 remove
.push( className
);
3076 if ( this.$flagged
) {
3078 .addClass( add
.join( ' ' ) )
3079 .removeClass( remove
.join( ' ' ) );
3082 this.updateThemeClasses();
3083 this.emit( 'flag', changes
);
3089 * TitledElement is mixed into other classes to provide a `title` attribute.
3090 * Titles are rendered by the browser and are made visible when the user moves
3091 * the mouse over the element. Titles are not visible on touch devices.
3094 * // TitledElement provides a 'title' attribute to the
3095 * // ButtonWidget class
3096 * var button = new OO.ui.ButtonWidget( {
3097 * label: 'Button with Title',
3098 * title: 'I am a button'
3100 * $( 'body' ).append( button.$element );
3106 * @param {Object} [config] Configuration options
3107 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
3108 * If this config is omitted, the title functionality is applied to $element, the
3109 * element created by the class.
3110 * @cfg {string|Function} [title] The title text or a function that returns text. If
3111 * this config is omitted, the value of the {@link #static-title static title} property is used.
3113 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
3114 // Configuration initialization
3115 config
= config
|| {};
3118 this.$titled
= null;
3122 this.setTitle( config
.title
!== undefined ? config
.title
: this.constructor.static.title
);
3123 this.setTitledElement( config
.$titled
|| this.$element
);
3128 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
3130 /* Static Properties */
3133 * The title text, a function that returns text, or `null` for no title. The value of the static property
3134 * is overridden if the #title config option is used.
3138 * @property {string|Function|null}
3140 OO
.ui
.mixin
.TitledElement
.static.title
= null;
3145 * Set the titled element.
3147 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
3148 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
3150 * @param {jQuery} $titled Element that should use the 'titled' functionality
3152 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
3153 if ( this.$titled
) {
3154 this.$titled
.removeAttr( 'title' );
3157 this.$titled
= $titled
;
3159 this.$titled
.attr( 'title', this.title
);
3166 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
3169 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
3170 title
= typeof title
=== 'function' ? OO
.ui
.resolveMsg( title
) : title
;
3171 title
= ( typeof title
=== 'string' && title
.length
) ? title
: null;
3173 if ( this.title
!== title
) {
3174 if ( this.$titled
) {
3175 if ( title
!== null ) {
3176 this.$titled
.attr( 'title', title
);
3178 this.$titled
.removeAttr( 'title' );
3190 * @return {string} Title string
3192 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
3197 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
3198 * Accesskeys allow an user to go to a specific element by using
3199 * a shortcut combination of a browser specific keys + the key
3203 * // AccessKeyedElement provides an 'accesskey' attribute to the
3204 * // ButtonWidget class
3205 * var button = new OO.ui.ButtonWidget( {
3206 * label: 'Button with Accesskey',
3209 * $( 'body' ).append( button.$element );
3215 * @param {Object} [config] Configuration options
3216 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3217 * If this config is omitted, the accesskey functionality is applied to $element, the
3218 * element created by the class.
3219 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3220 * this config is omitted, no accesskey will be added.
3222 OO
.ui
.mixin
.AccessKeyedElement
= function OoUiMixinAccessKeyedElement( config
) {
3223 // Configuration initialization
3224 config
= config
|| {};
3227 this.$accessKeyed
= null;
3228 this.accessKey
= null;
3231 this.setAccessKey( config
.accessKey
|| null );
3232 this.setAccessKeyedElement( config
.$accessKeyed
|| this.$element
);
3237 OO
.initClass( OO
.ui
.mixin
.AccessKeyedElement
);
3239 /* Static Properties */
3242 * The access key, a function that returns a key, or `null` for no accesskey.
3246 * @property {string|Function|null}
3248 OO
.ui
.mixin
.AccessKeyedElement
.static.accessKey
= null;
3253 * Set the accesskeyed element.
3255 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
3256 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
3258 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
3260 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKeyedElement = function ( $accessKeyed
) {
3261 if ( this.$accessKeyed
) {
3262 this.$accessKeyed
.removeAttr( 'accesskey' );
3265 this.$accessKeyed
= $accessKeyed
;
3266 if ( this.accessKey
) {
3267 this.$accessKeyed
.attr( 'accesskey', this.accessKey
);
3274 * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no accesskey
3277 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKey = function ( accessKey
) {
3278 accessKey
= typeof accessKey
=== 'string' ? OO
.ui
.resolveMsg( accessKey
) : null;
3280 if ( this.accessKey
!== accessKey
) {
3281 if ( this.$accessKeyed
) {
3282 if ( accessKey
!== null ) {
3283 this.$accessKeyed
.attr( 'accesskey', accessKey
);
3285 this.$accessKeyed
.removeAttr( 'accesskey' );
3288 this.accessKey
= accessKey
;
3297 * @return {string} accessKey string
3299 OO
.ui
.mixin
.AccessKeyedElement
.prototype.getAccessKey = function () {
3300 return this.accessKey
;
3304 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3305 * feels, and functionality can be customized via the class’s configuration options
3306 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
3309 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
3312 * // A button widget
3313 * var button = new OO.ui.ButtonWidget( {
3314 * label: 'Button with Icon',
3316 * iconTitle: 'Remove'
3318 * $( 'body' ).append( button.$element );
3320 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3323 * @extends OO.ui.Widget
3324 * @mixins OO.ui.mixin.ButtonElement
3325 * @mixins OO.ui.mixin.IconElement
3326 * @mixins OO.ui.mixin.IndicatorElement
3327 * @mixins OO.ui.mixin.LabelElement
3328 * @mixins OO.ui.mixin.TitledElement
3329 * @mixins OO.ui.mixin.FlaggedElement
3330 * @mixins OO.ui.mixin.TabIndexedElement
3331 * @mixins OO.ui.mixin.AccessKeyedElement
3334 * @param {Object} [config] Configuration options
3335 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3336 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3337 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3339 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
3340 // Configuration initialization
3341 config
= config
|| {};
3343 // Parent constructor
3344 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
3346 // Mixin constructors
3347 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
3348 OO
.ui
.mixin
.IconElement
.call( this, config
);
3349 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
3350 OO
.ui
.mixin
.LabelElement
.call( this, config
);
3351 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
3352 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
3353 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
3354 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$button
} ) );
3359 this.noFollow
= false;
3362 this.connect( this, { disable
: 'onDisable' } );
3365 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
3367 .addClass( 'oo-ui-buttonWidget' )
3368 .append( this.$button
);
3369 this.setHref( config
.href
);
3370 this.setTarget( config
.target
);
3371 this.setNoFollow( config
.noFollow
);
3376 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
3377 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
3378 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
3379 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
3380 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
3381 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
3382 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
3383 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
3384 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
3391 OO
.ui
.ButtonWidget
.prototype.onMouseDown = function ( e
) {
3392 if ( !this.isDisabled() ) {
3393 // Remove the tab-index while the button is down to prevent the button from stealing focus
3394 this.$button
.removeAttr( 'tabindex' );
3397 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown
.call( this, e
);
3403 OO
.ui
.ButtonWidget
.prototype.onMouseUp = function ( e
) {
3404 if ( !this.isDisabled() ) {
3405 // Restore the tab-index after the button is up to restore the button's accessibility
3406 this.$button
.attr( 'tabindex', this.tabIndex
);
3409 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp
.call( this, e
);
3413 * Get hyperlink location.
3415 * @return {string} Hyperlink location
3417 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
3422 * Get hyperlink target.
3424 * @return {string} Hyperlink target
3426 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
3431 * Get search engine traversal hint.
3433 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3435 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
3436 return this.noFollow
;
3440 * Set hyperlink location.
3442 * @param {string|null} href Hyperlink location, null to remove
3444 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
3445 href
= typeof href
=== 'string' ? href
: null;
3446 if ( href
!== null && !OO
.ui
.isSafeUrl( href
) ) {
3450 if ( href
!== this.href
) {
3459 * Update the `href` attribute, in case of changes to href or
3465 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
3466 if ( this.href
!== null && !this.isDisabled() ) {
3467 this.$button
.attr( 'href', this.href
);
3469 this.$button
.removeAttr( 'href' );
3476 * Handle disable events.
3479 * @param {boolean} disabled Element is disabled
3481 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
3486 * Set hyperlink target.
3488 * @param {string|null} target Hyperlink target, null to remove
3490 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
3491 target
= typeof target
=== 'string' ? target
: null;
3493 if ( target
!== this.target
) {
3494 this.target
= target
;
3495 if ( target
!== null ) {
3496 this.$button
.attr( 'target', target
);
3498 this.$button
.removeAttr( 'target' );
3506 * Set search engine traversal hint.
3508 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3510 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
3511 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
3513 if ( noFollow
!== this.noFollow
) {
3514 this.noFollow
= noFollow
;
3516 this.$button
.attr( 'rel', 'nofollow' );
3518 this.$button
.removeAttr( 'rel' );
3526 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3527 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3528 * removed, and cleared from the group.
3531 * // Example: A ButtonGroupWidget with two buttons
3532 * var button1 = new OO.ui.PopupButtonWidget( {
3533 * label: 'Select a category',
3536 * $content: $( '<p>List of categories...</p>' ),
3541 * var button2 = new OO.ui.ButtonWidget( {
3544 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
3545 * items: [button1, button2]
3547 * $( 'body' ).append( buttonGroup.$element );
3550 * @extends OO.ui.Widget
3551 * @mixins OO.ui.mixin.GroupElement
3554 * @param {Object} [config] Configuration options
3555 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
3557 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
3558 // Configuration initialization
3559 config
= config
|| {};
3561 // Parent constructor
3562 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
3564 // Mixin constructors
3565 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
3568 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
3569 if ( Array
.isArray( config
.items
) ) {
3570 this.addItems( config
.items
);
3576 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
3577 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
3580 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
3581 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
3582 * for a list of icons included in the library.
3585 * // An icon widget with a label
3586 * var myIcon = new OO.ui.IconWidget( {
3590 * // Create a label.
3591 * var iconLabel = new OO.ui.LabelWidget( {
3594 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
3596 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
3599 * @extends OO.ui.Widget
3600 * @mixins OO.ui.mixin.IconElement
3601 * @mixins OO.ui.mixin.TitledElement
3602 * @mixins OO.ui.mixin.FlaggedElement
3605 * @param {Object} [config] Configuration options
3607 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
3608 // Configuration initialization
3609 config
= config
|| {};
3611 // Parent constructor
3612 OO
.ui
.IconWidget
.parent
.call( this, config
);
3614 // Mixin constructors
3615 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
3616 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
3617 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
3620 this.$element
.addClass( 'oo-ui-iconWidget' );
3625 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
3626 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
3627 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
3628 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
3630 /* Static Properties */
3632 OO
.ui
.IconWidget
.static.tagName
= 'span';
3635 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
3636 * attention to the status of an item or to clarify the function of a control. For a list of
3637 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
3640 * // Example of an indicator widget
3641 * var indicator1 = new OO.ui.IndicatorWidget( {
3642 * indicator: 'alert'
3645 * // Create a fieldset layout to add a label
3646 * var fieldset = new OO.ui.FieldsetLayout();
3647 * fieldset.addItems( [
3648 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
3650 * $( 'body' ).append( fieldset.$element );
3652 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3655 * @extends OO.ui.Widget
3656 * @mixins OO.ui.mixin.IndicatorElement
3657 * @mixins OO.ui.mixin.TitledElement
3660 * @param {Object} [config] Configuration options
3662 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
3663 // Configuration initialization
3664 config
= config
|| {};
3666 // Parent constructor
3667 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
3669 // Mixin constructors
3670 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
3671 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
3674 this.$element
.addClass( 'oo-ui-indicatorWidget' );
3679 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
3680 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
3681 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
3683 /* Static Properties */
3685 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
3688 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
3689 * be configured with a `label` option that is set to a string, a label node, or a function:
3691 * - String: a plaintext string
3692 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
3693 * label that includes a link or special styling, such as a gray color or additional graphical elements.
3694 * - Function: a function that will produce a string in the future. Functions are used
3695 * in cases where the value of the label is not currently defined.
3697 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
3698 * will come into focus when the label is clicked.
3701 * // Examples of LabelWidgets
3702 * var label1 = new OO.ui.LabelWidget( {
3703 * label: 'plaintext label'
3705 * var label2 = new OO.ui.LabelWidget( {
3706 * label: $( '<a href="default.html">jQuery label</a>' )
3708 * // Create a fieldset layout with fields for each example
3709 * var fieldset = new OO.ui.FieldsetLayout();
3710 * fieldset.addItems( [
3711 * new OO.ui.FieldLayout( label1 ),
3712 * new OO.ui.FieldLayout( label2 )
3714 * $( 'body' ).append( fieldset.$element );
3717 * @extends OO.ui.Widget
3718 * @mixins OO.ui.mixin.LabelElement
3721 * @param {Object} [config] Configuration options
3722 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
3723 * Clicking the label will focus the specified input field.
3725 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
3726 // Configuration initialization
3727 config
= config
|| {};
3729 // Parent constructor
3730 OO
.ui
.LabelWidget
.parent
.call( this, config
);
3732 // Mixin constructors
3733 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
3734 OO
.ui
.mixin
.TitledElement
.call( this, config
);
3737 this.input
= config
.input
;
3740 if ( this.input
instanceof OO
.ui
.InputWidget
) {
3741 this.$element
.on( 'click', this.onClick
.bind( this ) );
3745 this.$element
.addClass( 'oo-ui-labelWidget' );
3750 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
3751 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
3752 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
3754 /* Static Properties */
3756 OO
.ui
.LabelWidget
.static.tagName
= 'span';
3761 * Handles label mouse click events.
3764 * @param {jQuery.Event} e Mouse click event
3766 OO
.ui
.LabelWidget
.prototype.onClick = function () {
3767 this.input
.simulateLabelClick();
3772 * PendingElement is a mixin that is used to create elements that notify users that something is happening
3773 * and that they should wait before proceeding. The pending state is visually represented with a pending
3774 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
3775 * field of a {@link OO.ui.TextInputWidget text input widget}.
3777 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
3778 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
3779 * in process dialogs.
3782 * function MessageDialog( config ) {
3783 * MessageDialog.parent.call( this, config );
3785 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
3787 * MessageDialog.static.actions = [
3788 * { action: 'save', label: 'Done', flags: 'primary' },
3789 * { label: 'Cancel', flags: 'safe' }
3792 * MessageDialog.prototype.initialize = function () {
3793 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
3794 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
3795 * 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>' );
3796 * this.$body.append( this.content.$element );
3798 * MessageDialog.prototype.getBodyHeight = function () {
3801 * MessageDialog.prototype.getActionProcess = function ( action ) {
3802 * var dialog = this;
3803 * if ( action === 'save' ) {
3804 * dialog.getActions().get({actions: 'save'})[0].pushPending();
3805 * return new OO.ui.Process()
3807 * .next( function () {
3808 * dialog.getActions().get({actions: 'save'})[0].popPending();
3811 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
3814 * var windowManager = new OO.ui.WindowManager();
3815 * $( 'body' ).append( windowManager.$element );
3817 * var dialog = new MessageDialog();
3818 * windowManager.addWindows( [ dialog ] );
3819 * windowManager.openWindow( dialog );
3825 * @param {Object} [config] Configuration options
3826 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
3828 OO
.ui
.mixin
.PendingElement
= function OoUiMixinPendingElement( config
) {
3829 // Configuration initialization
3830 config
= config
|| {};
3834 this.$pending
= null;
3837 this.setPendingElement( config
.$pending
|| this.$element
);
3842 OO
.initClass( OO
.ui
.mixin
.PendingElement
);
3847 * Set the pending element (and clean up any existing one).
3849 * @param {jQuery} $pending The element to set to pending.
3851 OO
.ui
.mixin
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
3852 if ( this.$pending
) {
3853 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
3856 this.$pending
= $pending
;
3857 if ( this.pending
> 0 ) {
3858 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
3863 * Check if an element is pending.
3865 * @return {boolean} Element is pending
3867 OO
.ui
.mixin
.PendingElement
.prototype.isPending = function () {
3868 return !!this.pending
;
3872 * Increase the pending counter. The pending state will remain active until the counter is zero
3873 * (i.e., the number of calls to #pushPending and #popPending is the same).
3877 OO
.ui
.mixin
.PendingElement
.prototype.pushPending = function () {
3878 if ( this.pending
=== 0 ) {
3879 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
3880 this.updateThemeClasses();
3888 * Decrease the pending counter. The pending state will remain active until the counter is zero
3889 * (i.e., the number of calls to #pushPending and #popPending is the same).
3893 OO
.ui
.mixin
.PendingElement
.prototype.popPending = function () {
3894 if ( this.pending
=== 1 ) {
3895 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
3896 this.updateThemeClasses();
3898 this.pending
= Math
.max( 0, this.pending
- 1 );
3904 * Element that can be automatically clipped to visible boundaries.
3906 * Whenever the element's natural height changes, you have to call
3907 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
3908 * clipping correctly.
3910 * The dimensions of #$clippableContainer will be compared to the boundaries of the
3911 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
3912 * then #$clippable will be given a fixed reduced height and/or width and will be made
3913 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
3914 * but you can build a static footer by setting #$clippableContainer to an element that contains
3915 * #$clippable and the footer.
3921 * @param {Object} [config] Configuration options
3922 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
3923 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
3924 * omit to use #$clippable
3926 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
3927 // Configuration initialization
3928 config
= config
|| {};
3931 this.$clippable
= null;
3932 this.$clippableContainer
= null;
3933 this.clipping
= false;
3934 this.clippedHorizontally
= false;
3935 this.clippedVertically
= false;
3936 this.$clippableScrollableContainer
= null;
3937 this.$clippableScroller
= null;
3938 this.$clippableWindow
= null;
3939 this.idealWidth
= null;
3940 this.idealHeight
= null;
3941 this.onClippableScrollHandler
= this.clip
.bind( this );
3942 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
3945 if ( config
.$clippableContainer
) {
3946 this.setClippableContainer( config
.$clippableContainer
);
3948 this.setClippableElement( config
.$clippable
|| this.$element
);
3954 * Set clippable element.
3956 * If an element is already set, it will be cleaned up before setting up the new element.
3958 * @param {jQuery} $clippable Element to make clippable
3960 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
3961 if ( this.$clippable
) {
3962 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
3963 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
3964 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
3967 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
3972 * Set clippable container.
3974 * This is the container that will be measured when deciding whether to clip. When clipping,
3975 * #$clippable will be resized in order to keep the clippable container fully visible.
3977 * If the clippable container is unset, #$clippable will be used.
3979 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
3981 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableContainer = function ( $clippableContainer
) {
3982 this.$clippableContainer
= $clippableContainer
;
3983 if ( this.$clippable
) {
3991 * Do not turn clipping on until after the element is attached to the DOM and visible.
3993 * @param {boolean} [clipping] Enable clipping, omit to toggle
3996 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
3997 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
3999 if ( this.clipping
!== clipping
) {
4000 this.clipping
= clipping
;
4002 this.$clippableScrollableContainer
= $( this.getClosestScrollableElementContainer() );
4003 // If the clippable container is the root, we have to listen to scroll events and check
4004 // jQuery.scrollTop on the window because of browser inconsistencies
4005 this.$clippableScroller
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
4006 $( OO
.ui
.Element
.static.getWindow( this.$clippableScrollableContainer
) ) :
4007 this.$clippableScrollableContainer
;
4008 this.$clippableScroller
.on( 'scroll', this.onClippableScrollHandler
);
4009 this.$clippableWindow
= $( this.getElementWindow() )
4010 .on( 'resize', this.onClippableWindowResizeHandler
);
4011 // Initial clip after visible
4014 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
4015 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4017 this.$clippableScrollableContainer
= null;
4018 this.$clippableScroller
.off( 'scroll', this.onClippableScrollHandler
);
4019 this.$clippableScroller
= null;
4020 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
4021 this.$clippableWindow
= null;
4029 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4031 * @return {boolean} Element will be clipped to the visible area
4033 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
4034 return this.clipping
;
4038 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
4040 * @return {boolean} Part of the element is being clipped
4042 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
4043 return this.clippedHorizontally
|| this.clippedVertically
;
4047 * Check if the right of the element is being clipped by the nearest scrollable container.
4049 * @return {boolean} Part of the element is being clipped
4051 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
4052 return this.clippedHorizontally
;
4056 * Check if the bottom of the element is being clipped by the nearest scrollable container.
4058 * @return {boolean} Part of the element is being clipped
4060 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
4061 return this.clippedVertically
;
4065 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
4067 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
4068 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
4070 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
4071 this.idealWidth
= width
;
4072 this.idealHeight
= height
;
4074 if ( !this.clipping
) {
4075 // Update dimensions
4076 this.$clippable
.css( { width
: width
, height
: height
} );
4078 // While clipping, idealWidth and idealHeight are not considered
4082 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
4083 * the element's natural height changes.
4085 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
4086 * overlapped by, the visible area of the nearest scrollable container.
4090 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
4091 var $container
, extraHeight
, extraWidth
, ccOffset
,
4092 $scrollableContainer
, scOffset
, scHeight
, scWidth
,
4093 ccWidth
, scrollerIsWindow
, scrollTop
, scrollLeft
,
4094 desiredWidth
, desiredHeight
, allotedWidth
, allotedHeight
,
4095 naturalWidth
, naturalHeight
, clipWidth
, clipHeight
,
4096 buffer
= 7; // Chosen by fair dice roll
4098 if ( !this.clipping
) {
4099 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
4103 $container
= this.$clippableContainer
|| this.$clippable
;
4104 extraHeight
= $container
.outerHeight() - this.$clippable
.outerHeight();
4105 extraWidth
= $container
.outerWidth() - this.$clippable
.outerWidth();
4106 ccOffset
= $container
.offset();
4107 $scrollableContainer
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
4108 this.$clippableWindow
: this.$clippableScrollableContainer
;
4109 scOffset
= $scrollableContainer
.offset() || { top
: 0, left
: 0 };
4110 scHeight
= $scrollableContainer
.innerHeight() - buffer
;
4111 scWidth
= $scrollableContainer
.innerWidth() - buffer
;
4112 ccWidth
= $container
.outerWidth() + buffer
;
4113 scrollerIsWindow
= this.$clippableScroller
[ 0 ] === this.$clippableWindow
[ 0 ];
4114 scrollTop
= scrollerIsWindow
? this.$clippableScroller
.scrollTop() : 0;
4115 scrollLeft
= scrollerIsWindow
? this.$clippableScroller
.scrollLeft() : 0;
4116 desiredWidth
= ccOffset
.left
< 0 ?
4117 ccWidth
+ ccOffset
.left
:
4118 ( scOffset
.left
+ scrollLeft
+ scWidth
) - ccOffset
.left
;
4119 desiredHeight
= ( scOffset
.top
+ scrollTop
+ scHeight
) - ccOffset
.top
;
4120 // It should never be desirable to exceed the dimensions of the browser viewport... right?
4121 desiredWidth
= Math
.min( desiredWidth
, document
.documentElement
.clientWidth
);
4122 desiredHeight
= Math
.min( desiredHeight
, document
.documentElement
.clientHeight
);
4123 allotedWidth
= Math
.ceil( desiredWidth
- extraWidth
);
4124 allotedHeight
= Math
.ceil( desiredHeight
- extraHeight
);
4125 naturalWidth
= this.$clippable
.prop( 'scrollWidth' );
4126 naturalHeight
= this.$clippable
.prop( 'scrollHeight' );
4127 clipWidth
= allotedWidth
< naturalWidth
;
4128 clipHeight
= allotedHeight
< naturalHeight
;
4131 this.$clippable
.css( { overflowX
: 'scroll', width
: Math
.max( 0, allotedWidth
) } );
4133 this.$clippable
.css( { width
: this.idealWidth
? this.idealWidth
- extraWidth
: '', overflowX
: '' } );
4136 this.$clippable
.css( { overflowY
: 'scroll', height
: Math
.max( 0, allotedHeight
) } );
4138 this.$clippable
.css( { height
: this.idealHeight
? this.idealHeight
- extraHeight
: '', overflowY
: '' } );
4141 // If we stopped clipping in at least one of the dimensions
4142 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
4143 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4146 this.clippedHorizontally
= clipWidth
;
4147 this.clippedVertically
= clipHeight
;
4153 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
4154 * By default, each popup has an anchor that points toward its origin.
4155 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
4158 * // A popup widget.
4159 * var popup = new OO.ui.PopupWidget( {
4160 * $content: $( '<p>Hi there!</p>' ),
4165 * $( 'body' ).append( popup.$element );
4166 * // To display the popup, toggle the visibility to 'true'.
4167 * popup.toggle( true );
4169 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
4172 * @extends OO.ui.Widget
4173 * @mixins OO.ui.mixin.LabelElement
4174 * @mixins OO.ui.mixin.ClippableElement
4177 * @param {Object} [config] Configuration options
4178 * @cfg {number} [width=320] Width of popup in pixels
4179 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
4180 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
4181 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
4182 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
4183 * popup is leaning towards the right of the screen.
4184 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
4185 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
4186 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
4187 * sentence in the given language.
4188 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
4189 * See the [OOjs UI docs on MediaWiki][3] for an example.
4190 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
4191 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
4192 * @cfg {jQuery} [$content] Content to append to the popup's body
4193 * @cfg {jQuery} [$footer] Content to append to the popup's footer
4194 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
4195 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
4196 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
4198 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
4199 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
4201 * @cfg {boolean} [padded=false] Add padding to the popup's body
4203 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
4204 // Configuration initialization
4205 config
= config
|| {};
4207 // Parent constructor
4208 OO
.ui
.PopupWidget
.parent
.call( this, config
);
4210 // Properties (must be set before ClippableElement constructor call)
4211 this.$body
= $( '<div>' );
4212 this.$popup
= $( '<div>' );
4214 // Mixin constructors
4215 OO
.ui
.mixin
.LabelElement
.call( this, config
);
4216 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, {
4217 $clippable
: this.$body
,
4218 $clippableContainer
: this.$popup
4222 this.$anchor
= $( '<div>' );
4223 // If undefined, will be computed lazily in updateDimensions()
4224 this.$container
= config
.$container
;
4225 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
4226 this.autoClose
= !!config
.autoClose
;
4227 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
4228 this.transitionTimeout
= null;
4230 this.width
= config
.width
!== undefined ? config
.width
: 320;
4231 this.height
= config
.height
!== undefined ? config
.height
: null;
4232 this.setAlignment( config
.align
);
4233 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
4234 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
4237 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
4238 this.$body
.addClass( 'oo-ui-popupWidget-body' );
4239 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
4241 .addClass( 'oo-ui-popupWidget-popup' )
4242 .append( this.$body
);
4244 .addClass( 'oo-ui-popupWidget' )
4245 .append( this.$popup
, this.$anchor
);
4246 // Move content, which was added to #$element by OO.ui.Widget, to the body
4247 // FIXME This is gross, we should use '$body' or something for the config
4248 if ( config
.$content
instanceof jQuery
) {
4249 this.$body
.append( config
.$content
);
4252 if ( config
.padded
) {
4253 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
4256 if ( config
.head
) {
4257 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
4258 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
4259 this.$head
= $( '<div>' )
4260 .addClass( 'oo-ui-popupWidget-head' )
4261 .append( this.$label
, this.closeButton
.$element
);
4262 this.$popup
.prepend( this.$head
);
4265 if ( config
.$footer
) {
4266 this.$footer
= $( '<div>' )
4267 .addClass( 'oo-ui-popupWidget-footer' )
4268 .append( config
.$footer
);
4269 this.$popup
.append( this.$footer
);
4272 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
4273 // that reference properties not initialized at that time of parent class construction
4274 // TODO: Find a better way to handle post-constructor setup
4275 this.visible
= false;
4276 this.$element
.addClass( 'oo-ui-element-hidden' );
4281 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
4282 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
4283 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
4288 * Handles mouse down events.
4291 * @param {MouseEvent} e Mouse down event
4293 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
4296 !$.contains( this.$element
[ 0 ], e
.target
) &&
4297 ( !this.$autoCloseIgnore
|| !this.$autoCloseIgnore
.has( e
.target
).length
)
4299 this.toggle( false );
4304 * Bind mouse down listener.
4308 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
4309 // Capture clicks outside popup
4310 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler
, true );
4314 * Handles close button click events.
4318 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
4319 if ( this.isVisible() ) {
4320 this.toggle( false );
4325 * Unbind mouse down listener.
4329 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
4330 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler
, true );
4334 * Handles key down events.
4337 * @param {KeyboardEvent} e Key down event
4339 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
4341 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
4344 this.toggle( false );
4346 e
.stopPropagation();
4351 * Bind key down listener.
4355 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
4356 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
4360 * Unbind key down listener.
4364 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
4365 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
4369 * Show, hide, or toggle the visibility of the anchor.
4371 * @param {boolean} [show] Show anchor, omit to toggle
4373 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
4374 show
= show
=== undefined ? !this.anchored
: !!show
;
4376 if ( this.anchored
!== show
) {
4378 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
4380 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
4382 this.anchored
= show
;
4387 * Check if the anchor is visible.
4389 * @return {boolean} Anchor is visible
4391 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
4398 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
4400 show
= show
=== undefined ? !this.isVisible() : !!show
;
4402 change
= show
!== this.isVisible();
4405 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
4409 if ( this.autoClose
) {
4410 this.bindMouseDownListener();
4411 this.bindKeyDownListener();
4413 this.updateDimensions();
4414 this.toggleClipping( true );
4416 this.toggleClipping( false );
4417 if ( this.autoClose
) {
4418 this.unbindMouseDownListener();
4419 this.unbindKeyDownListener();
4428 * Set the size of the popup.
4430 * Changing the size may also change the popup's position depending on the alignment.
4432 * @param {number} width Width in pixels
4433 * @param {number} height Height in pixels
4434 * @param {boolean} [transition=false] Use a smooth transition
4437 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
4439 this.height
= height
!== undefined ? height
: null;
4440 if ( this.isVisible() ) {
4441 this.updateDimensions( transition
);
4446 * Update the size and position.
4448 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
4449 * be called automatically.
4451 * @param {boolean} [transition=false] Use a smooth transition
4454 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
4455 var popupOffset
, originOffset
, containerLeft
, containerWidth
, containerRight
,
4456 popupLeft
, popupRight
, overlapLeft
, overlapRight
, anchorWidth
,
4460 if ( !this.$container
) {
4461 // Lazy-initialize $container if not specified in constructor
4462 this.$container
= $( this.getClosestScrollableElementContainer() );
4465 // Set height and width before measuring things, since it might cause our measurements
4466 // to change (e.g. due to scrollbars appearing or disappearing)
4469 height
: this.height
!== null ? this.height
: 'auto'
4472 // If we are in RTL, we need to flip the alignment, unless it is center
4473 if ( align
=== 'forwards' || align
=== 'backwards' ) {
4474 if ( this.$container
.css( 'direction' ) === 'rtl' ) {
4475 align
= ( { forwards
: 'force-left', backwards
: 'force-right' } )[ this.align
];
4477 align
= ( { forwards
: 'force-right', backwards
: 'force-left' } )[ this.align
];
4482 // Compute initial popupOffset based on alignment
4483 popupOffset
= this.width
* ( { 'force-left': -1, center
: -0.5, 'force-right': 0 } )[ align
];
4485 // Figure out if this will cause the popup to go beyond the edge of the container
4486 originOffset
= this.$element
.offset().left
;
4487 containerLeft
= this.$container
.offset().left
;
4488 containerWidth
= this.$container
.innerWidth();
4489 containerRight
= containerLeft
+ containerWidth
;
4490 popupLeft
= popupOffset
- this.containerPadding
;
4491 popupRight
= popupOffset
+ this.containerPadding
+ this.width
+ this.containerPadding
;
4492 overlapLeft
= ( originOffset
+ popupLeft
) - containerLeft
;
4493 overlapRight
= containerRight
- ( originOffset
+ popupRight
);
4495 // Adjust offset to make the popup not go beyond the edge, if needed
4496 if ( overlapRight
< 0 ) {
4497 popupOffset
+= overlapRight
;
4498 } else if ( overlapLeft
< 0 ) {
4499 popupOffset
-= overlapLeft
;
4502 // Adjust offset to avoid anchor being rendered too close to the edge
4503 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
4504 // TODO: Find a measurement that works for CSS anchors and image anchors
4505 anchorWidth
= this.$anchor
[ 0 ].scrollWidth
* 2;
4506 if ( popupOffset
+ this.width
< anchorWidth
) {
4507 popupOffset
= anchorWidth
- this.width
;
4508 } else if ( -popupOffset
< anchorWidth
) {
4509 popupOffset
= -anchorWidth
;
4512 // Prevent transition from being interrupted
4513 clearTimeout( this.transitionTimeout
);
4515 // Enable transition
4516 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
4519 // Position body relative to anchor
4520 this.$popup
.css( 'margin-left', popupOffset
);
4523 // Prevent transitioning after transition is complete
4524 this.transitionTimeout
= setTimeout( function () {
4525 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
4528 // Prevent transitioning immediately
4529 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
4532 // Reevaluate clipping state since we've relocated and resized the popup
4539 * Set popup alignment
4541 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
4542 * `backwards` or `forwards`.
4544 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
4545 // Validate alignment and transform deprecated values
4546 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
4547 this.align
= { left
: 'force-right', right
: 'force-left' }[ align
] || align
;
4549 this.align
= 'center';
4554 * Get popup alignment
4556 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
4557 * `backwards` or `forwards`.
4559 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
4564 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
4565 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
4566 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
4567 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
4573 * @param {Object} [config] Configuration options
4574 * @cfg {Object} [popup] Configuration to pass to popup
4575 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
4577 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
4578 // Configuration initialization
4579 config
= config
|| {};
4582 this.popup
= new OO
.ui
.PopupWidget( $.extend(
4583 { autoClose
: true },
4585 { $autoCloseIgnore
: this.$element
}
4594 * @return {OO.ui.PopupWidget} Popup widget
4596 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
4601 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
4602 * which is used to display additional information or options.
4605 * // Example of a popup button.
4606 * var popupButton = new OO.ui.PopupButtonWidget( {
4607 * label: 'Popup button with options',
4610 * $content: $( '<p>Additional options here.</p>' ),
4612 * align: 'force-left'
4615 * // Append the button to the DOM.
4616 * $( 'body' ).append( popupButton.$element );
4619 * @extends OO.ui.ButtonWidget
4620 * @mixins OO.ui.mixin.PopupElement
4623 * @param {Object} [config] Configuration options
4625 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
4626 // Parent constructor
4627 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
4629 // Mixin constructors
4630 OO
.ui
.mixin
.PopupElement
.call( this, config
);
4633 this.connect( this, { click
: 'onAction' } );
4637 .addClass( 'oo-ui-popupButtonWidget' )
4638 .attr( 'aria-haspopup', 'true' )
4639 .append( this.popup
.$element
);
4644 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
4645 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
4650 * Handle the button action being triggered.
4654 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
4655 this.popup
.toggle();
4659 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
4661 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
4666 * @extends OO.ui.mixin.GroupElement
4669 * @param {Object} [config] Configuration options
4671 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
4672 // Parent constructor
4673 OO
.ui
.mixin
.GroupWidget
.parent
.call( this, config
);
4678 OO
.inheritClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
4683 * Set the disabled state of the widget.
4685 * This will also update the disabled state of child widgets.
4687 * @param {boolean} disabled Disable widget
4690 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
4694 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
4695 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
4697 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
4699 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4700 this.items
[ i
].updateDisabled();
4708 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
4710 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
4711 * allows bidirectional communication.
4713 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
4721 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
4728 * Check if widget is disabled.
4730 * Checks parent if present, making disabled state inheritable.
4732 * @return {boolean} Widget is disabled
4734 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
4735 return this.disabled
||
4736 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
4740 * Set group element is in.
4742 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
4745 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
4747 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
4748 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
4750 // Initialize item disabled states
4751 this.updateDisabled();
4757 * OptionWidgets are special elements that can be selected and configured with data. The
4758 * data is often unique for each option, but it does not have to be. OptionWidgets are used
4759 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
4760 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
4762 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
4765 * @extends OO.ui.Widget
4766 * @mixins OO.ui.mixin.LabelElement
4767 * @mixins OO.ui.mixin.FlaggedElement
4770 * @param {Object} [config] Configuration options
4772 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
4773 // Configuration initialization
4774 config
= config
|| {};
4776 // Parent constructor
4777 OO
.ui
.OptionWidget
.parent
.call( this, config
);
4779 // Mixin constructors
4780 OO
.ui
.mixin
.ItemWidget
.call( this );
4781 OO
.ui
.mixin
.LabelElement
.call( this, config
);
4782 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
4785 this.selected
= false;
4786 this.highlighted
= false;
4787 this.pressed
= false;
4791 .data( 'oo-ui-optionWidget', this )
4792 .attr( 'role', 'option' )
4793 .attr( 'aria-selected', 'false' )
4794 .addClass( 'oo-ui-optionWidget' )
4795 .append( this.$label
);
4800 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
4801 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
4802 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
4803 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
4805 /* Static Properties */
4807 OO
.ui
.OptionWidget
.static.selectable
= true;
4809 OO
.ui
.OptionWidget
.static.highlightable
= true;
4811 OO
.ui
.OptionWidget
.static.pressable
= true;
4813 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
4818 * Check if the option can be selected.
4820 * @return {boolean} Item is selectable
4822 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
4823 return this.constructor.static.selectable
&& !this.isDisabled() && this.isVisible();
4827 * Check if the option can be highlighted. A highlight indicates that the option
4828 * may be selected when a user presses enter or clicks. Disabled items cannot
4831 * @return {boolean} Item is highlightable
4833 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
4834 return this.constructor.static.highlightable
&& !this.isDisabled() && this.isVisible();
4838 * Check if the option can be pressed. The pressed state occurs when a user mouses
4839 * down on an item, but has not yet let go of the mouse.
4841 * @return {boolean} Item is pressable
4843 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
4844 return this.constructor.static.pressable
&& !this.isDisabled() && this.isVisible();
4848 * Check if the option is selected.
4850 * @return {boolean} Item is selected
4852 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
4853 return this.selected
;
4857 * Check if the option is highlighted. A highlight indicates that the
4858 * item may be selected when a user presses enter or clicks.
4860 * @return {boolean} Item is highlighted
4862 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
4863 return this.highlighted
;
4867 * Check if the option is pressed. The pressed state occurs when a user mouses
4868 * down on an item, but has not yet let go of the mouse. The item may appear
4869 * selected, but it will not be selected until the user releases the mouse.
4871 * @return {boolean} Item is pressed
4873 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
4874 return this.pressed
;
4878 * Set the option’s selected state. In general, all modifications to the selection
4879 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
4880 * method instead of this method.
4882 * @param {boolean} [state=false] Select option
4885 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
4886 if ( this.constructor.static.selectable
) {
4887 this.selected
= !!state
;
4889 .toggleClass( 'oo-ui-optionWidget-selected', state
)
4890 .attr( 'aria-selected', state
.toString() );
4891 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
4892 this.scrollElementIntoView();
4894 this.updateThemeClasses();
4900 * Set the option’s highlighted state. In general, all programmatic
4901 * modifications to the highlight should be handled by the
4902 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
4903 * method instead of this method.
4905 * @param {boolean} [state=false] Highlight option
4908 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
4909 if ( this.constructor.static.highlightable
) {
4910 this.highlighted
= !!state
;
4911 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
4912 this.updateThemeClasses();
4918 * Set the option’s pressed state. In general, all
4919 * programmatic modifications to the pressed state should be handled by the
4920 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
4921 * method instead of this method.
4923 * @param {boolean} [state=false] Press option
4926 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
4927 if ( this.constructor.static.pressable
) {
4928 this.pressed
= !!state
;
4929 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
4930 this.updateThemeClasses();
4936 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
4937 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
4938 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
4941 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
4942 * information, please see the [OOjs UI documentation on MediaWiki][1].
4945 * // Example of a select widget with three options
4946 * var select = new OO.ui.SelectWidget( {
4948 * new OO.ui.OptionWidget( {
4950 * label: 'Option One',
4952 * new OO.ui.OptionWidget( {
4954 * label: 'Option Two',
4956 * new OO.ui.OptionWidget( {
4958 * label: 'Option Three',
4962 * $( 'body' ).append( select.$element );
4964 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
4968 * @extends OO.ui.Widget
4969 * @mixins OO.ui.mixin.GroupWidget
4972 * @param {Object} [config] Configuration options
4973 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
4974 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
4975 * the [OOjs UI documentation on MediaWiki] [2] for examples.
4976 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
4978 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
4979 // Configuration initialization
4980 config
= config
|| {};
4982 // Parent constructor
4983 OO
.ui
.SelectWidget
.parent
.call( this, config
);
4985 // Mixin constructors
4986 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
4989 this.pressed
= false;
4990 this.selecting
= null;
4991 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
4992 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
4993 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
4994 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
4995 this.keyPressBuffer
= '';
4996 this.keyPressBufferTimer
= null;
4997 this.blockMouseOverEvents
= 0;
5000 this.connect( this, {
5004 mousedown
: this.onMouseDown
.bind( this ),
5005 mouseover
: this.onMouseOver
.bind( this ),
5006 mouseleave
: this.onMouseLeave
.bind( this )
5011 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
5012 .attr( 'role', 'listbox' );
5013 if ( Array
.isArray( config
.items
) ) {
5014 this.addItems( config
.items
);
5020 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
5022 // Need to mixin base class as well
5023 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupElement
);
5024 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
5027 OO
.ui
.SelectWidget
.static.passAllFilter = function () {
5036 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
5038 * @param {OO.ui.OptionWidget|null} item Highlighted item
5044 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
5045 * pressed state of an option.
5047 * @param {OO.ui.OptionWidget|null} item Pressed item
5053 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
5055 * @param {OO.ui.OptionWidget|null} item Selected item
5060 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
5061 * @param {OO.ui.OptionWidget} item Chosen item
5067 * An `add` event is emitted when options are added to the select with the #addItems method.
5069 * @param {OO.ui.OptionWidget[]} items Added items
5070 * @param {number} index Index of insertion point
5076 * A `remove` event is emitted when options are removed from the select with the #clearItems
5077 * or #removeItems methods.
5079 * @param {OO.ui.OptionWidget[]} items Removed items
5085 * Handle mouse down events.
5088 * @param {jQuery.Event} e Mouse down event
5090 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
5093 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
5094 this.togglePressed( true );
5095 item
= this.getTargetItem( e
);
5096 if ( item
&& item
.isSelectable() ) {
5097 this.pressItem( item
);
5098 this.selecting
= item
;
5099 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
5100 this.getElementDocument().addEventListener( 'mousemove', this.onMouseMoveHandler
, true );
5107 * Handle mouse up events.
5110 * @param {MouseEvent} e Mouse up event
5112 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
5115 this.togglePressed( false );
5116 if ( !this.selecting
) {
5117 item
= this.getTargetItem( e
);
5118 if ( item
&& item
.isSelectable() ) {
5119 this.selecting
= item
;
5122 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
&& this.selecting
) {
5123 this.pressItem( null );
5124 this.chooseItem( this.selecting
);
5125 this.selecting
= null;
5128 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
5129 this.getElementDocument().removeEventListener( 'mousemove', this.onMouseMoveHandler
, true );
5135 * Handle mouse move events.
5138 * @param {MouseEvent} e Mouse move event
5140 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
5143 if ( !this.isDisabled() && this.pressed
) {
5144 item
= this.getTargetItem( e
);
5145 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
5146 this.pressItem( item
);
5147 this.selecting
= item
;
5153 * Handle mouse over events.
5156 * @param {jQuery.Event} e Mouse over event
5158 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
5160 if ( this.blockMouseOverEvents
) {
5163 if ( !this.isDisabled() ) {
5164 item
= this.getTargetItem( e
);
5165 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
5171 * Handle mouse leave events.
5174 * @param {jQuery.Event} e Mouse over event
5176 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
5177 if ( !this.isDisabled() ) {
5178 this.highlightItem( null );
5184 * Handle key down events.
5187 * @param {KeyboardEvent} e Key down event
5189 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
5192 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
5194 if ( !this.isDisabled() && this.isVisible() ) {
5195 switch ( e
.keyCode
) {
5196 case OO
.ui
.Keys
.ENTER
:
5197 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
5198 // Was only highlighted, now let's select it. No-op if already selected.
5199 this.chooseItem( currentItem
);
5204 case OO
.ui
.Keys
.LEFT
:
5205 this.clearKeyPressBuffer();
5206 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
5209 case OO
.ui
.Keys
.DOWN
:
5210 case OO
.ui
.Keys
.RIGHT
:
5211 this.clearKeyPressBuffer();
5212 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
5215 case OO
.ui
.Keys
.ESCAPE
:
5216 case OO
.ui
.Keys
.TAB
:
5217 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
5218 currentItem
.setHighlighted( false );
5220 this.unbindKeyDownListener();
5221 this.unbindKeyPressListener();
5222 // Don't prevent tabbing away / defocusing
5228 if ( nextItem
.constructor.static.highlightable
) {
5229 this.highlightItem( nextItem
);
5231 this.chooseItem( nextItem
);
5233 this.scrollItemIntoView( nextItem
);
5238 e
.stopPropagation();
5244 * Bind key down listener.
5248 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
5249 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler
, true );
5253 * Unbind key down listener.
5257 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
5258 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler
, true );
5262 * Scroll item into view, preventing spurious mouse highlight actions from happening.
5264 * @param {OO.ui.OptionWidget} item Item to scroll into view
5266 OO
.ui
.SelectWidget
.prototype.scrollItemIntoView = function ( item
) {
5268 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling
5269 // and around 100-150 ms after it is finished.
5270 this.blockMouseOverEvents
++;
5271 item
.scrollElementIntoView().done( function () {
5272 setTimeout( function () {
5273 widget
.blockMouseOverEvents
--;
5279 * Clear the key-press buffer
5283 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
5284 if ( this.keyPressBufferTimer
) {
5285 clearTimeout( this.keyPressBufferTimer
);
5286 this.keyPressBufferTimer
= null;
5288 this.keyPressBuffer
= '';
5292 * Handle key press events.
5295 * @param {KeyboardEvent} e Key press event
5297 OO
.ui
.SelectWidget
.prototype.onKeyPress = function ( e
) {
5298 var c
, filter
, item
;
5300 if ( !e
.charCode
) {
5301 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
5302 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
5307 if ( String
.fromCodePoint
) {
5308 c
= String
.fromCodePoint( e
.charCode
);
5310 c
= String
.fromCharCode( e
.charCode
);
5313 if ( this.keyPressBufferTimer
) {
5314 clearTimeout( this.keyPressBufferTimer
);
5316 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
5318 item
= this.getHighlightedItem() || this.getSelectedItem();
5320 if ( this.keyPressBuffer
=== c
) {
5321 // Common (if weird) special case: typing "xxxx" will cycle through all
5322 // the items beginning with "x".
5324 item
= this.getRelativeSelectableItem( item
, 1 );
5327 this.keyPressBuffer
+= c
;
5330 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
5331 if ( !item
|| !filter( item
) ) {
5332 item
= this.getRelativeSelectableItem( item
, 1, filter
);
5335 if ( item
.constructor.static.highlightable
) {
5336 this.highlightItem( item
);
5338 this.chooseItem( item
);
5340 this.scrollItemIntoView( item
);
5344 e
.stopPropagation();
5348 * Get a matcher for the specific string
5351 * @param {string} s String to match against items
5352 * @param {boolean} [exact=false] Only accept exact matches
5353 * @return {Function} function ( OO.ui.OptionItem ) => boolean
5355 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
, exact
) {
5358 if ( s
.normalize
) {
5361 s
= exact
? s
.trim() : s
.replace( /^\s+/, '' );
5362 re
= '^\\s*' + s
.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
5366 re
= new RegExp( re
, 'i' );
5367 return function ( item
) {
5368 var l
= item
.getLabel();
5369 if ( typeof l
!== 'string' ) {
5370 l
= item
.$label
.text();
5372 if ( l
.normalize
) {
5375 return re
.test( l
);
5380 * Bind key press listener.
5384 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
5385 this.getElementWindow().addEventListener( 'keypress', this.onKeyPressHandler
, true );
5389 * Unbind key down listener.
5391 * If you override this, be sure to call this.clearKeyPressBuffer() from your
5396 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
5397 this.getElementWindow().removeEventListener( 'keypress', this.onKeyPressHandler
, true );
5398 this.clearKeyPressBuffer();
5402 * Visibility change handler
5405 * @param {boolean} visible
5407 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
5409 this.clearKeyPressBuffer();
5414 * Get the closest item to a jQuery.Event.
5417 * @param {jQuery.Event} e
5418 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
5420 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
5421 return $( e
.target
).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
5425 * Get selected item.
5427 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
5429 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
5432 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5433 if ( this.items
[ i
].isSelected() ) {
5434 return this.items
[ i
];
5441 * Get highlighted item.
5443 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
5445 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
5448 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5449 if ( this.items
[ i
].isHighlighted() ) {
5450 return this.items
[ i
];
5457 * Toggle pressed state.
5459 * Press is a state that occurs when a user mouses down on an item, but
5460 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
5461 * until the user releases the mouse.
5463 * @param {boolean} pressed An option is being pressed
5465 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
5466 if ( pressed
=== undefined ) {
5467 pressed
= !this.pressed
;
5469 if ( pressed
!== this.pressed
) {
5471 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
5472 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
5473 this.pressed
= pressed
;
5478 * Highlight an option. If the `item` param is omitted, no options will be highlighted
5479 * and any existing highlight will be removed. The highlight is mutually exclusive.
5481 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
5485 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
5486 var i
, len
, highlighted
,
5489 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5490 highlighted
= this.items
[ i
] === item
;
5491 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
5492 this.items
[ i
].setHighlighted( highlighted
);
5497 this.emit( 'highlight', item
);
5504 * Fetch an item by its label.
5506 * @param {string} label Label of the item to select.
5507 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
5508 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
5510 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
5512 len
= this.items
.length
,
5513 filter
= this.getItemMatcher( label
, true );
5515 for ( i
= 0; i
< len
; i
++ ) {
5516 item
= this.items
[ i
];
5517 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
5524 filter
= this.getItemMatcher( label
, false );
5525 for ( i
= 0; i
< len
; i
++ ) {
5526 item
= this.items
[ i
];
5527 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
5543 * Programmatically select an option by its label. If the item does not exist,
5544 * all options will be deselected.
5546 * @param {string} [label] Label of the item to select.
5547 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
5551 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
5552 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
5553 if ( label
=== undefined || !itemFromLabel
) {
5554 return this.selectItem();
5556 return this.selectItem( itemFromLabel
);
5560 * Programmatically select an option by its data. If the `data` parameter is omitted,
5561 * or if the item does not exist, all options will be deselected.
5563 * @param {Object|string} [data] Value of the item to select, omit to deselect all
5567 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
5568 var itemFromData
= this.getItemFromData( data
);
5569 if ( data
=== undefined || !itemFromData
) {
5570 return this.selectItem();
5572 return this.selectItem( itemFromData
);
5576 * Programmatically select an option by its reference. If the `item` parameter is omitted,
5577 * all options will be deselected.
5579 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
5583 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
5584 var i
, len
, selected
,
5587 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5588 selected
= this.items
[ i
] === item
;
5589 if ( this.items
[ i
].isSelected() !== selected
) {
5590 this.items
[ i
].setSelected( selected
);
5595 this.emit( 'select', item
);
5604 * Press is a state that occurs when a user mouses down on an item, but has not
5605 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
5606 * releases the mouse.
5608 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
5612 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
5613 var i
, len
, pressed
,
5616 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5617 pressed
= this.items
[ i
] === item
;
5618 if ( this.items
[ i
].isPressed() !== pressed
) {
5619 this.items
[ i
].setPressed( pressed
);
5624 this.emit( 'press', item
);
5633 * Note that ‘choose’ should never be modified programmatically. A user can choose
5634 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
5635 * use the #selectItem method.
5637 * This method is identical to #selectItem, but may vary in subclasses that take additional action
5638 * when users choose an item with the keyboard or mouse.
5640 * @param {OO.ui.OptionWidget} item Item to choose
5644 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
5646 this.selectItem( item
);
5647 this.emit( 'choose', item
);
5654 * Get an option by its position relative to the specified item (or to the start of the option array,
5655 * if item is `null`). The direction in which to search through the option array is specified with a
5656 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
5657 * `null` if there are no options in the array.
5659 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
5660 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
5661 * @param {Function} filter Only consider items for which this function returns
5662 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
5663 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
5665 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
, filter
) {
5666 var currentIndex
, nextIndex
, i
,
5667 increase
= direction
> 0 ? 1 : -1,
5668 len
= this.items
.length
;
5670 if ( !$.isFunction( filter
) ) {
5671 filter
= OO
.ui
.SelectWidget
.static.passAllFilter
;
5674 if ( item
instanceof OO
.ui
.OptionWidget
) {
5675 currentIndex
= this.items
.indexOf( item
);
5676 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
5678 // If no item is selected and moving forward, start at the beginning.
5679 // If moving backward, start at the end.
5680 nextIndex
= direction
> 0 ? 0 : len
- 1;
5683 for ( i
= 0; i
< len
; i
++ ) {
5684 item
= this.items
[ nextIndex
];
5685 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
5688 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
5694 * Get the next selectable item or `null` if there are no selectable items.
5695 * Disabled options and menu-section markers and breaks are not selectable.
5697 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
5699 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
5702 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5703 item
= this.items
[ i
];
5704 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() ) {
5713 * Add an array of options to the select. Optionally, an index number can be used to
5714 * specify an insertion point.
5716 * @param {OO.ui.OptionWidget[]} items Items to add
5717 * @param {number} [index] Index to insert items after
5721 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
5723 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
5725 // Always provide an index, even if it was omitted
5726 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
5732 * Remove the specified array of options from the select. Options will be detached
5733 * from the DOM, not removed, so they can be reused later. To remove all options from
5734 * the select, you may wish to use the #clearItems method instead.
5736 * @param {OO.ui.OptionWidget[]} items Items to remove
5740 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
5743 // Deselect items being removed
5744 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
5746 if ( item
.isSelected() ) {
5747 this.selectItem( null );
5752 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
5754 this.emit( 'remove', items
);
5760 * Clear all options from the select. Options will be detached from the DOM, not removed,
5761 * so that they can be reused later. To remove a subset of options from the select, use
5762 * the #removeItems method.
5767 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
5768 var items
= this.items
.slice();
5771 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
5774 this.selectItem( null );
5776 this.emit( 'remove', items
);
5782 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
5783 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
5784 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
5785 * options. For more information about options and selects, please see the
5786 * [OOjs UI documentation on MediaWiki][1].
5789 * // Decorated options in a select widget
5790 * var select = new OO.ui.SelectWidget( {
5792 * new OO.ui.DecoratedOptionWidget( {
5794 * label: 'Option with icon',
5797 * new OO.ui.DecoratedOptionWidget( {
5799 * label: 'Option with indicator',
5804 * $( 'body' ).append( select.$element );
5806 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5809 * @extends OO.ui.OptionWidget
5810 * @mixins OO.ui.mixin.IconElement
5811 * @mixins OO.ui.mixin.IndicatorElement
5814 * @param {Object} [config] Configuration options
5816 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
5817 // Parent constructor
5818 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
5820 // Mixin constructors
5821 OO
.ui
.mixin
.IconElement
.call( this, config
);
5822 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
5826 .addClass( 'oo-ui-decoratedOptionWidget' )
5827 .prepend( this.$icon
)
5828 .append( this.$indicator
);
5833 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
5834 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
5835 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
5838 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
5839 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
5840 * the [OOjs UI documentation on MediaWiki] [1] for more information.
5842 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
5845 * @extends OO.ui.DecoratedOptionWidget
5848 * @param {Object} [config] Configuration options
5850 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
5851 // Configuration initialization
5852 config
= $.extend( { icon
: 'check' }, config
);
5854 // Parent constructor
5855 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
5859 .attr( 'role', 'menuitem' )
5860 .addClass( 'oo-ui-menuOptionWidget' );
5865 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
5867 /* Static Properties */
5869 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
5872 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
5873 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
5876 * var myDropdown = new OO.ui.DropdownWidget( {
5879 * new OO.ui.MenuSectionOptionWidget( {
5882 * new OO.ui.MenuOptionWidget( {
5884 * label: 'Welsh Corgi'
5886 * new OO.ui.MenuOptionWidget( {
5888 * label: 'Standard Poodle'
5890 * new OO.ui.MenuSectionOptionWidget( {
5893 * new OO.ui.MenuOptionWidget( {
5900 * $( 'body' ).append( myDropdown.$element );
5903 * @extends OO.ui.DecoratedOptionWidget
5906 * @param {Object} [config] Configuration options
5908 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
5909 // Parent constructor
5910 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
5913 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' );
5918 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
5920 /* Static Properties */
5922 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
5924 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
5927 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
5928 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
5929 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
5930 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
5931 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
5932 * and customized to be opened, closed, and displayed as needed.
5934 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
5935 * mouse outside the menu.
5937 * Menus also have support for keyboard interaction:
5939 * - Enter/Return key: choose and select a menu option
5940 * - Up-arrow key: highlight the previous menu option
5941 * - Down-arrow key: highlight the next menu option
5942 * - Esc key: hide the menu
5944 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
5945 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5948 * @extends OO.ui.SelectWidget
5949 * @mixins OO.ui.mixin.ClippableElement
5952 * @param {Object} [config] Configuration options
5953 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
5954 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
5955 * and {@link OO.ui.mixin.LookupElement LookupElement}
5956 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
5957 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiSelectWidget CapsuleMultiSelectWidget}
5958 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
5959 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
5960 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
5961 * that button, unless the button (or its parent widget) is passed in here.
5962 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
5963 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
5965 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
5966 // Configuration initialization
5967 config
= config
|| {};
5969 // Parent constructor
5970 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
5972 // Mixin constructors
5973 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
5976 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
5977 this.filterFromInput
= !!config
.filterFromInput
;
5978 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
5979 this.$widget
= config
.widget
? config
.widget
.$element
: null;
5980 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
5981 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
5985 .addClass( 'oo-ui-menuSelectWidget' )
5986 .attr( 'role', 'menu' );
5988 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
5989 // that reference properties not initialized at that time of parent class construction
5990 // TODO: Find a better way to handle post-constructor setup
5991 this.visible
= false;
5992 this.$element
.addClass( 'oo-ui-element-hidden' );
5997 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
5998 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
6003 * Handles document mouse down events.
6006 * @param {MouseEvent} e Mouse down event
6008 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
6010 !OO
.ui
.contains( this.$element
[ 0 ], e
.target
, true ) &&
6011 ( !this.$widget
|| !OO
.ui
.contains( this.$widget
[ 0 ], e
.target
, true ) )
6013 this.toggle( false );
6020 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
6021 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
6023 if ( !this.isDisabled() && this.isVisible() ) {
6024 switch ( e
.keyCode
) {
6025 case OO
.ui
.Keys
.LEFT
:
6026 case OO
.ui
.Keys
.RIGHT
:
6027 // Do nothing if a text field is associated, arrow keys will be handled natively
6028 if ( !this.$input
) {
6029 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
6032 case OO
.ui
.Keys
.ESCAPE
:
6033 case OO
.ui
.Keys
.TAB
:
6034 if ( currentItem
) {
6035 currentItem
.setHighlighted( false );
6037 this.toggle( false );
6038 // Don't prevent tabbing away, prevent defocusing
6039 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
6041 e
.stopPropagation();
6045 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
6052 * Update menu item visibility after input changes.
6056 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
6058 len
= this.items
.length
,
6059 showAll
= !this.isVisible(),
6060 filter
= showAll
? null : this.getItemMatcher( this.$input
.val() );
6062 for ( i
= 0; i
< len
; i
++ ) {
6063 item
= this.items
[ i
];
6064 if ( item
instanceof OO
.ui
.OptionWidget
) {
6065 item
.toggle( showAll
|| filter( item
) );
6069 // Reevaluate clipping
6076 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
6077 if ( this.$input
) {
6078 this.$input
.on( 'keydown', this.onKeyDownHandler
);
6080 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyDownListener
.call( this );
6087 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
6088 if ( this.$input
) {
6089 this.$input
.off( 'keydown', this.onKeyDownHandler
);
6091 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyDownListener
.call( this );
6098 OO
.ui
.MenuSelectWidget
.prototype.bindKeyPressListener = function () {
6099 if ( this.$input
) {
6100 if ( this.filterFromInput
) {
6101 this.$input
.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
6104 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyPressListener
.call( this );
6111 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyPressListener = function () {
6112 if ( this.$input
) {
6113 if ( this.filterFromInput
) {
6114 this.$input
.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
6115 this.updateItemVisibility();
6118 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyPressListener
.call( this );
6125 * When a user chooses an item, the menu is closed.
6127 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
6128 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
6130 * @param {OO.ui.OptionWidget} item Item to choose
6133 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
6134 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
6135 this.toggle( false );
6142 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
6144 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
6146 // Reevaluate clipping
6155 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
6157 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
6159 // Reevaluate clipping
6168 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
6170 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
6172 // Reevaluate clipping
6181 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
6184 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
6185 change
= visible
!== this.isVisible();
6188 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
6192 this.bindKeyDownListener();
6193 this.bindKeyPressListener();
6195 this.toggleClipping( true );
6197 if ( this.getSelectedItem() ) {
6198 this.getSelectedItem().scrollElementIntoView( { duration
: 0 } );
6202 if ( this.autoHide
) {
6203 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
6206 this.unbindKeyDownListener();
6207 this.unbindKeyPressListener();
6208 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
6209 this.toggleClipping( false );
6217 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
6218 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
6219 * users can interact with it.
6221 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
6222 * OO.ui.DropdownInputWidget instead.
6225 * // Example: A DropdownWidget with a menu that contains three options
6226 * var dropDown = new OO.ui.DropdownWidget( {
6227 * label: 'Dropdown menu: Select a menu option',
6230 * new OO.ui.MenuOptionWidget( {
6234 * new OO.ui.MenuOptionWidget( {
6238 * new OO.ui.MenuOptionWidget( {
6246 * $( 'body' ).append( dropDown.$element );
6248 * dropDown.getMenu().selectItemByData( 'b' );
6250 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
6252 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
6254 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
6257 * @extends OO.ui.Widget
6258 * @mixins OO.ui.mixin.IconElement
6259 * @mixins OO.ui.mixin.IndicatorElement
6260 * @mixins OO.ui.mixin.LabelElement
6261 * @mixins OO.ui.mixin.TitledElement
6262 * @mixins OO.ui.mixin.TabIndexedElement
6265 * @param {Object} [config] Configuration options
6266 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
6267 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
6268 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
6269 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
6271 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
6272 // Configuration initialization
6273 config
= $.extend( { indicator
: 'down' }, config
);
6275 // Parent constructor
6276 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
6278 // Properties (must be set before TabIndexedElement constructor call)
6279 this.$handle
= this.$( '<span>' );
6280 this.$overlay
= config
.$overlay
|| this.$element
;
6282 // Mixin constructors
6283 OO
.ui
.mixin
.IconElement
.call( this, config
);
6284 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
6285 OO
.ui
.mixin
.LabelElement
.call( this, config
);
6286 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
6287 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
6290 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend( {
6292 $container
: this.$element
6297 click
: this.onClick
.bind( this ),
6298 keydown
: this.onKeyDown
.bind( this )
6300 this.menu
.connect( this, { select
: 'onMenuSelect' } );
6304 .addClass( 'oo-ui-dropdownWidget-handle' )
6305 .append( this.$icon
, this.$label
, this.$indicator
);
6307 .addClass( 'oo-ui-dropdownWidget' )
6308 .append( this.$handle
);
6309 this.$overlay
.append( this.menu
.$element
);
6314 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
6315 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
6316 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
6317 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
6318 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
6319 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
6326 * @return {OO.ui.MenuSelectWidget} Menu of widget
6328 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
6333 * Handles menu select events.
6336 * @param {OO.ui.MenuOptionWidget} item Selected menu item
6338 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
6342 this.setLabel( null );
6346 selectedLabel
= item
.getLabel();
6348 // If the label is a DOM element, clone it, because setLabel will append() it
6349 if ( selectedLabel
instanceof jQuery
) {
6350 selectedLabel
= selectedLabel
.clone();
6353 this.setLabel( selectedLabel
);
6357 * Handle mouse click events.
6360 * @param {jQuery.Event} e Mouse click event
6362 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
6363 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
6370 * Handle key down events.
6373 * @param {jQuery.Event} e Key down event
6375 OO
.ui
.DropdownWidget
.prototype.onKeyDown = function ( e
) {
6377 !this.isDisabled() &&
6379 e
.which
=== OO
.ui
.Keys
.ENTER
||
6381 !this.menu
.isVisible() &&
6383 e
.which
=== OO
.ui
.Keys
.SPACE
||
6384 e
.which
=== OO
.ui
.Keys
.UP
||
6385 e
.which
=== OO
.ui
.Keys
.DOWN
6396 * RadioOptionWidget is an option widget that looks like a radio button.
6397 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
6398 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6400 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
6403 * @extends OO.ui.OptionWidget
6406 * @param {Object} [config] Configuration options
6408 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
6409 // Configuration initialization
6410 config
= config
|| {};
6412 // Properties (must be done before parent constructor which calls #setDisabled)
6413 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
6415 // Parent constructor
6416 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
6419 this.radio
.$input
.on( 'focus', this.onInputFocus
.bind( this ) );
6422 // Remove implicit role, we're handling it ourselves
6423 this.radio
.$input
.attr( 'role', 'presentation' );
6425 .addClass( 'oo-ui-radioOptionWidget' )
6426 .attr( 'role', 'radio' )
6427 .attr( 'aria-checked', 'false' )
6428 .removeAttr( 'aria-selected' )
6429 .prepend( this.radio
.$element
);
6434 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
6436 /* Static Properties */
6438 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
6440 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
6442 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
6444 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
6449 * @param {jQuery.Event} e Focus event
6452 OO
.ui
.RadioOptionWidget
.prototype.onInputFocus = function () {
6453 this.radio
.$input
.blur();
6454 this.$element
.parent().focus();
6460 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
6461 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
6463 this.radio
.setSelected( state
);
6465 .attr( 'aria-checked', state
.toString() )
6466 .removeAttr( 'aria-selected' );
6474 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
6475 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
6477 this.radio
.setDisabled( this.isDisabled() );
6483 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
6484 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
6485 * an interface for adding, removing and selecting options.
6486 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
6488 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
6489 * OO.ui.RadioSelectInputWidget instead.
6492 * // A RadioSelectWidget with RadioOptions.
6493 * var option1 = new OO.ui.RadioOptionWidget( {
6495 * label: 'Selected radio option'
6498 * var option2 = new OO.ui.RadioOptionWidget( {
6500 * label: 'Unselected radio option'
6503 * var radioSelect=new OO.ui.RadioSelectWidget( {
6504 * items: [ option1, option2 ]
6507 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
6508 * radioSelect.selectItem( option1 );
6510 * $( 'body' ).append( radioSelect.$element );
6512 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6516 * @extends OO.ui.SelectWidget
6517 * @mixins OO.ui.mixin.TabIndexedElement
6520 * @param {Object} [config] Configuration options
6522 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
6523 // Parent constructor
6524 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
6526 // Mixin constructors
6527 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
6531 focus
: this.bindKeyDownListener
.bind( this ),
6532 blur
: this.unbindKeyDownListener
.bind( this )
6537 .addClass( 'oo-ui-radioSelectWidget' )
6538 .attr( 'role', 'radiogroup' );
6543 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
6544 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
6547 * Element that will stick under a specified container, even when it is inserted elsewhere in the
6548 * document (for example, in a OO.ui.Window's $overlay).
6550 * The elements's position is automatically calculated and maintained when window is resized or the
6551 * page is scrolled. If you reposition the container manually, you have to call #position to make
6552 * sure the element is still placed correctly.
6554 * As positioning is only possible when both the element and the container are attached to the DOM
6555 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
6556 * the #toggle method to display a floating popup, for example.
6562 * @param {Object} [config] Configuration options
6563 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
6564 * @cfg {jQuery} [$floatableContainer] Node to position below
6566 OO
.ui
.mixin
.FloatableElement
= function OoUiMixinFloatableElement( config
) {
6567 // Configuration initialization
6568 config
= config
|| {};
6571 this.$floatable
= null;
6572 this.$floatableContainer
= null;
6573 this.$floatableWindow
= null;
6574 this.$floatableClosestScrollable
= null;
6575 this.onFloatableScrollHandler
= this.position
.bind( this );
6576 this.onFloatableWindowResizeHandler
= this.position
.bind( this );
6579 this.setFloatableContainer( config
.$floatableContainer
);
6580 this.setFloatableElement( config
.$floatable
|| this.$element
);
6586 * Set floatable element.
6588 * If an element is already set, it will be cleaned up before setting up the new element.
6590 * @param {jQuery} $floatable Element to make floatable
6592 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableElement = function ( $floatable
) {
6593 if ( this.$floatable
) {
6594 this.$floatable
.removeClass( 'oo-ui-floatableElement-floatable' );
6595 this.$floatable
.css( { left
: '', top
: '' } );
6598 this.$floatable
= $floatable
.addClass( 'oo-ui-floatableElement-floatable' );
6603 * Set floatable container.
6605 * The element will be always positioned under the specified container.
6607 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
6609 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableContainer = function ( $floatableContainer
) {
6610 this.$floatableContainer
= $floatableContainer
;
6611 if ( this.$floatable
) {
6617 * Toggle positioning.
6619 * Do not turn positioning on until after the element is attached to the DOM and visible.
6621 * @param {boolean} [positioning] Enable positioning, omit to toggle
6624 OO
.ui
.mixin
.FloatableElement
.prototype.togglePositioning = function ( positioning
) {
6625 var closestScrollableOfContainer
, closestScrollableOfFloatable
;
6627 positioning
= positioning
=== undefined ? !this.positioning
: !!positioning
;
6629 if ( this.positioning
!== positioning
) {
6630 this.positioning
= positioning
;
6632 closestScrollableOfContainer
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatableContainer
[ 0 ] );
6633 closestScrollableOfFloatable
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatable
[ 0 ] );
6634 this.needsCustomPosition
= closestScrollableOfContainer
!== closestScrollableOfFloatable
;
6635 // If the scrollable is the root, we have to listen to scroll events
6636 // on the window because of browser inconsistencies.
6637 if ( $( closestScrollableOfContainer
).is( 'html, body' ) ) {
6638 closestScrollableOfContainer
= OO
.ui
.Element
.static.getWindow( closestScrollableOfContainer
);
6641 if ( positioning
) {
6642 this.$floatableWindow
= $( this.getElementWindow() );
6643 this.$floatableWindow
.on( 'resize', this.onFloatableWindowResizeHandler
);
6645 this.$floatableClosestScrollable
= $( closestScrollableOfContainer
);
6646 this.$floatableClosestScrollable
.on( 'scroll', this.onFloatableScrollHandler
);
6648 // Initial position after visible
6651 if ( this.$floatableWindow
) {
6652 this.$floatableWindow
.off( 'resize', this.onFloatableWindowResizeHandler
);
6653 this.$floatableWindow
= null;
6656 if ( this.$floatableClosestScrollable
) {
6657 this.$floatableClosestScrollable
.off( 'scroll', this.onFloatableScrollHandler
);
6658 this.$floatableClosestScrollable
= null;
6661 this.$floatable
.css( { left
: '', top
: '' } );
6669 * Check whether the bottom edge of the given element is within the viewport of the given container.
6672 * @param {jQuery} $element
6673 * @param {jQuery} $container
6676 OO
.ui
.mixin
.FloatableElement
.prototype.isElementInViewport = function ( $element
, $container
) {
6677 var elemRect
, contRect
,
6678 topEdgeInBounds
= false,
6679 leftEdgeInBounds
= false,
6680 bottomEdgeInBounds
= false,
6681 rightEdgeInBounds
= false;
6683 elemRect
= $element
[ 0 ].getBoundingClientRect();
6684 if ( $container
[ 0 ] === window
) {
6688 right
: document
.documentElement
.clientWidth
,
6689 bottom
: document
.documentElement
.clientHeight
6692 contRect
= $container
[ 0 ].getBoundingClientRect();
6695 if ( elemRect
.top
>= contRect
.top
&& elemRect
.top
<= contRect
.bottom
) {
6696 topEdgeInBounds
= true;
6698 if ( elemRect
.left
>= contRect
.left
&& elemRect
.left
<= contRect
.right
) {
6699 leftEdgeInBounds
= true;
6701 if ( elemRect
.bottom
>= contRect
.top
&& elemRect
.bottom
<= contRect
.bottom
) {
6702 bottomEdgeInBounds
= true;
6704 if ( elemRect
.right
>= contRect
.left
&& elemRect
.right
<= contRect
.right
) {
6705 rightEdgeInBounds
= true;
6708 // We only care that any part of the bottom edge is visible
6709 return bottomEdgeInBounds
&& ( leftEdgeInBounds
|| rightEdgeInBounds
);
6713 * Position the floatable below its container.
6715 * This should only be done when both of them are attached to the DOM and visible.
6719 OO
.ui
.mixin
.FloatableElement
.prototype.position = function () {
6722 if ( !this.positioning
) {
6726 if ( !this.isElementInViewport( this.$floatableContainer
, this.$floatableClosestScrollable
) ) {
6727 this.$floatable
.addClass( 'oo-ui-floatableElement-hidden' );
6730 this.$floatable
.removeClass( 'oo-ui-floatableElement-hidden' );
6733 if ( !this.needsCustomPosition
) {
6737 pos
= OO
.ui
.Element
.static.getRelativePosition( this.$floatableContainer
, this.$floatable
.offsetParent() );
6739 // Position under container
6740 pos
.top
+= this.$floatableContainer
.height();
6741 this.$floatable
.css( pos
);
6743 // We updated the position, so re-evaluate the clipping state.
6744 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
6745 // will not notice the need to update itself.)
6746 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
6747 // it not listen to the right events in the right places?
6756 * FloatingMenuSelectWidget is a menu that will stick under a specified
6757 * container, even when it is inserted elsewhere in the document (for example,
6758 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
6759 * menu from being clipped too aggresively.
6761 * The menu's position is automatically calculated and maintained when the menu
6762 * is toggled or the window is resized.
6764 * See OO.ui.ComboBoxInputWidget for an example of a widget that uses this class.
6767 * @extends OO.ui.MenuSelectWidget
6768 * @mixins OO.ui.mixin.FloatableElement
6771 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
6772 * Deprecated, omit this parameter and specify `$container` instead.
6773 * @param {Object} [config] Configuration options
6774 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
6776 OO
.ui
.FloatingMenuSelectWidget
= function OoUiFloatingMenuSelectWidget( inputWidget
, config
) {
6777 // Allow 'inputWidget' parameter and config for backwards compatibility
6778 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
6779 config
= inputWidget
;
6780 inputWidget
= config
.inputWidget
;
6783 // Configuration initialization
6784 config
= config
|| {};
6786 // Parent constructor
6787 OO
.ui
.FloatingMenuSelectWidget
.parent
.call( this, config
);
6789 // Properties (must be set before mixin constructors)
6790 this.inputWidget
= inputWidget
; // For backwards compatibility
6791 this.$container
= config
.$container
|| this.inputWidget
.$element
;
6793 // Mixins constructors
6794 OO
.ui
.mixin
.FloatableElement
.call( this, $.extend( {}, config
, { $floatableContainer
: this.$container
} ) );
6797 this.$element
.addClass( 'oo-ui-floatingMenuSelectWidget' );
6798 // For backwards compatibility
6799 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
6804 OO
.inheritClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
6805 OO
.mixinClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.mixin
.FloatableElement
);
6807 // For backwards compatibility
6808 OO
.ui
.TextInputMenuSelectWidget
= OO
.ui
.FloatingMenuSelectWidget
;
6815 OO
.ui
.FloatingMenuSelectWidget
.prototype.toggle = function ( visible
) {
6817 visible
= visible
=== undefined ? !this.isVisible() : !!visible
;
6818 change
= visible
!== this.isVisible();
6820 if ( change
&& visible
) {
6821 // Make sure the width is set before the parent method runs.
6822 this.setIdealSize( this.$container
.width() );
6826 // This will call this.clip(), which is nonsensical since we're not positioned yet...
6827 OO
.ui
.FloatingMenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
6830 this.togglePositioning( this.isVisible() );
6837 * InputWidget is the base class for all input widgets, which
6838 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
6839 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
6840 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
6842 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
6846 * @extends OO.ui.Widget
6847 * @mixins OO.ui.mixin.FlaggedElement
6848 * @mixins OO.ui.mixin.TabIndexedElement
6849 * @mixins OO.ui.mixin.TitledElement
6850 * @mixins OO.ui.mixin.AccessKeyedElement
6853 * @param {Object} [config] Configuration options
6854 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
6855 * @cfg {string} [value=''] The value of the input.
6856 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
6857 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
6858 * before it is accepted.
6860 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
6861 // Configuration initialization
6862 config
= config
|| {};
6864 // Parent constructor
6865 OO
.ui
.InputWidget
.parent
.call( this, config
);
6868 // See #reusePreInfuseDOM about config.$input
6869 this.$input
= config
.$input
|| this.getInputElement( config
);
6871 this.inputFilter
= config
.inputFilter
;
6873 // Mixin constructors
6874 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
6875 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
6876 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
6877 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$input
} ) );
6880 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
6884 .addClass( 'oo-ui-inputWidget-input' )
6885 .attr( 'name', config
.name
)
6886 .prop( 'disabled', this.isDisabled() );
6888 .addClass( 'oo-ui-inputWidget' )
6889 .append( this.$input
);
6890 this.setValue( config
.value
);
6892 this.setDir( config
.dir
);
6898 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
6899 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
6900 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
6901 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
6902 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
6904 /* Static Properties */
6906 OO
.ui
.InputWidget
.static.supportsSimpleLabel
= true;
6908 /* Static Methods */
6913 OO
.ui
.InputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
6914 config
= OO
.ui
.InputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
6915 // Reusing $input lets browsers preserve inputted values across page reloads (T114134)
6916 config
.$input
= $( node
).find( '.oo-ui-inputWidget-input' );
6923 OO
.ui
.InputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
6924 var state
= OO
.ui
.InputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
6925 if ( config
.$input
&& config
.$input
.length
) {
6926 state
.value
= config
.$input
.val();
6927 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
6928 state
.focus
= config
.$input
.is( ':focus' );
6938 * A change event is emitted when the value of the input changes.
6940 * @param {string} value
6946 * Get input element.
6948 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
6949 * different circumstances. The element must have a `value` property (like form elements).
6952 * @param {Object} config Configuration options
6953 * @return {jQuery} Input element
6955 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
6956 return $( '<input>' );
6960 * Handle potentially value-changing events.
6963 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
6965 OO
.ui
.InputWidget
.prototype.onEdit = function () {
6967 if ( !this.isDisabled() ) {
6968 // Allow the stack to clear so the value will be updated
6969 setTimeout( function () {
6970 widget
.setValue( widget
.$input
.val() );
6976 * Get the value of the input.
6978 * @return {string} Input value
6980 OO
.ui
.InputWidget
.prototype.getValue = function () {
6981 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
6982 // it, and we won't know unless they're kind enough to trigger a 'change' event.
6983 var value
= this.$input
.val();
6984 if ( this.value
!== value
) {
6985 this.setValue( value
);
6991 * Set the directionality of the input, either RTL (right-to-left) or LTR (left-to-right).
6993 * @deprecated since v0.13.1; use #setDir directly
6994 * @param {boolean} isRTL Directionality is right-to-left
6997 OO
.ui
.InputWidget
.prototype.setRTL = function ( isRTL
) {
6998 this.setDir( isRTL
? 'rtl' : 'ltr' );
7003 * Set the directionality of the input.
7005 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
7008 OO
.ui
.InputWidget
.prototype.setDir = function ( dir
) {
7009 this.$input
.prop( 'dir', dir
);
7014 * Set the value of the input.
7016 * @param {string} value New value
7020 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
7021 value
= this.cleanUpValue( value
);
7022 // Update the DOM if it has changed. Note that with cleanUpValue, it
7023 // is possible for the DOM value to change without this.value changing.
7024 if ( this.$input
.val() !== value
) {
7025 this.$input
.val( value
);
7027 if ( this.value
!== value
) {
7029 this.emit( 'change', this.value
);
7035 * Clean up incoming value.
7037 * Ensures value is a string, and converts undefined and null to empty string.
7040 * @param {string} value Original value
7041 * @return {string} Cleaned up value
7043 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
7044 if ( value
=== undefined || value
=== null ) {
7046 } else if ( this.inputFilter
) {
7047 return this.inputFilter( String( value
) );
7049 return String( value
);
7054 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
7055 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
7058 OO
.ui
.InputWidget
.prototype.simulateLabelClick = function () {
7059 if ( !this.isDisabled() ) {
7060 if ( this.$input
.is( ':checkbox, :radio' ) ) {
7061 this.$input
.click();
7063 if ( this.$input
.is( ':input' ) ) {
7064 this.$input
[ 0 ].focus();
7072 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
7073 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
7074 if ( this.$input
) {
7075 this.$input
.prop( 'disabled', this.isDisabled() );
7085 OO
.ui
.InputWidget
.prototype.focus = function () {
7086 this.$input
[ 0 ].focus();
7095 OO
.ui
.InputWidget
.prototype.blur = function () {
7096 this.$input
[ 0 ].blur();
7103 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
7104 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
7105 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
7106 this.setValue( state
.value
);
7108 if ( state
.focus
) {
7114 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
7115 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
7116 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
7117 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
7118 * [OOjs UI documentation on MediaWiki] [1] for more information.
7121 * // A ButtonInputWidget rendered as an HTML button, the default.
7122 * var button = new OO.ui.ButtonInputWidget( {
7123 * label: 'Input button',
7127 * $( 'body' ).append( button.$element );
7129 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
7132 * @extends OO.ui.InputWidget
7133 * @mixins OO.ui.mixin.ButtonElement
7134 * @mixins OO.ui.mixin.IconElement
7135 * @mixins OO.ui.mixin.IndicatorElement
7136 * @mixins OO.ui.mixin.LabelElement
7137 * @mixins OO.ui.mixin.TitledElement
7140 * @param {Object} [config] Configuration options
7141 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
7142 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
7143 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
7144 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
7145 * be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
7147 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
7148 // Configuration initialization
7149 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
7151 // See InputWidget#reusePreInfuseDOM about config.$input
7152 if ( config
.$input
) {
7153 config
.$input
.empty();
7156 // Properties (must be set before parent constructor, which calls #setValue)
7157 this.useInputTag
= config
.useInputTag
;
7159 // Parent constructor
7160 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
7162 // Mixin constructors
7163 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
7164 OO
.ui
.mixin
.IconElement
.call( this, config
);
7165 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
7166 OO
.ui
.mixin
.LabelElement
.call( this, config
);
7167 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
7170 if ( !config
.useInputTag
) {
7171 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
7173 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
7178 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
7179 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
7180 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
7181 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
7182 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
7183 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
7185 /* Static Properties */
7188 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
7189 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
7191 OO
.ui
.ButtonInputWidget
.static.supportsSimpleLabel
= false;
7199 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
7201 type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ? config
.type
: 'button';
7202 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
7208 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
7210 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
7211 * text, or `null` for no label
7214 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
7215 if ( typeof label
=== 'function' ) {
7216 label
= OO
.ui
.resolveMsg( label
);
7219 if ( this.useInputTag
) {
7220 // Discard non-plaintext labels
7221 if ( typeof label
!== 'string' ) {
7225 this.$input
.val( label
);
7228 return OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
7232 * Set the value of the input.
7234 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
7235 * they do not support {@link #value values}.
7237 * @param {string} value New value
7240 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
7241 if ( !this.useInputTag
) {
7242 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
7248 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
7249 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
7250 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
7251 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
7253 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
7256 * // An example of selected, unselected, and disabled checkbox inputs
7257 * var checkbox1=new OO.ui.CheckboxInputWidget( {
7261 * var checkbox2=new OO.ui.CheckboxInputWidget( {
7264 * var checkbox3=new OO.ui.CheckboxInputWidget( {
7268 * // Create a fieldset layout with fields for each checkbox.
7269 * var fieldset = new OO.ui.FieldsetLayout( {
7270 * label: 'Checkboxes'
7272 * fieldset.addItems( [
7273 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
7274 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
7275 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
7277 * $( 'body' ).append( fieldset.$element );
7279 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7282 * @extends OO.ui.InputWidget
7285 * @param {Object} [config] Configuration options
7286 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
7288 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
7289 // Configuration initialization
7290 config
= config
|| {};
7292 // Parent constructor
7293 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
7297 .addClass( 'oo-ui-checkboxInputWidget' )
7298 // Required for pretty styling in MediaWiki theme
7299 .append( $( '<span>' ) );
7300 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
7305 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
7307 /* Static Methods */
7312 OO
.ui
.CheckboxInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
7313 var state
= OO
.ui
.CheckboxInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
7314 state
.checked
= config
.$input
.prop( 'checked' );
7324 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
7325 return $( '<input>' ).attr( 'type', 'checkbox' );
7331 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
7333 if ( !this.isDisabled() ) {
7334 // Allow the stack to clear so the value will be updated
7335 setTimeout( function () {
7336 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
7342 * Set selection state of this checkbox.
7344 * @param {boolean} state `true` for selected
7347 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
7349 if ( this.selected
!== state
) {
7350 this.selected
= state
;
7351 this.$input
.prop( 'checked', this.selected
);
7352 this.emit( 'change', this.selected
);
7358 * Check if this checkbox is selected.
7360 * @return {boolean} Checkbox is selected
7362 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
7363 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
7364 // it, and we won't know unless they're kind enough to trigger a 'change' event.
7365 var selected
= this.$input
.prop( 'checked' );
7366 if ( this.selected
!== selected
) {
7367 this.setSelected( selected
);
7369 return this.selected
;
7375 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
7376 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
7377 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
7378 this.setSelected( state
.checked
);
7383 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
7384 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
7385 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
7386 * more information about input widgets.
7388 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
7389 * are no options. If no `value` configuration option is provided, the first option is selected.
7390 * If you need a state representing no value (no option being selected), use a DropdownWidget.
7392 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
7395 * // Example: A DropdownInputWidget with three options
7396 * var dropdownInput = new OO.ui.DropdownInputWidget( {
7398 * { data: 'a', label: 'First' },
7399 * { data: 'b', label: 'Second'},
7400 * { data: 'c', label: 'Third' }
7403 * $( 'body' ).append( dropdownInput.$element );
7405 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7408 * @extends OO.ui.InputWidget
7409 * @mixins OO.ui.mixin.TitledElement
7412 * @param {Object} [config] Configuration options
7413 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
7414 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
7416 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
7417 // Configuration initialization
7418 config
= config
|| {};
7420 // See InputWidget#reusePreInfuseDOM about config.$input
7421 if ( config
.$input
) {
7422 config
.$input
.addClass( 'oo-ui-element-hidden' );
7425 // Properties (must be done before parent constructor which calls #setDisabled)
7426 this.dropdownWidget
= new OO
.ui
.DropdownWidget( config
.dropdown
);
7428 // Parent constructor
7429 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
7431 // Mixin constructors
7432 OO
.ui
.mixin
.TitledElement
.call( this, config
);
7435 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
7438 this.setOptions( config
.options
|| [] );
7440 .addClass( 'oo-ui-dropdownInputWidget' )
7441 .append( this.dropdownWidget
.$element
);
7446 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
7447 OO
.mixinClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.mixin
.TitledElement
);
7455 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
7456 return $( '<input>' ).attr( 'type', 'hidden' );
7460 * Handles menu select events.
7463 * @param {OO.ui.MenuOptionWidget} item Selected menu item
7465 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
7466 this.setValue( item
.getData() );
7472 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
7473 value
= this.cleanUpValue( value
);
7474 this.dropdownWidget
.getMenu().selectItemByData( value
);
7475 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
7482 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
7483 this.dropdownWidget
.setDisabled( state
);
7484 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
7489 * Set the options available for this input.
7491 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
7494 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
7496 value
= this.getValue(),
7499 // Rebuild the dropdown menu
7500 this.dropdownWidget
.getMenu()
7502 .addItems( options
.map( function ( opt
) {
7503 var optValue
= widget
.cleanUpValue( opt
.data
);
7504 return new OO
.ui
.MenuOptionWidget( {
7506 label
: opt
.label
!== undefined ? opt
.label
: optValue
7510 // Restore the previous value, or reset to something sensible
7511 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
7512 // Previous value is still available, ensure consistency with the dropdown
7513 this.setValue( value
);
7515 // No longer valid, reset
7516 if ( options
.length
) {
7517 this.setValue( options
[ 0 ].data
);
7527 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
7528 this.dropdownWidget
.getMenu().toggle( true );
7535 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
7536 this.dropdownWidget
.getMenu().toggle( false );
7541 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
7542 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
7543 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
7544 * please see the [OOjs UI documentation on MediaWiki][1].
7546 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
7549 * // An example of selected, unselected, and disabled radio inputs
7550 * var radio1 = new OO.ui.RadioInputWidget( {
7554 * var radio2 = new OO.ui.RadioInputWidget( {
7557 * var radio3 = new OO.ui.RadioInputWidget( {
7561 * // Create a fieldset layout with fields for each radio button.
7562 * var fieldset = new OO.ui.FieldsetLayout( {
7563 * label: 'Radio inputs'
7565 * fieldset.addItems( [
7566 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
7567 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
7568 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
7570 * $( 'body' ).append( fieldset.$element );
7572 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7575 * @extends OO.ui.InputWidget
7578 * @param {Object} [config] Configuration options
7579 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
7581 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
7582 // Configuration initialization
7583 config
= config
|| {};
7585 // Parent constructor
7586 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
7590 .addClass( 'oo-ui-radioInputWidget' )
7591 // Required for pretty styling in MediaWiki theme
7592 .append( $( '<span>' ) );
7593 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
7598 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
7600 /* Static Methods */
7605 OO
.ui
.RadioInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
7606 var state
= OO
.ui
.RadioInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
7607 state
.checked
= config
.$input
.prop( 'checked' );
7617 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
7618 return $( '<input>' ).attr( 'type', 'radio' );
7624 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
7625 // RadioInputWidget doesn't track its state.
7629 * Set selection state of this radio button.
7631 * @param {boolean} state `true` for selected
7634 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
7635 // RadioInputWidget doesn't track its state.
7636 this.$input
.prop( 'checked', state
);
7641 * Check if this radio button is selected.
7643 * @return {boolean} Radio is selected
7645 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
7646 return this.$input
.prop( 'checked' );
7652 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
7653 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
7654 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
7655 this.setSelected( state
.checked
);
7660 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
7661 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
7662 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
7663 * more information about input widgets.
7665 * This and OO.ui.DropdownInputWidget support the same configuration options.
7668 * // Example: A RadioSelectInputWidget with three options
7669 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
7671 * { data: 'a', label: 'First' },
7672 * { data: 'b', label: 'Second'},
7673 * { data: 'c', label: 'Third' }
7676 * $( 'body' ).append( radioSelectInput.$element );
7678 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7681 * @extends OO.ui.InputWidget
7684 * @param {Object} [config] Configuration options
7685 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
7687 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
7688 // Configuration initialization
7689 config
= config
|| {};
7691 // Properties (must be done before parent constructor which calls #setDisabled)
7692 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
7694 // Parent constructor
7695 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
7698 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
7701 this.setOptions( config
.options
|| [] );
7703 .addClass( 'oo-ui-radioSelectInputWidget' )
7704 .append( this.radioSelectWidget
.$element
);
7709 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
7711 /* Static Properties */
7713 OO
.ui
.RadioSelectInputWidget
.static.supportsSimpleLabel
= false;
7715 /* Static Methods */
7720 OO
.ui
.RadioSelectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
7721 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
7722 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
7729 OO
.ui
.RadioSelectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
7730 config
= OO
.ui
.RadioSelectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
7731 // Cannot reuse the `<input type=radio>` set
7732 delete config
.$input
;
7742 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
7743 return $( '<input>' ).attr( 'type', 'hidden' );
7747 * Handles menu select events.
7750 * @param {OO.ui.RadioOptionWidget} item Selected menu item
7752 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
7753 this.setValue( item
.getData() );
7759 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
7760 value
= this.cleanUpValue( value
);
7761 this.radioSelectWidget
.selectItemByData( value
);
7762 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
7769 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
7770 this.radioSelectWidget
.setDisabled( state
);
7771 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
7776 * Set the options available for this input.
7778 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
7781 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
7783 value
= this.getValue(),
7786 // Rebuild the radioSelect menu
7787 this.radioSelectWidget
7789 .addItems( options
.map( function ( opt
) {
7790 var optValue
= widget
.cleanUpValue( opt
.data
);
7791 return new OO
.ui
.RadioOptionWidget( {
7793 label
: opt
.label
!== undefined ? opt
.label
: optValue
7797 // Restore the previous value, or reset to something sensible
7798 if ( this.radioSelectWidget
.getItemFromData( value
) ) {
7799 // Previous value is still available, ensure consistency with the radioSelect
7800 this.setValue( value
);
7802 // No longer valid, reset
7803 if ( options
.length
) {
7804 this.setValue( options
[ 0 ].data
);
7812 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
7813 * size of the field as well as its presentation. In addition, these widgets can be configured
7814 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
7815 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
7816 * which modifies incoming values rather than validating them.
7817 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
7819 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
7822 * // Example of a text input widget
7823 * var textInput = new OO.ui.TextInputWidget( {
7824 * value: 'Text input'
7826 * $( 'body' ).append( textInput.$element );
7828 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7831 * @extends OO.ui.InputWidget
7832 * @mixins OO.ui.mixin.IconElement
7833 * @mixins OO.ui.mixin.IndicatorElement
7834 * @mixins OO.ui.mixin.PendingElement
7835 * @mixins OO.ui.mixin.LabelElement
7838 * @param {Object} [config] Configuration options
7839 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
7840 * 'email', 'url' or 'date'. Ignored if `multiline` is true.
7842 * Some values of `type` result in additional behaviors:
7844 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
7845 * empties the text field
7846 * @cfg {string} [placeholder] Placeholder text
7847 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
7848 * instruct the browser to focus this widget.
7849 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
7850 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
7851 * @cfg {boolean} [multiline=false] Allow multiple lines of text
7852 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
7853 * specifies minimum number of rows to display.
7854 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
7855 * Use the #maxRows config to specify a maximum number of displayed rows.
7856 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
7857 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
7858 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
7859 * the value or placeholder text: `'before'` or `'after'`
7860 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
7861 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
7862 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
7863 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
7864 * (the value must contain only numbers); when RegExp, a regular expression that must match the
7865 * value for it to be considered valid; when Function, a function receiving the value as parameter
7866 * that must return true, or promise resolving to true, for it to be considered valid.
7868 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
7869 // Configuration initialization
7870 config
= $.extend( {
7872 labelPosition
: 'after'
7874 if ( config
.type
=== 'search' ) {
7875 if ( config
.icon
=== undefined ) {
7876 config
.icon
= 'search';
7878 // indicator: 'clear' is set dynamically later, depending on value
7880 if ( config
.required
) {
7881 if ( config
.indicator
=== undefined ) {
7882 config
.indicator
= 'required';
7886 // Parent constructor
7887 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
7889 // Mixin constructors
7890 OO
.ui
.mixin
.IconElement
.call( this, config
);
7891 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
7892 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
7893 OO
.ui
.mixin
.LabelElement
.call( this, config
);
7896 this.type
= this.getSaneType( config
);
7897 this.readOnly
= false;
7898 this.multiline
= !!config
.multiline
;
7899 this.autosize
= !!config
.autosize
;
7900 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
7901 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
7902 this.validate
= null;
7903 this.styleHeight
= null;
7904 this.scrollWidth
= null;
7906 // Clone for resizing
7907 if ( this.autosize
) {
7908 this.$clone
= this.$input
7910 .insertAfter( this.$input
)
7911 .attr( 'aria-hidden', 'true' )
7912 .addClass( 'oo-ui-element-hidden' );
7915 this.setValidation( config
.validate
);
7916 this.setLabelPosition( config
.labelPosition
);
7920 keypress
: this.onKeyPress
.bind( this ),
7921 blur
: this.onBlur
.bind( this )
7924 focus
: this.onElementAttach
.bind( this )
7926 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
7927 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
7928 this.on( 'labelChange', this.updatePosition
.bind( this ) );
7929 this.connect( this, {
7931 disable
: 'onDisable'
7936 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
7937 .append( this.$icon
, this.$indicator
);
7938 this.setReadOnly( !!config
.readOnly
);
7939 this.updateSearchIndicator();
7940 if ( config
.placeholder
!== undefined ) {
7941 this.$input
.attr( 'placeholder', config
.placeholder
);
7943 if ( config
.maxLength
!== undefined ) {
7944 this.$input
.attr( 'maxlength', config
.maxLength
);
7946 if ( config
.autofocus
) {
7947 this.$input
.attr( 'autofocus', 'autofocus' );
7949 if ( config
.required
) {
7950 this.$input
.attr( 'required', 'required' );
7951 this.$input
.attr( 'aria-required', 'true' );
7953 if ( config
.autocomplete
=== false ) {
7954 this.$input
.attr( 'autocomplete', 'off' );
7955 // Turning off autocompletion also disables "form caching" when the user navigates to a
7956 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
7958 beforeunload: function () {
7959 this.$input
.removeAttr( 'autocomplete' );
7961 pageshow: function () {
7962 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
7963 // whole page... it shouldn't hurt, though.
7964 this.$input
.attr( 'autocomplete', 'off' );
7968 if ( this.multiline
&& config
.rows
) {
7969 this.$input
.attr( 'rows', config
.rows
);
7971 if ( this.label
|| config
.autosize
) {
7972 this.installParentChangeDetector();
7978 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
7979 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
7980 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
7981 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
7982 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
7984 /* Static Properties */
7986 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
7991 /* Static Methods */
7996 OO
.ui
.TextInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
7997 var state
= OO
.ui
.TextInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
7998 if ( config
.multiline
) {
7999 state
.scrollTop
= config
.$input
.scrollTop();
8007 * An `enter` event is emitted when the user presses 'enter' inside the text box.
8009 * Not emitted if the input is multiline.
8015 * A `resize` event is emitted when autosize is set and the widget resizes
8023 * Handle icon mouse down events.
8026 * @param {jQuery.Event} e Mouse down event
8029 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
8030 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
8031 this.$input
[ 0 ].focus();
8037 * Handle indicator mouse down events.
8040 * @param {jQuery.Event} e Mouse down event
8043 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
8044 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
8045 if ( this.type
=== 'search' ) {
8046 // Clear the text field
8047 this.setValue( '' );
8049 this.$input
[ 0 ].focus();
8055 * Handle key press events.
8058 * @param {jQuery.Event} e Key press event
8059 * @fires enter If enter key is pressed and input is not multiline
8061 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
8062 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
8063 this.emit( 'enter', e
);
8068 * Handle blur events.
8071 * @param {jQuery.Event} e Blur event
8073 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
8074 this.setValidityFlag();
8078 * Handle element attach events.
8081 * @param {jQuery.Event} e Element attach event
8083 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
8084 // Any previously calculated size is now probably invalid if we reattached elsewhere
8085 this.valCache
= null;
8087 this.positionLabel();
8091 * Handle change events.
8093 * @param {string} value
8096 OO
.ui
.TextInputWidget
.prototype.onChange = function () {
8097 this.updateSearchIndicator();
8098 this.setValidityFlag();
8103 * Handle disable events.
8105 * @param {boolean} disabled Element is disabled
8108 OO
.ui
.TextInputWidget
.prototype.onDisable = function () {
8109 this.updateSearchIndicator();
8113 * Check if the input is {@link #readOnly read-only}.
8117 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
8118 return this.readOnly
;
8122 * Set the {@link #readOnly read-only} state of the input.
8124 * @param {boolean} state Make input read-only
8127 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
8128 this.readOnly
= !!state
;
8129 this.$input
.prop( 'readOnly', this.readOnly
);
8130 this.updateSearchIndicator();
8135 * Support function for making #onElementAttach work across browsers.
8137 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
8138 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
8140 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
8141 * first time that the element gets attached to the documented.
8143 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
8144 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
8145 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
8148 if ( MutationObserver
) {
8149 // The new way. If only it wasn't so ugly.
8151 if ( this.$element
.closest( 'html' ).length
) {
8152 // Widget is attached already, do nothing. This breaks the functionality of this function when
8153 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
8154 // would require observation of the whole document, which would hurt performance of other,
8155 // more important code.
8159 // Find topmost node in the tree
8160 topmostNode
= this.$element
[ 0 ];
8161 while ( topmostNode
.parentNode
) {
8162 topmostNode
= topmostNode
.parentNode
;
8165 // We have no way to detect the $element being attached somewhere without observing the entire
8166 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
8167 // parent node of $element, and instead detect when $element is removed from it (and thus
8168 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
8169 // doesn't get attached, we end up back here and create the parent.
8171 mutationObserver
= new MutationObserver( function ( mutations
) {
8172 var i
, j
, removedNodes
;
8173 for ( i
= 0; i
< mutations
.length
; i
++ ) {
8174 removedNodes
= mutations
[ i
].removedNodes
;
8175 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
8176 if ( removedNodes
[ j
] === topmostNode
) {
8177 setTimeout( onRemove
, 0 );
8184 onRemove = function () {
8185 // If the node was attached somewhere else, report it
8186 if ( widget
.$element
.closest( 'html' ).length
) {
8187 widget
.onElementAttach();
8189 mutationObserver
.disconnect();
8190 widget
.installParentChangeDetector();
8193 // Create a fake parent and observe it
8194 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
8195 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
8197 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
8198 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
8199 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
8204 * Automatically adjust the size of the text input.
8206 * This only affects #multiline inputs that are {@link #autosize autosized}.
8211 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
8212 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
,
8213 idealHeight
, newHeight
, scrollWidth
, property
;
8215 if ( this.multiline
&& this.$input
.val() !== this.valCache
) {
8216 if ( this.autosize
) {
8218 .val( this.$input
.val() )
8219 .attr( 'rows', this.minRows
)
8220 // Set inline height property to 0 to measure scroll height
8221 .css( 'height', 0 );
8223 this.$clone
.removeClass( 'oo-ui-element-hidden' );
8225 this.valCache
= this.$input
.val();
8227 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
8229 // Remove inline height property to measure natural heights
8230 this.$clone
.css( 'height', '' );
8231 innerHeight
= this.$clone
.innerHeight();
8232 outerHeight
= this.$clone
.outerHeight();
8234 // Measure max rows height
8236 .attr( 'rows', this.maxRows
)
8237 .css( 'height', 'auto' )
8239 maxInnerHeight
= this.$clone
.innerHeight();
8241 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
8242 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
8243 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
8244 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
8246 this.$clone
.addClass( 'oo-ui-element-hidden' );
8248 // Only apply inline height when expansion beyond natural height is needed
8249 // Use the difference between the inner and outer height as a buffer
8250 newHeight
= idealHeight
> innerHeight
? idealHeight
+ ( outerHeight
- innerHeight
) : '';
8251 if ( newHeight
!== this.styleHeight
) {
8252 this.$input
.css( 'height', newHeight
);
8253 this.styleHeight
= newHeight
;
8254 this.emit( 'resize' );
8257 scrollWidth
= this.$input
[ 0 ].offsetWidth
- this.$input
[ 0 ].clientWidth
;
8258 if ( scrollWidth
!== this.scrollWidth
) {
8259 property
= this.$element
.css( 'direction' ) === 'rtl' ? 'left' : 'right';
8261 this.$label
.css( { right
: '', left
: '' } );
8262 this.$indicator
.css( { right
: '', left
: '' } );
8264 if ( scrollWidth
) {
8265 this.$indicator
.css( property
, scrollWidth
);
8266 if ( this.labelPosition
=== 'after' ) {
8267 this.$label
.css( property
, scrollWidth
);
8271 this.scrollWidth
= scrollWidth
;
8272 this.positionLabel();
8282 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
8283 return config
.multiline
?
8285 $( '<input>' ).attr( 'type', this.getSaneType( config
) );
8289 * Get sanitized value for 'type' for given config.
8291 * @param {Object} config Configuration options
8292 * @return {string|null}
8295 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
8296 var type
= [ 'text', 'password', 'search', 'email', 'url', 'date' ].indexOf( config
.type
) !== -1 ?
8299 return config
.multiline
? 'multiline' : type
;
8303 * Check if the input supports multiple lines.
8307 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
8308 return !!this.multiline
;
8312 * Check if the input automatically adjusts its size.
8316 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
8317 return !!this.autosize
;
8321 * Focus the input and select a specified range within the text.
8323 * @param {number} from Select from offset
8324 * @param {number} [to] Select to offset, defaults to from
8327 OO
.ui
.TextInputWidget
.prototype.selectRange = function ( from, to
) {
8328 var isBackwards
, start
, end
,
8329 input
= this.$input
[ 0 ];
8333 isBackwards
= to
< from;
8334 start
= isBackwards
? to
: from;
8335 end
= isBackwards
? from : to
;
8340 input
.setSelectionRange( start
, end
, isBackwards
? 'backward' : 'forward' );
8342 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
8343 // Rather than expensively check if the input is attached every time, just check
8344 // if it was the cause of an error being thrown. If not, rethrow the error.
8345 if ( this.getElementDocument().body
.contains( input
) ) {
8353 * Get an object describing the current selection range in a directional manner
8355 * @return {Object} Object containing 'from' and 'to' offsets
8357 OO
.ui
.TextInputWidget
.prototype.getRange = function () {
8358 var input
= this.$input
[ 0 ],
8359 start
= input
.selectionStart
,
8360 end
= input
.selectionEnd
,
8361 isBackwards
= input
.selectionDirection
=== 'backward';
8364 from: isBackwards
? end
: start
,
8365 to
: isBackwards
? start
: end
8370 * Get the length of the text input value.
8372 * This could differ from the length of #getValue if the
8373 * value gets filtered
8375 * @return {number} Input length
8377 OO
.ui
.TextInputWidget
.prototype.getInputLength = function () {
8378 return this.$input
[ 0 ].value
.length
;
8382 * Focus the input and select the entire text.
8386 OO
.ui
.TextInputWidget
.prototype.select = function () {
8387 return this.selectRange( 0, this.getInputLength() );
8391 * Focus the input and move the cursor to the start.
8395 OO
.ui
.TextInputWidget
.prototype.moveCursorToStart = function () {
8396 return this.selectRange( 0 );
8400 * Focus the input and move the cursor to the end.
8404 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
8405 return this.selectRange( this.getInputLength() );
8409 * Insert new content into the input.
8411 * @param {string} content Content to be inserted
8414 OO
.ui
.TextInputWidget
.prototype.insertContent = function ( content
) {
8416 range
= this.getRange(),
8417 value
= this.getValue();
8419 start
= Math
.min( range
.from, range
.to
);
8420 end
= Math
.max( range
.from, range
.to
);
8422 this.setValue( value
.slice( 0, start
) + content
+ value
.slice( end
) );
8423 this.selectRange( start
+ content
.length
);
8428 * Insert new content either side of a selection.
8430 * @param {string} pre Content to be inserted before the selection
8431 * @param {string} post Content to be inserted after the selection
8434 OO
.ui
.TextInputWidget
.prototype.encapsulateContent = function ( pre
, post
) {
8436 range
= this.getRange(),
8437 offset
= pre
.length
;
8439 start
= Math
.min( range
.from, range
.to
);
8440 end
= Math
.max( range
.from, range
.to
);
8442 this.selectRange( start
).insertContent( pre
);
8443 this.selectRange( offset
+ end
).insertContent( post
);
8445 this.selectRange( offset
+ start
, offset
+ end
);
8450 * Set the validation pattern.
8452 * The validation pattern is either a regular expression, a function, or the symbolic name of a
8453 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
8454 * value must contain only numbers).
8456 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
8457 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
8459 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
8460 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
8461 this.validate
= validate
;
8463 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
8468 * Sets the 'invalid' flag appropriately.
8470 * @param {boolean} [isValid] Optionally override validation result
8472 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
8474 setFlag = function ( valid
) {
8476 widget
.$input
.attr( 'aria-invalid', 'true' );
8478 widget
.$input
.removeAttr( 'aria-invalid' );
8480 widget
.setFlags( { invalid
: !valid
} );
8483 if ( isValid
!== undefined ) {
8486 this.getValidity().then( function () {
8495 * Check if a value is valid.
8497 * This method returns a promise that resolves with a boolean `true` if the current value is
8498 * considered valid according to the supplied {@link #validate validation pattern}.
8500 * @deprecated since v0.12.3
8501 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
8503 OO
.ui
.TextInputWidget
.prototype.isValid = function () {
8506 if ( this.validate
instanceof Function
) {
8507 result
= this.validate( this.getValue() );
8508 if ( result
&& $.isFunction( result
.promise
) ) {
8509 return result
.promise();
8511 return $.Deferred().resolve( !!result
).promise();
8514 return $.Deferred().resolve( !!this.getValue().match( this.validate
) ).promise();
8519 * Get the validity of current value.
8521 * This method returns a promise that resolves if the value is valid and rejects if
8522 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
8524 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
8526 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
8529 function rejectOrResolve( valid
) {
8531 return $.Deferred().resolve().promise();
8533 return $.Deferred().reject().promise();
8537 if ( this.validate
instanceof Function
) {
8538 result
= this.validate( this.getValue() );
8539 if ( result
&& $.isFunction( result
.promise
) ) {
8540 return result
.promise().then( function ( valid
) {
8541 return rejectOrResolve( valid
);
8544 return rejectOrResolve( result
);
8547 return rejectOrResolve( this.getValue().match( this.validate
) );
8552 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
8554 * @param {string} labelPosition Label position, 'before' or 'after'
8557 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
8558 this.labelPosition
= labelPosition
;
8560 // If there is no label and we only change the position, #updatePosition is a no-op,
8561 // but it takes really a lot of work to do nothing.
8562 this.updatePosition();
8568 * Update the position of the inline label.
8570 * This method is called by #setLabelPosition, and can also be called on its own if
8571 * something causes the label to be mispositioned.
8575 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
8576 var after
= this.labelPosition
=== 'after';
8579 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
8580 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
8582 this.valCache
= null;
8583 this.scrollWidth
= null;
8585 this.positionLabel();
8591 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
8592 * already empty or when it's not editable.
8594 OO
.ui
.TextInputWidget
.prototype.updateSearchIndicator = function () {
8595 if ( this.type
=== 'search' ) {
8596 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
8597 this.setIndicator( null );
8599 this.setIndicator( 'clear' );
8605 * Position the label by setting the correct padding on the input.
8610 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
8611 var after
, rtl
, property
;
8614 // Clear old values if present
8616 'padding-right': '',
8621 this.$element
.append( this.$label
);
8623 this.$label
.detach();
8627 after
= this.labelPosition
=== 'after';
8628 rtl
= this.$element
.css( 'direction' ) === 'rtl';
8629 property
= after
=== rtl
? 'padding-left' : 'padding-right';
8631 this.$input
.css( property
, this.$label
.outerWidth( true ) + ( after
? this.scrollWidth
: 0 ) );
8639 OO
.ui
.TextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
8640 OO
.ui
.TextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
8641 if ( state
.scrollTop
!== undefined ) {
8642 this.$input
.scrollTop( state
.scrollTop
);
8647 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
8648 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
8649 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
8651 * - by typing a value in the text input field. If the value exactly matches the value of a menu
8652 * option, that option will appear to be selected.
8653 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
8656 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
8658 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
8661 * // Example: A ComboBoxInputWidget.
8662 * var comboBox = new OO.ui.ComboBoxInputWidget( {
8663 * label: 'ComboBoxInputWidget',
8664 * value: 'Option 1',
8667 * new OO.ui.MenuOptionWidget( {
8669 * label: 'Option One'
8671 * new OO.ui.MenuOptionWidget( {
8673 * label: 'Option Two'
8675 * new OO.ui.MenuOptionWidget( {
8677 * label: 'Option Three'
8679 * new OO.ui.MenuOptionWidget( {
8681 * label: 'Option Four'
8683 * new OO.ui.MenuOptionWidget( {
8685 * label: 'Option Five'
8690 * $( 'body' ).append( comboBox.$element );
8692 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
8695 * @extends OO.ui.TextInputWidget
8698 * @param {Object} [config] Configuration options
8699 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
8700 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
8701 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
8702 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
8703 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
8705 OO
.ui
.ComboBoxInputWidget
= function OoUiComboBoxInputWidget( config
) {
8706 // Configuration initialization
8707 config
= $.extend( {
8711 // For backwards-compatibility with ComboBoxWidget config
8712 $.extend( config
, config
.input
);
8714 // Parent constructor
8715 OO
.ui
.ComboBoxInputWidget
.parent
.call( this, config
);
8718 this.$overlay
= config
.$overlay
|| this.$element
;
8719 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
8723 $container
: this.$element
,
8724 disabled
: this.isDisabled()
8728 // For backwards-compatibility with ComboBoxWidget
8732 this.$indicator
.on( {
8733 click
: this.onIndicatorClick
.bind( this ),
8734 keypress
: this.onIndicatorKeyPress
.bind( this )
8736 this.connect( this, {
8737 change
: 'onInputChange',
8738 enter
: 'onInputEnter'
8740 this.menu
.connect( this, {
8741 choose
: 'onMenuChoose',
8742 add
: 'onMenuItemsChange',
8743 remove
: 'onMenuItemsChange'
8749 'aria-autocomplete': 'list'
8751 // Do not override options set via config.menu.items
8752 if ( config
.options
!== undefined ) {
8753 this.setOptions( config
.options
);
8755 // Extra class for backwards-compatibility with ComboBoxWidget
8756 this.$element
.addClass( 'oo-ui-comboBoxInputWidget oo-ui-comboBoxWidget' );
8757 this.$overlay
.append( this.menu
.$element
);
8758 this.onMenuItemsChange();
8763 OO
.inheritClass( OO
.ui
.ComboBoxInputWidget
, OO
.ui
.TextInputWidget
);
8768 * Get the combobox's menu.
8770 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
8772 OO
.ui
.ComboBoxInputWidget
.prototype.getMenu = function () {
8777 * Get the combobox's text input widget.
8779 * @return {OO.ui.TextInputWidget} Text input widget
8781 OO
.ui
.ComboBoxInputWidget
.prototype.getInput = function () {
8786 * Handle input change events.
8789 * @param {string} value New value
8791 OO
.ui
.ComboBoxInputWidget
.prototype.onInputChange = function ( value
) {
8792 var match
= this.menu
.getItemFromData( value
);
8794 this.menu
.selectItem( match
);
8795 if ( this.menu
.getHighlightedItem() ) {
8796 this.menu
.highlightItem( match
);
8799 if ( !this.isDisabled() ) {
8800 this.menu
.toggle( true );
8805 * Handle mouse click events.
8808 * @param {jQuery.Event} e Mouse click event
8810 OO
.ui
.ComboBoxInputWidget
.prototype.onIndicatorClick = function ( e
) {
8811 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
8813 this.$input
[ 0 ].focus();
8819 * Handle key press events.
8822 * @param {jQuery.Event} e Key press event
8824 OO
.ui
.ComboBoxInputWidget
.prototype.onIndicatorKeyPress = function ( e
) {
8825 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
8827 this.$input
[ 0 ].focus();
8833 * Handle input enter events.
8837 OO
.ui
.ComboBoxInputWidget
.prototype.onInputEnter = function () {
8838 if ( !this.isDisabled() ) {
8839 this.menu
.toggle( false );
8844 * Handle menu choose events.
8847 * @param {OO.ui.OptionWidget} item Chosen item
8849 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuChoose = function ( item
) {
8850 this.setValue( item
.getData() );
8854 * Handle menu item change events.
8858 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuItemsChange = function () {
8859 var match
= this.menu
.getItemFromData( this.getValue() );
8860 this.menu
.selectItem( match
);
8861 if ( this.menu
.getHighlightedItem() ) {
8862 this.menu
.highlightItem( match
);
8864 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu
.isEmpty() );
8870 OO
.ui
.ComboBoxInputWidget
.prototype.setDisabled = function ( disabled
) {
8872 OO
.ui
.ComboBoxInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
8875 this.menu
.setDisabled( this.isDisabled() );
8882 * Set the options available for this input.
8884 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
8887 OO
.ui
.ComboBoxInputWidget
.prototype.setOptions = function ( options
) {
8890 .addItems( options
.map( function ( opt
) {
8891 return new OO
.ui
.MenuOptionWidget( {
8893 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
8902 * @deprecated since 0.13.2; use OO.ui.ComboBoxInputWidget instead
8904 OO
.ui
.ComboBoxWidget
= OO
.ui
.ComboBoxInputWidget
;
8907 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
8908 * which is a widget that is specified by reference before any optional configuration settings.
8910 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
8912 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8913 * A left-alignment is used for forms with many fields.
8914 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8915 * A right-alignment is used for long but familiar forms which users tab through,
8916 * verifying the current field with a quick glance at the label.
8917 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8918 * that users fill out from top to bottom.
8919 * - **inline**: The label is placed after the field-widget and aligned to the left.
8920 * An inline-alignment is best used with checkboxes or radio buttons.
8922 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
8923 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
8925 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8928 * @extends OO.ui.Layout
8929 * @mixins OO.ui.mixin.LabelElement
8930 * @mixins OO.ui.mixin.TitledElement
8933 * @param {OO.ui.Widget} fieldWidget Field widget
8934 * @param {Object} [config] Configuration options
8935 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
8936 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
8937 * The array may contain strings or OO.ui.HtmlSnippet instances.
8938 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
8939 * The array may contain strings or OO.ui.HtmlSnippet instances.
8940 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
8941 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
8942 * For important messages, you are advised to use `notices`, as they are always shown.
8944 * @throws {Error} An error is thrown if no widget is specified
8946 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
8947 var hasInputWidget
, div
;
8949 // Allow passing positional parameters inside the config object
8950 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
8951 config
= fieldWidget
;
8952 fieldWidget
= config
.fieldWidget
;
8955 // Make sure we have required constructor arguments
8956 if ( fieldWidget
=== undefined ) {
8957 throw new Error( 'Widget not found' );
8960 hasInputWidget
= fieldWidget
.constructor.static.supportsSimpleLabel
;
8962 // Configuration initialization
8963 config
= $.extend( { align
: 'left' }, config
);
8965 // Parent constructor
8966 OO
.ui
.FieldLayout
.parent
.call( this, config
);
8968 // Mixin constructors
8969 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8970 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
8973 this.fieldWidget
= fieldWidget
;
8976 this.$field
= $( '<div>' );
8977 this.$messages
= $( '<ul>' );
8978 this.$body
= $( '<' + ( hasInputWidget
? 'label' : 'div' ) + '>' );
8980 if ( config
.help
) {
8981 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
8982 classes
: [ 'oo-ui-fieldLayout-help' ],
8988 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
8989 div
.html( config
.help
.toString() );
8991 div
.text( config
.help
);
8993 this.popupButtonWidget
.getPopup().$body
.append(
8994 div
.addClass( 'oo-ui-fieldLayout-help-content' )
8996 this.$help
= this.popupButtonWidget
.$element
;
8998 this.$help
= $( [] );
9002 if ( hasInputWidget
) {
9003 this.$label
.on( 'click', this.onLabelClick
.bind( this ) );
9005 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
9009 .addClass( 'oo-ui-fieldLayout' )
9010 .append( this.$help
, this.$body
);
9011 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
9012 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
9014 .addClass( 'oo-ui-fieldLayout-field' )
9015 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget
.isDisabled() )
9016 .append( this.fieldWidget
.$element
);
9018 this.setErrors( config
.errors
|| [] );
9019 this.setNotices( config
.notices
|| [] );
9020 this.setAlignment( config
.align
);
9025 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
9026 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
9027 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
9032 * Handle field disable events.
9035 * @param {boolean} value Field is disabled
9037 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
9038 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
9042 * Handle label mouse click events.
9045 * @param {jQuery.Event} e Mouse click event
9047 OO
.ui
.FieldLayout
.prototype.onLabelClick = function () {
9048 this.fieldWidget
.simulateLabelClick();
9053 * Get the widget contained by the field.
9055 * @return {OO.ui.Widget} Field widget
9057 OO
.ui
.FieldLayout
.prototype.getField = function () {
9058 return this.fieldWidget
;
9063 * @param {string} kind 'error' or 'notice'
9064 * @param {string|OO.ui.HtmlSnippet} text
9067 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
9068 var $listItem
, $icon
, message
;
9069 $listItem
= $( '<li>' );
9070 if ( kind
=== 'error' ) {
9071 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
9072 } else if ( kind
=== 'notice' ) {
9073 $icon
= new OO
.ui
.IconWidget( { icon
: 'info' } ).$element
;
9077 message
= new OO
.ui
.LabelWidget( { label
: text
} );
9079 .append( $icon
, message
.$element
)
9080 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
9085 * Set the field alignment mode.
9088 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
9091 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
9092 if ( value
!== this.align
) {
9093 // Default to 'left'
9094 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
9098 if ( value
=== 'inline' ) {
9099 this.$body
.append( this.$field
, this.$label
);
9101 this.$body
.append( this.$label
, this.$field
);
9103 // Set classes. The following classes can be used here:
9104 // * oo-ui-fieldLayout-align-left
9105 // * oo-ui-fieldLayout-align-right
9106 // * oo-ui-fieldLayout-align-top
9107 // * oo-ui-fieldLayout-align-inline
9109 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
9111 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
9119 * Set the list of error messages.
9121 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
9122 * The array may contain strings or OO.ui.HtmlSnippet instances.
9125 OO
.ui
.FieldLayout
.prototype.setErrors = function ( errors
) {
9126 this.errors
= errors
.slice();
9127 this.updateMessages();
9132 * Set the list of notice messages.
9134 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
9135 * The array may contain strings or OO.ui.HtmlSnippet instances.
9138 OO
.ui
.FieldLayout
.prototype.setNotices = function ( notices
) {
9139 this.notices
= notices
.slice();
9140 this.updateMessages();
9145 * Update the rendering of error and notice messages.
9149 OO
.ui
.FieldLayout
.prototype.updateMessages = function () {
9151 this.$messages
.empty();
9153 if ( this.errors
.length
|| this.notices
.length
) {
9154 this.$body
.after( this.$messages
);
9156 this.$messages
.remove();
9160 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
9161 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
9163 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
9164 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
9169 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
9170 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
9171 * is required and is specified before any optional configuration settings.
9173 * Labels can be aligned in one of four ways:
9175 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9176 * A left-alignment is used for forms with many fields.
9177 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9178 * A right-alignment is used for long but familiar forms which users tab through,
9179 * verifying the current field with a quick glance at the label.
9180 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9181 * that users fill out from top to bottom.
9182 * - **inline**: The label is placed after the field-widget and aligned to the left.
9183 * An inline-alignment is best used with checkboxes or radio buttons.
9185 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
9186 * text is specified.
9189 * // Example of an ActionFieldLayout
9190 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
9191 * new OO.ui.TextInputWidget( {
9192 * placeholder: 'Field widget'
9194 * new OO.ui.ButtonWidget( {
9198 * label: 'An ActionFieldLayout. This label is aligned top',
9200 * help: 'This is help text'
9204 * $( 'body' ).append( actionFieldLayout.$element );
9207 * @extends OO.ui.FieldLayout
9210 * @param {OO.ui.Widget} fieldWidget Field widget
9211 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
9213 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
9214 // Allow passing positional parameters inside the config object
9215 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
9216 config
= fieldWidget
;
9217 fieldWidget
= config
.fieldWidget
;
9218 buttonWidget
= config
.buttonWidget
;
9221 // Parent constructor
9222 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
9225 this.buttonWidget
= buttonWidget
;
9226 this.$button
= $( '<div>' );
9227 this.$input
= $( '<div>' );
9231 .addClass( 'oo-ui-actionFieldLayout' );
9233 .addClass( 'oo-ui-actionFieldLayout-button' )
9234 .append( this.buttonWidget
.$element
);
9236 .addClass( 'oo-ui-actionFieldLayout-input' )
9237 .append( this.fieldWidget
.$element
);
9239 .append( this.$input
, this.$button
);
9244 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
9247 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
9248 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
9249 * configured with a label as well. For more information and examples,
9250 * please see the [OOjs UI documentation on MediaWiki][1].
9253 * // Example of a fieldset layout
9254 * var input1 = new OO.ui.TextInputWidget( {
9255 * placeholder: 'A text input field'
9258 * var input2 = new OO.ui.TextInputWidget( {
9259 * placeholder: 'A text input field'
9262 * var fieldset = new OO.ui.FieldsetLayout( {
9263 * label: 'Example of a fieldset layout'
9266 * fieldset.addItems( [
9267 * new OO.ui.FieldLayout( input1, {
9268 * label: 'Field One'
9270 * new OO.ui.FieldLayout( input2, {
9271 * label: 'Field Two'
9274 * $( 'body' ).append( fieldset.$element );
9276 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9279 * @extends OO.ui.Layout
9280 * @mixins OO.ui.mixin.IconElement
9281 * @mixins OO.ui.mixin.LabelElement
9282 * @mixins OO.ui.mixin.GroupElement
9285 * @param {Object} [config] Configuration options
9286 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
9288 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
9289 // Configuration initialization
9290 config
= config
|| {};
9292 // Parent constructor
9293 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
9295 // Mixin constructors
9296 OO
.ui
.mixin
.IconElement
.call( this, config
);
9297 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9298 OO
.ui
.mixin
.GroupElement
.call( this, config
);
9300 if ( config
.help
) {
9301 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
9302 classes
: [ 'oo-ui-fieldsetLayout-help' ],
9307 this.popupButtonWidget
.getPopup().$body
.append(
9309 .text( config
.help
)
9310 .addClass( 'oo-ui-fieldsetLayout-help-content' )
9312 this.$help
= this.popupButtonWidget
.$element
;
9314 this.$help
= $( [] );
9319 .addClass( 'oo-ui-fieldsetLayout' )
9320 .prepend( this.$help
, this.$icon
, this.$label
, this.$group
);
9321 if ( Array
.isArray( config
.items
) ) {
9322 this.addItems( config
.items
);
9328 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
9329 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
9330 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
9331 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
9334 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
9335 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
9336 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
9337 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9339 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
9340 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
9341 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
9342 * some fancier controls. Some controls have both regular and InputWidget variants, for example
9343 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
9344 * often have simplified APIs to match the capabilities of HTML forms.
9345 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
9347 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
9348 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9351 * // Example of a form layout that wraps a fieldset layout
9352 * var input1 = new OO.ui.TextInputWidget( {
9353 * placeholder: 'Username'
9355 * var input2 = new OO.ui.TextInputWidget( {
9356 * placeholder: 'Password',
9359 * var submit = new OO.ui.ButtonInputWidget( {
9363 * var fieldset = new OO.ui.FieldsetLayout( {
9364 * label: 'A form layout'
9366 * fieldset.addItems( [
9367 * new OO.ui.FieldLayout( input1, {
9368 * label: 'Username',
9371 * new OO.ui.FieldLayout( input2, {
9372 * label: 'Password',
9375 * new OO.ui.FieldLayout( submit )
9377 * var form = new OO.ui.FormLayout( {
9378 * items: [ fieldset ],
9379 * action: '/api/formhandler',
9382 * $( 'body' ).append( form.$element );
9385 * @extends OO.ui.Layout
9386 * @mixins OO.ui.mixin.GroupElement
9389 * @param {Object} [config] Configuration options
9390 * @cfg {string} [method] HTML form `method` attribute
9391 * @cfg {string} [action] HTML form `action` attribute
9392 * @cfg {string} [enctype] HTML form `enctype` attribute
9393 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
9395 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
9398 // Configuration initialization
9399 config
= config
|| {};
9401 // Parent constructor
9402 OO
.ui
.FormLayout
.parent
.call( this, config
);
9404 // Mixin constructors
9405 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
9408 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
9410 // Make sure the action is safe
9411 action
= config
.action
;
9412 if ( action
!== undefined && !OO
.ui
.isSafeUrl( action
) ) {
9413 action
= './' + action
;
9418 .addClass( 'oo-ui-formLayout' )
9420 method
: config
.method
,
9422 enctype
: config
.enctype
9424 if ( Array
.isArray( config
.items
) ) {
9425 this.addItems( config
.items
);
9431 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
9432 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
9437 * A 'submit' event is emitted when the form is submitted.
9442 /* Static Properties */
9444 OO
.ui
.FormLayout
.static.tagName
= 'form';
9449 * Handle form submit events.
9452 * @param {jQuery.Event} e Submit event
9455 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
9456 if ( this.emit( 'submit' ) ) {
9462 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
9463 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
9466 * // Example of a panel layout
9467 * var panel = new OO.ui.PanelLayout( {
9471 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
9473 * $( 'body' ).append( panel.$element );
9476 * @extends OO.ui.Layout
9479 * @param {Object} [config] Configuration options
9480 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
9481 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
9482 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
9483 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
9485 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
9486 // Configuration initialization
9487 config
= $.extend( {
9494 // Parent constructor
9495 OO
.ui
.PanelLayout
.parent
.call( this, config
);
9498 this.$element
.addClass( 'oo-ui-panelLayout' );
9499 if ( config
.scrollable
) {
9500 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
9502 if ( config
.padded
) {
9503 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
9505 if ( config
.expanded
) {
9506 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
9508 if ( config
.framed
) {
9509 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
9515 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
9520 * Focus the panel layout
9522 * The default implementation just focuses the first focusable element in the panel
9524 OO
.ui
.PanelLayout
.prototype.focus = function () {
9525 OO
.ui
.findFocusable( this.$element
).focus();
9529 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
9530 * items), with small margins between them. Convenient when you need to put a number of block-level
9531 * widgets on a single line next to each other.
9533 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
9536 * // HorizontalLayout with a text input and a label
9537 * var layout = new OO.ui.HorizontalLayout( {
9539 * new OO.ui.LabelWidget( { label: 'Label' } ),
9540 * new OO.ui.TextInputWidget( { value: 'Text' } )
9543 * $( 'body' ).append( layout.$element );
9546 * @extends OO.ui.Layout
9547 * @mixins OO.ui.mixin.GroupElement
9550 * @param {Object} [config] Configuration options
9551 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
9553 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
9554 // Configuration initialization
9555 config
= config
|| {};
9557 // Parent constructor
9558 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
9560 // Mixin constructors
9561 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
9564 this.$element
.addClass( 'oo-ui-horizontalLayout' );
9565 if ( Array
.isArray( config
.items
) ) {
9566 this.addItems( config
.items
);
9572 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
9573 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);