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-05-10T22:58:27Z
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 can be set on:
2006 * - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected
2007 * - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on
2008 * - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page
2011 * @param {boolean} value Make button active
2014 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
2015 this.active
= !!value
;
2016 this.$element
.toggleClass( 'oo-ui-buttonElement-active', this.active
);
2021 * Check if the button is active
2024 * @return {boolean} The button is active
2026 OO
.ui
.mixin
.ButtonElement
.prototype.isActive = function () {
2031 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
2032 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
2033 * items from the group is done through the interface the class provides.
2034 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2036 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
2042 * @param {Object} [config] Configuration options
2043 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
2044 * is omitted, the group element will use a generated `<div>`.
2046 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
2047 // Configuration initialization
2048 config
= config
|| {};
2053 this.aggregateItemEvents
= {};
2056 this.setGroupElement( config
.$group
|| $( '<div>' ) );
2064 * A change event is emitted when the set of selected items changes.
2066 * @param {OO.ui.Element[]} items Items currently in the group
2072 * Set the group element.
2074 * If an element is already set, items will be moved to the new element.
2076 * @param {jQuery} $group Element to use as group
2078 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
2081 this.$group
= $group
;
2082 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2083 this.$group
.append( this.items
[ i
].$element
);
2088 * Check if a group contains no items.
2090 * @return {boolean} Group is empty
2092 OO
.ui
.mixin
.GroupElement
.prototype.isEmpty = function () {
2093 return !this.items
.length
;
2097 * Get all items in the group.
2099 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
2100 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
2103 * @return {OO.ui.Element[]} An array of items.
2105 OO
.ui
.mixin
.GroupElement
.prototype.getItems = function () {
2106 return this.items
.slice( 0 );
2110 * Get an item by its data.
2112 * Only the first item with matching data will be returned. To return all matching items,
2113 * use the #getItemsFromData method.
2115 * @param {Object} data Item data to search for
2116 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2118 OO
.ui
.mixin
.GroupElement
.prototype.getItemFromData = function ( data
) {
2120 hash
= OO
.getHash( data
);
2122 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2123 item
= this.items
[ i
];
2124 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2133 * Get items by their data.
2135 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
2137 * @param {Object} data Item data to search for
2138 * @return {OO.ui.Element[]} Items with equivalent data
2140 OO
.ui
.mixin
.GroupElement
.prototype.getItemsFromData = function ( data
) {
2142 hash
= OO
.getHash( data
),
2145 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2146 item
= this.items
[ i
];
2147 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2156 * Aggregate the events emitted by the group.
2158 * When events are aggregated, the group will listen to all contained items for the event,
2159 * and then emit the event under a new name. The new event will contain an additional leading
2160 * parameter containing the item that emitted the original event. Other arguments emitted from
2161 * the original event are passed through.
2163 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
2164 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
2165 * A `null` value will remove aggregated events.
2167 * @throws {Error} An error is thrown if aggregation already exists.
2169 OO
.ui
.mixin
.GroupElement
.prototype.aggregate = function ( events
) {
2170 var i
, len
, item
, add
, remove
, itemEvent
, groupEvent
;
2172 for ( itemEvent
in events
) {
2173 groupEvent
= events
[ itemEvent
];
2175 // Remove existing aggregated event
2176 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
2177 // Don't allow duplicate aggregations
2179 throw new Error( 'Duplicate item event aggregation for ' + itemEvent
);
2181 // Remove event aggregation from existing items
2182 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2183 item
= this.items
[ i
];
2184 if ( item
.connect
&& item
.disconnect
) {
2186 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
2187 item
.disconnect( this, remove
);
2190 // Prevent future items from aggregating event
2191 delete this.aggregateItemEvents
[ itemEvent
];
2194 // Add new aggregate event
2196 // Make future items aggregate event
2197 this.aggregateItemEvents
[ itemEvent
] = groupEvent
;
2198 // Add event aggregation to existing items
2199 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2200 item
= this.items
[ i
];
2201 if ( item
.connect
&& item
.disconnect
) {
2203 add
[ itemEvent
] = [ 'emit', groupEvent
, item
];
2204 item
.connect( this, add
);
2212 * Add items to the group.
2214 * Items will be added to the end of the group array unless the optional `index` parameter specifies
2215 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
2217 * @param {OO.ui.Element[]} items An array of items to add to the group
2218 * @param {number} [index] Index of the insertion point
2221 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
2222 var i
, len
, item
, event
, events
, currentIndex
,
2225 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
2228 // Check if item exists then remove it first, effectively "moving" it
2229 currentIndex
= this.items
.indexOf( item
);
2230 if ( currentIndex
>= 0 ) {
2231 this.removeItems( [ item
] );
2232 // Adjust index to compensate for removal
2233 if ( currentIndex
< index
) {
2238 if ( item
.connect
&& item
.disconnect
&& !$.isEmptyObject( this.aggregateItemEvents
) ) {
2240 for ( event
in this.aggregateItemEvents
) {
2241 events
[ event
] = [ 'emit', this.aggregateItemEvents
[ event
], item
];
2243 item
.connect( this, events
);
2245 item
.setElementGroup( this );
2246 itemElements
.push( item
.$element
.get( 0 ) );
2249 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
2250 this.$group
.append( itemElements
);
2251 this.items
.push
.apply( this.items
, items
);
2252 } else if ( index
=== 0 ) {
2253 this.$group
.prepend( itemElements
);
2254 this.items
.unshift
.apply( this.items
, items
);
2256 this.items
[ index
].$element
.before( itemElements
);
2257 this.items
.splice
.apply( this.items
, [ index
, 0 ].concat( items
) );
2260 this.emit( 'change', this.getItems() );
2265 * Remove the specified items from a group.
2267 * Removed items are detached (not removed) from the DOM so that they may be reused.
2268 * To remove all items from a group, you may wish to use the #clearItems method instead.
2270 * @param {OO.ui.Element[]} items An array of items to remove
2273 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
2274 var i
, len
, item
, index
, remove
, itemEvent
;
2276 // Remove specific items
2277 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
2279 index
= this.items
.indexOf( item
);
2280 if ( index
!== -1 ) {
2282 item
.connect
&& item
.disconnect
&&
2283 !$.isEmptyObject( this.aggregateItemEvents
)
2286 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
2287 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
2289 item
.disconnect( this, remove
);
2291 item
.setElementGroup( null );
2292 this.items
.splice( index
, 1 );
2293 item
.$element
.detach();
2297 this.emit( 'change', this.getItems() );
2302 * Clear all items from the group.
2304 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2305 * To remove only a subset of items from a group, use the #removeItems method.
2309 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
2310 var i
, len
, item
, remove
, itemEvent
;
2313 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2314 item
= this.items
[ i
];
2316 item
.connect
&& item
.disconnect
&&
2317 !$.isEmptyObject( this.aggregateItemEvents
)
2320 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
2321 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
2323 item
.disconnect( this, remove
);
2325 item
.setElementGroup( null );
2326 item
.$element
.detach();
2329 this.emit( 'change', this.getItems() );
2335 * IconElement is often mixed into other classes to generate an icon.
2336 * Icons are graphics, about the size of normal text. They are used to aid the user
2337 * in locating a control or to convey information in a space-efficient way. See the
2338 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
2339 * included in the library.
2341 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2347 * @param {Object} [config] Configuration options
2348 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2349 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2350 * the icon element be set to an existing icon instead of the one generated by this class, set a
2351 * value using a jQuery selection. For example:
2353 * // Use a <div> tag instead of a <span>
2355 * // Use an existing icon element instead of the one generated by the class
2356 * $icon: this.$element
2357 * // Use an icon element from a child widget
2358 * $icon: this.childwidget.$element
2359 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
2360 * symbolic names. A map is used for i18n purposes and contains a `default` icon
2361 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
2362 * by the user's language.
2364 * Example of an i18n map:
2366 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2367 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
2368 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2369 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
2370 * text. The icon title is displayed when users move the mouse over the icon.
2372 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
2373 // Configuration initialization
2374 config
= config
|| {};
2379 this.iconTitle
= null;
2382 this.setIcon( config
.icon
|| this.constructor.static.icon
);
2383 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
2384 this.setIconElement( config
.$icon
|| $( '<span>' ) );
2389 OO
.initClass( OO
.ui
.mixin
.IconElement
);
2391 /* Static Properties */
2394 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
2395 * for i18n purposes and contains a `default` icon name and additional names keyed by
2396 * language code. The `default` name is used when no icon is keyed by the user's language.
2398 * Example of an i18n map:
2400 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2402 * Note: the static property will be overridden if the #icon configuration is used.
2406 * @property {Object|string}
2408 OO
.ui
.mixin
.IconElement
.static.icon
= null;
2411 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2412 * function that returns title text, or `null` for no title.
2414 * The static property will be overridden if the #iconTitle configuration is used.
2418 * @property {string|Function|null}
2420 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
2425 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2426 * applies to the specified icon element instead of the one created by the class. If an icon
2427 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2428 * and mixin methods will no longer affect the element.
2430 * @param {jQuery} $icon Element to use as icon
2432 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
2435 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
2436 .removeAttr( 'title' );
2440 .addClass( 'oo-ui-iconElement-icon' )
2441 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
2442 if ( this.iconTitle
!== null ) {
2443 this.$icon
.attr( 'title', this.iconTitle
);
2446 this.updateThemeClasses();
2450 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
2451 * The icon parameter can also be set to a map of icon names. See the #icon config setting
2454 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
2455 * by language code, or `null` to remove the icon.
2458 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
2459 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
2460 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
2462 if ( this.icon
!== icon
) {
2464 if ( this.icon
!== null ) {
2465 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
2467 if ( icon
!== null ) {
2468 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
2474 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
2475 this.updateThemeClasses();
2481 * Set the icon title. Use `null` to remove the title.
2483 * @param {string|Function|null} iconTitle A text string used as the icon title,
2484 * a function that returns title text, or `null` for no title.
2487 OO
.ui
.mixin
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
2488 iconTitle
= typeof iconTitle
=== 'function' ||
2489 ( typeof iconTitle
=== 'string' && iconTitle
.length
) ?
2490 OO
.ui
.resolveMsg( iconTitle
) : null;
2492 if ( this.iconTitle
!== iconTitle
) {
2493 this.iconTitle
= iconTitle
;
2495 if ( this.iconTitle
!== null ) {
2496 this.$icon
.attr( 'title', iconTitle
);
2498 this.$icon
.removeAttr( 'title' );
2507 * Get the symbolic name of the icon.
2509 * @return {string} Icon name
2511 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
2516 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
2518 * @return {string} Icon title text
2520 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
2521 return this.iconTitle
;
2525 * IndicatorElement is often mixed into other classes to generate an indicator.
2526 * Indicators are small graphics that are generally used in two ways:
2528 * - To draw attention to the status of an item. For example, an indicator might be
2529 * used to show that an item in a list has errors that need to be resolved.
2530 * - To clarify the function of a control that acts in an exceptional way (a button
2531 * that opens a menu instead of performing an action directly, for example).
2533 * For a list of indicators included in the library, please see the
2534 * [OOjs UI documentation on MediaWiki] [1].
2536 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2542 * @param {Object} [config] Configuration options
2543 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
2544 * configuration is omitted, the indicator element will use a generated `<span>`.
2545 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2546 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
2548 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2549 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
2550 * or a function that returns title text. The indicator title is displayed when users move
2551 * the mouse over the indicator.
2553 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
2554 // Configuration initialization
2555 config
= config
|| {};
2558 this.$indicator
= null;
2559 this.indicator
= null;
2560 this.indicatorTitle
= null;
2563 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
2564 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
2565 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
2570 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
2572 /* Static Properties */
2575 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2576 * The static property will be overridden if the #indicator configuration is used.
2580 * @property {string|null}
2582 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
2585 * A text string used as the indicator title, a function that returns title text, or `null`
2586 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
2590 * @property {string|Function|null}
2592 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
2597 * Set the indicator element.
2599 * If an element is already set, it will be cleaned up before setting up the new element.
2601 * @param {jQuery} $indicator Element to use as indicator
2603 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
2604 if ( this.$indicator
) {
2606 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
2607 .removeAttr( 'title' );
2610 this.$indicator
= $indicator
2611 .addClass( 'oo-ui-indicatorElement-indicator' )
2612 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
2613 if ( this.indicatorTitle
!== null ) {
2614 this.$indicator
.attr( 'title', this.indicatorTitle
);
2617 this.updateThemeClasses();
2621 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
2623 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
2626 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
2627 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
2629 if ( this.indicator
!== indicator
) {
2630 if ( this.$indicator
) {
2631 if ( this.indicator
!== null ) {
2632 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
2634 if ( indicator
!== null ) {
2635 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
2638 this.indicator
= indicator
;
2641 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
2642 this.updateThemeClasses();
2648 * Set the indicator title.
2650 * The title is displayed when a user moves the mouse over the indicator.
2652 * @param {string|Function|null} indicatorTitle Indicator title text, a function that returns text, or
2653 * `null` for no indicator title
2656 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
2657 indicatorTitle
= typeof indicatorTitle
=== 'function' ||
2658 ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ?
2659 OO
.ui
.resolveMsg( indicatorTitle
) : null;
2661 if ( this.indicatorTitle
!== indicatorTitle
) {
2662 this.indicatorTitle
= indicatorTitle
;
2663 if ( this.$indicator
) {
2664 if ( this.indicatorTitle
!== null ) {
2665 this.$indicator
.attr( 'title', indicatorTitle
);
2667 this.$indicator
.removeAttr( 'title' );
2676 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2678 * @return {string} Symbolic name of indicator
2680 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
2681 return this.indicator
;
2685 * Get the indicator title.
2687 * The title is displayed when a user moves the mouse over the indicator.
2689 * @return {string} Indicator title text
2691 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
2692 return this.indicatorTitle
;
2696 * LabelElement is often mixed into other classes to generate a label, which
2697 * helps identify the function of an interface element.
2698 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
2700 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2706 * @param {Object} [config] Configuration options
2707 * @cfg {jQuery} [$label] The label element created by the class. If this
2708 * configuration is omitted, the label element will use a generated `<span>`.
2709 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
2710 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
2711 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
2712 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2714 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
2715 // Configuration initialization
2716 config
= config
|| {};
2723 this.setLabel( config
.label
|| this.constructor.static.label
);
2724 this.setLabelElement( config
.$label
|| $( '<span>' ) );
2729 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
2734 * @event labelChange
2735 * @param {string} value
2738 /* Static Properties */
2741 * The label text. The label can be specified as a plaintext string, a function that will
2742 * produce a string in the future, or `null` for no label. The static value will
2743 * be overridden if a label is specified with the #label config option.
2747 * @property {string|Function|null}
2749 OO
.ui
.mixin
.LabelElement
.static.label
= null;
2751 /* Static methods */
2754 * Highlight the first occurrence of the query in the given text
2756 * @param {string} text Text
2757 * @param {string} query Query to find
2758 * @return {jQuery} Text with the first match of the query
2759 * sub-string wrapped in highlighted span
2761 OO
.ui
.mixin
.LabelElement
.static.highlightQuery = function ( text
, query
) {
2762 var $result
= $( '<span>' ),
2763 offset
= text
.toLowerCase().indexOf( query
.toLowerCase() );
2765 if ( !query
.length
|| offset
=== -1 ) {
2766 return $result
.text( text
);
2769 document
.createTextNode( text
.slice( 0, offset
) ),
2771 .addClass( 'oo-ui-labelElement-label-highlight' )
2772 .text( text
.slice( offset
, offset
+ query
.length
) ),
2773 document
.createTextNode( text
.slice( offset
+ query
.length
) )
2775 return $result
.contents();
2781 * Set the label element.
2783 * If an element is already set, it will be cleaned up before setting up the new element.
2785 * @param {jQuery} $label Element to use as label
2787 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
2788 if ( this.$label
) {
2789 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
2792 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
2793 this.setLabelContent( this.label
);
2799 * An empty string will result in the label being hidden. A string containing only whitespace will
2800 * be converted to a single ` `.
2802 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
2803 * text; or null for no label
2806 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
2807 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
2808 label
= ( ( typeof label
=== 'string' || label
instanceof jQuery
) && label
.length
) || ( label
instanceof OO
.ui
.HtmlSnippet
&& label
.toString().length
) ? label
: null;
2810 if ( this.label
!== label
) {
2811 if ( this.$label
) {
2812 this.setLabelContent( label
);
2815 this.emit( 'labelChange' );
2818 this.$element
.toggleClass( 'oo-ui-labelElement', !!this.label
);
2824 * Set the label as plain text with a highlighted query
2826 * @param {string} text Text label to set
2827 * @param {string} query Substring of text to highlight
2830 OO
.ui
.mixin
.LabelElement
.prototype.setHighlightedQuery = function ( text
, query
) {
2831 return this.setLabel( this.constructor.static.highlightQuery( text
, query
) );
2837 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
2838 * text; or null for no label
2840 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
2848 * @deprecated since 0.16.0
2850 OO
.ui
.mixin
.LabelElement
.prototype.fitLabel = function () {
2855 * Set the content of the label.
2857 * Do not call this method until after the label element has been set by #setLabelElement.
2860 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
2861 * text; or null for no label
2863 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
2864 if ( typeof label
=== 'string' ) {
2865 if ( label
.match( /^\s*$/ ) ) {
2866 // Convert whitespace only string to a single non-breaking space
2867 this.$label
.html( ' ' );
2869 this.$label
.text( label
);
2871 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
2872 this.$label
.html( label
.toString() );
2873 } else if ( label
instanceof jQuery
) {
2874 this.$label
.empty().append( label
);
2876 this.$label
.empty();
2881 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
2882 * additional functionality to an element created by another class. The class provides
2883 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
2884 * which are used to customize the look and feel of a widget to better describe its
2885 * importance and functionality.
2887 * The library currently contains the following styling flags for general use:
2889 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
2890 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
2891 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
2893 * The flags affect the appearance of the buttons:
2896 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
2897 * var button1 = new OO.ui.ButtonWidget( {
2898 * label: 'Constructive',
2899 * flags: 'constructive'
2901 * var button2 = new OO.ui.ButtonWidget( {
2902 * label: 'Destructive',
2903 * flags: 'destructive'
2905 * var button3 = new OO.ui.ButtonWidget( {
2906 * label: 'Progressive',
2907 * flags: 'progressive'
2909 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
2911 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
2912 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
2914 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
2920 * @param {Object} [config] Configuration options
2921 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
2922 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
2923 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
2924 * @cfg {jQuery} [$flagged] The flagged element. By default,
2925 * the flagged functionality is applied to the element created by the class ($element).
2926 * If a different element is specified, the flagged functionality will be applied to it instead.
2928 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
2929 // Configuration initialization
2930 config
= config
|| {};
2934 this.$flagged
= null;
2937 this.setFlags( config
.flags
);
2938 this.setFlaggedElement( config
.$flagged
|| this.$element
);
2945 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
2946 * parameter contains the name of each modified flag and indicates whether it was
2949 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
2950 * that the flag was added, `false` that the flag was removed.
2956 * Set the flagged element.
2958 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
2959 * If an element is already set, the method will remove the mixin’s effect on that element.
2961 * @param {jQuery} $flagged Element that should be flagged
2963 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
2964 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
2965 return 'oo-ui-flaggedElement-' + flag
;
2968 if ( this.$flagged
) {
2969 this.$flagged
.removeClass( classNames
);
2972 this.$flagged
= $flagged
.addClass( classNames
);
2976 * Check if the specified flag is set.
2978 * @param {string} flag Name of flag
2979 * @return {boolean} The flag is set
2981 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
2982 // This may be called before the constructor, thus before this.flags is set
2983 return this.flags
&& ( flag
in this.flags
);
2987 * Get the names of all flags set.
2989 * @return {string[]} Flag names
2991 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
2992 // This may be called before the constructor, thus before this.flags is set
2993 return Object
.keys( this.flags
|| {} );
3002 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
3003 var flag
, className
,
3006 classPrefix
= 'oo-ui-flaggedElement-';
3008 for ( flag
in this.flags
) {
3009 className
= classPrefix
+ flag
;
3010 changes
[ flag
] = false;
3011 delete this.flags
[ flag
];
3012 remove
.push( className
);
3015 if ( this.$flagged
) {
3016 this.$flagged
.removeClass( remove
.join( ' ' ) );
3019 this.updateThemeClasses();
3020 this.emit( 'flag', changes
);
3026 * Add one or more flags.
3028 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
3029 * or an object keyed by flag name with a boolean value that indicates whether the flag should
3030 * be added (`true`) or removed (`false`).
3034 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
3035 var i
, len
, flag
, className
,
3039 classPrefix
= 'oo-ui-flaggedElement-';
3041 if ( typeof flags
=== 'string' ) {
3042 className
= classPrefix
+ flags
;
3044 if ( !this.flags
[ flags
] ) {
3045 this.flags
[ flags
] = true;
3046 add
.push( className
);
3048 } else if ( Array
.isArray( flags
) ) {
3049 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
3051 className
= classPrefix
+ flag
;
3053 if ( !this.flags
[ flag
] ) {
3054 changes
[ flag
] = true;
3055 this.flags
[ flag
] = true;
3056 add
.push( className
);
3059 } else if ( OO
.isPlainObject( flags
) ) {
3060 for ( flag
in flags
) {
3061 className
= classPrefix
+ flag
;
3062 if ( flags
[ flag
] ) {
3064 if ( !this.flags
[ flag
] ) {
3065 changes
[ flag
] = true;
3066 this.flags
[ flag
] = true;
3067 add
.push( className
);
3071 if ( this.flags
[ flag
] ) {
3072 changes
[ flag
] = false;
3073 delete this.flags
[ flag
];
3074 remove
.push( className
);
3080 if ( this.$flagged
) {
3082 .addClass( add
.join( ' ' ) )
3083 .removeClass( remove
.join( ' ' ) );
3086 this.updateThemeClasses();
3087 this.emit( 'flag', changes
);
3093 * TitledElement is mixed into other classes to provide a `title` attribute.
3094 * Titles are rendered by the browser and are made visible when the user moves
3095 * the mouse over the element. Titles are not visible on touch devices.
3098 * // TitledElement provides a 'title' attribute to the
3099 * // ButtonWidget class
3100 * var button = new OO.ui.ButtonWidget( {
3101 * label: 'Button with Title',
3102 * title: 'I am a button'
3104 * $( 'body' ).append( button.$element );
3110 * @param {Object} [config] Configuration options
3111 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
3112 * If this config is omitted, the title functionality is applied to $element, the
3113 * element created by the class.
3114 * @cfg {string|Function} [title] The title text or a function that returns text. If
3115 * this config is omitted, the value of the {@link #static-title static title} property is used.
3117 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
3118 // Configuration initialization
3119 config
= config
|| {};
3122 this.$titled
= null;
3126 this.setTitle( config
.title
!== undefined ? config
.title
: this.constructor.static.title
);
3127 this.setTitledElement( config
.$titled
|| this.$element
);
3132 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
3134 /* Static Properties */
3137 * The title text, a function that returns text, or `null` for no title. The value of the static property
3138 * is overridden if the #title config option is used.
3142 * @property {string|Function|null}
3144 OO
.ui
.mixin
.TitledElement
.static.title
= null;
3149 * Set the titled element.
3151 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
3152 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
3154 * @param {jQuery} $titled Element that should use the 'titled' functionality
3156 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
3157 if ( this.$titled
) {
3158 this.$titled
.removeAttr( 'title' );
3161 this.$titled
= $titled
;
3163 this.$titled
.attr( 'title', this.title
);
3170 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
3173 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
3174 title
= typeof title
=== 'function' ? OO
.ui
.resolveMsg( title
) : title
;
3175 title
= ( typeof title
=== 'string' && title
.length
) ? title
: null;
3177 if ( this.title
!== title
) {
3178 if ( this.$titled
) {
3179 if ( title
!== null ) {
3180 this.$titled
.attr( 'title', title
);
3182 this.$titled
.removeAttr( 'title' );
3194 * @return {string} Title string
3196 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
3201 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
3202 * Accesskeys allow an user to go to a specific element by using
3203 * a shortcut combination of a browser specific keys + the key
3207 * // AccessKeyedElement provides an 'accesskey' attribute to the
3208 * // ButtonWidget class
3209 * var button = new OO.ui.ButtonWidget( {
3210 * label: 'Button with Accesskey',
3213 * $( 'body' ).append( button.$element );
3219 * @param {Object} [config] Configuration options
3220 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3221 * If this config is omitted, the accesskey functionality is applied to $element, the
3222 * element created by the class.
3223 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3224 * this config is omitted, no accesskey will be added.
3226 OO
.ui
.mixin
.AccessKeyedElement
= function OoUiMixinAccessKeyedElement( config
) {
3227 // Configuration initialization
3228 config
= config
|| {};
3231 this.$accessKeyed
= null;
3232 this.accessKey
= null;
3235 this.setAccessKey( config
.accessKey
|| null );
3236 this.setAccessKeyedElement( config
.$accessKeyed
|| this.$element
);
3241 OO
.initClass( OO
.ui
.mixin
.AccessKeyedElement
);
3243 /* Static Properties */
3246 * The access key, a function that returns a key, or `null` for no accesskey.
3250 * @property {string|Function|null}
3252 OO
.ui
.mixin
.AccessKeyedElement
.static.accessKey
= null;
3257 * Set the accesskeyed element.
3259 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
3260 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
3262 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
3264 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKeyedElement = function ( $accessKeyed
) {
3265 if ( this.$accessKeyed
) {
3266 this.$accessKeyed
.removeAttr( 'accesskey' );
3269 this.$accessKeyed
= $accessKeyed
;
3270 if ( this.accessKey
) {
3271 this.$accessKeyed
.attr( 'accesskey', this.accessKey
);
3278 * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no accesskey
3281 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKey = function ( accessKey
) {
3282 accessKey
= typeof accessKey
=== 'string' ? OO
.ui
.resolveMsg( accessKey
) : null;
3284 if ( this.accessKey
!== accessKey
) {
3285 if ( this.$accessKeyed
) {
3286 if ( accessKey
!== null ) {
3287 this.$accessKeyed
.attr( 'accesskey', accessKey
);
3289 this.$accessKeyed
.removeAttr( 'accesskey' );
3292 this.accessKey
= accessKey
;
3301 * @return {string} accessKey string
3303 OO
.ui
.mixin
.AccessKeyedElement
.prototype.getAccessKey = function () {
3304 return this.accessKey
;
3308 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3309 * feels, and functionality can be customized via the class’s configuration options
3310 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
3313 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
3316 * // A button widget
3317 * var button = new OO.ui.ButtonWidget( {
3318 * label: 'Button with Icon',
3320 * iconTitle: 'Remove'
3322 * $( 'body' ).append( button.$element );
3324 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3327 * @extends OO.ui.Widget
3328 * @mixins OO.ui.mixin.ButtonElement
3329 * @mixins OO.ui.mixin.IconElement
3330 * @mixins OO.ui.mixin.IndicatorElement
3331 * @mixins OO.ui.mixin.LabelElement
3332 * @mixins OO.ui.mixin.TitledElement
3333 * @mixins OO.ui.mixin.FlaggedElement
3334 * @mixins OO.ui.mixin.TabIndexedElement
3335 * @mixins OO.ui.mixin.AccessKeyedElement
3338 * @param {Object} [config] Configuration options
3339 * @cfg {boolean} [active=false] Whether button should be shown as active
3340 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3341 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3342 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3344 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
3345 // Configuration initialization
3346 config
= config
|| {};
3348 // Parent constructor
3349 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
3351 // Mixin constructors
3352 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
3353 OO
.ui
.mixin
.IconElement
.call( this, config
);
3354 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
3355 OO
.ui
.mixin
.LabelElement
.call( this, config
);
3356 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
3357 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
3358 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
3359 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$button
} ) );
3364 this.noFollow
= false;
3367 this.connect( this, { disable
: 'onDisable' } );
3370 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
3372 .addClass( 'oo-ui-buttonWidget' )
3373 .append( this.$button
);
3374 this.setActive( config
.active
);
3375 this.setHref( config
.href
);
3376 this.setTarget( config
.target
);
3377 this.setNoFollow( config
.noFollow
);
3382 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
3383 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
3384 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
3385 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
3386 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
3387 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
3388 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
3389 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
3390 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
3397 OO
.ui
.ButtonWidget
.prototype.onMouseDown = function ( e
) {
3398 if ( !this.isDisabled() ) {
3399 // Remove the tab-index while the button is down to prevent the button from stealing focus
3400 this.$button
.removeAttr( 'tabindex' );
3403 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown
.call( this, e
);
3409 OO
.ui
.ButtonWidget
.prototype.onMouseUp = function ( e
) {
3410 if ( !this.isDisabled() ) {
3411 // Restore the tab-index after the button is up to restore the button's accessibility
3412 this.$button
.attr( 'tabindex', this.tabIndex
);
3415 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp
.call( this, e
);
3419 * Get hyperlink location.
3421 * @return {string} Hyperlink location
3423 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
3428 * Get hyperlink target.
3430 * @return {string} Hyperlink target
3432 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
3437 * Get search engine traversal hint.
3439 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3441 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
3442 return this.noFollow
;
3446 * Set hyperlink location.
3448 * @param {string|null} href Hyperlink location, null to remove
3450 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
3451 href
= typeof href
=== 'string' ? href
: null;
3452 if ( href
!== null && !OO
.ui
.isSafeUrl( href
) ) {
3456 if ( href
!== this.href
) {
3465 * Update the `href` attribute, in case of changes to href or
3471 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
3472 if ( this.href
!== null && !this.isDisabled() ) {
3473 this.$button
.attr( 'href', this.href
);
3475 this.$button
.removeAttr( 'href' );
3482 * Handle disable events.
3485 * @param {boolean} disabled Element is disabled
3487 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
3492 * Set hyperlink target.
3494 * @param {string|null} target Hyperlink target, null to remove
3496 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
3497 target
= typeof target
=== 'string' ? target
: null;
3499 if ( target
!== this.target
) {
3500 this.target
= target
;
3501 if ( target
!== null ) {
3502 this.$button
.attr( 'target', target
);
3504 this.$button
.removeAttr( 'target' );
3512 * Set search engine traversal hint.
3514 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3516 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
3517 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
3519 if ( noFollow
!== this.noFollow
) {
3520 this.noFollow
= noFollow
;
3522 this.$button
.attr( 'rel', 'nofollow' );
3524 this.$button
.removeAttr( 'rel' );
3531 // Override method visibility hints from ButtonElement
3540 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3541 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3542 * removed, and cleared from the group.
3545 * // Example: A ButtonGroupWidget with two buttons
3546 * var button1 = new OO.ui.PopupButtonWidget( {
3547 * label: 'Select a category',
3550 * $content: $( '<p>List of categories...</p>' ),
3555 * var button2 = new OO.ui.ButtonWidget( {
3558 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
3559 * items: [button1, button2]
3561 * $( 'body' ).append( buttonGroup.$element );
3564 * @extends OO.ui.Widget
3565 * @mixins OO.ui.mixin.GroupElement
3568 * @param {Object} [config] Configuration options
3569 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
3571 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
3572 // Configuration initialization
3573 config
= config
|| {};
3575 // Parent constructor
3576 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
3578 // Mixin constructors
3579 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
3582 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
3583 if ( Array
.isArray( config
.items
) ) {
3584 this.addItems( config
.items
);
3590 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
3591 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
3594 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
3595 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
3596 * for a list of icons included in the library.
3599 * // An icon widget with a label
3600 * var myIcon = new OO.ui.IconWidget( {
3604 * // Create a label.
3605 * var iconLabel = new OO.ui.LabelWidget( {
3608 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
3610 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
3613 * @extends OO.ui.Widget
3614 * @mixins OO.ui.mixin.IconElement
3615 * @mixins OO.ui.mixin.TitledElement
3616 * @mixins OO.ui.mixin.FlaggedElement
3619 * @param {Object} [config] Configuration options
3621 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
3622 // Configuration initialization
3623 config
= config
|| {};
3625 // Parent constructor
3626 OO
.ui
.IconWidget
.parent
.call( this, config
);
3628 // Mixin constructors
3629 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
3630 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
3631 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
3634 this.$element
.addClass( 'oo-ui-iconWidget' );
3639 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
3640 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
3641 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
3642 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
3644 /* Static Properties */
3646 OO
.ui
.IconWidget
.static.tagName
= 'span';
3649 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
3650 * attention to the status of an item or to clarify the function of a control. For a list of
3651 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
3654 * // Example of an indicator widget
3655 * var indicator1 = new OO.ui.IndicatorWidget( {
3656 * indicator: 'alert'
3659 * // Create a fieldset layout to add a label
3660 * var fieldset = new OO.ui.FieldsetLayout();
3661 * fieldset.addItems( [
3662 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
3664 * $( 'body' ).append( fieldset.$element );
3666 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3669 * @extends OO.ui.Widget
3670 * @mixins OO.ui.mixin.IndicatorElement
3671 * @mixins OO.ui.mixin.TitledElement
3674 * @param {Object} [config] Configuration options
3676 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
3677 // Configuration initialization
3678 config
= config
|| {};
3680 // Parent constructor
3681 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
3683 // Mixin constructors
3684 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
3685 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
3688 this.$element
.addClass( 'oo-ui-indicatorWidget' );
3693 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
3694 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
3695 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
3697 /* Static Properties */
3699 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
3702 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
3703 * be configured with a `label` option that is set to a string, a label node, or a function:
3705 * - String: a plaintext string
3706 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
3707 * label that includes a link or special styling, such as a gray color or additional graphical elements.
3708 * - Function: a function that will produce a string in the future. Functions are used
3709 * in cases where the value of the label is not currently defined.
3711 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
3712 * will come into focus when the label is clicked.
3715 * // Examples of LabelWidgets
3716 * var label1 = new OO.ui.LabelWidget( {
3717 * label: 'plaintext label'
3719 * var label2 = new OO.ui.LabelWidget( {
3720 * label: $( '<a href="default.html">jQuery label</a>' )
3722 * // Create a fieldset layout with fields for each example
3723 * var fieldset = new OO.ui.FieldsetLayout();
3724 * fieldset.addItems( [
3725 * new OO.ui.FieldLayout( label1 ),
3726 * new OO.ui.FieldLayout( label2 )
3728 * $( 'body' ).append( fieldset.$element );
3731 * @extends OO.ui.Widget
3732 * @mixins OO.ui.mixin.LabelElement
3735 * @param {Object} [config] Configuration options
3736 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
3737 * Clicking the label will focus the specified input field.
3739 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
3740 // Configuration initialization
3741 config
= config
|| {};
3743 // Parent constructor
3744 OO
.ui
.LabelWidget
.parent
.call( this, config
);
3746 // Mixin constructors
3747 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
3748 OO
.ui
.mixin
.TitledElement
.call( this, config
);
3751 this.input
= config
.input
;
3754 if ( this.input
instanceof OO
.ui
.InputWidget
) {
3755 this.$element
.on( 'click', this.onClick
.bind( this ) );
3759 this.$element
.addClass( 'oo-ui-labelWidget' );
3764 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
3765 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
3766 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
3768 /* Static Properties */
3770 OO
.ui
.LabelWidget
.static.tagName
= 'span';
3775 * Handles label mouse click events.
3778 * @param {jQuery.Event} e Mouse click event
3780 OO
.ui
.LabelWidget
.prototype.onClick = function () {
3781 this.input
.simulateLabelClick();
3786 * PendingElement is a mixin that is used to create elements that notify users that something is happening
3787 * and that they should wait before proceeding. The pending state is visually represented with a pending
3788 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
3789 * field of a {@link OO.ui.TextInputWidget text input widget}.
3791 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
3792 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
3793 * in process dialogs.
3796 * function MessageDialog( config ) {
3797 * MessageDialog.parent.call( this, config );
3799 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
3801 * MessageDialog.static.actions = [
3802 * { action: 'save', label: 'Done', flags: 'primary' },
3803 * { label: 'Cancel', flags: 'safe' }
3806 * MessageDialog.prototype.initialize = function () {
3807 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
3808 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
3809 * 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>' );
3810 * this.$body.append( this.content.$element );
3812 * MessageDialog.prototype.getBodyHeight = function () {
3815 * MessageDialog.prototype.getActionProcess = function ( action ) {
3816 * var dialog = this;
3817 * if ( action === 'save' ) {
3818 * dialog.getActions().get({actions: 'save'})[0].pushPending();
3819 * return new OO.ui.Process()
3821 * .next( function () {
3822 * dialog.getActions().get({actions: 'save'})[0].popPending();
3825 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
3828 * var windowManager = new OO.ui.WindowManager();
3829 * $( 'body' ).append( windowManager.$element );
3831 * var dialog = new MessageDialog();
3832 * windowManager.addWindows( [ dialog ] );
3833 * windowManager.openWindow( dialog );
3839 * @param {Object} [config] Configuration options
3840 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
3842 OO
.ui
.mixin
.PendingElement
= function OoUiMixinPendingElement( config
) {
3843 // Configuration initialization
3844 config
= config
|| {};
3848 this.$pending
= null;
3851 this.setPendingElement( config
.$pending
|| this.$element
);
3856 OO
.initClass( OO
.ui
.mixin
.PendingElement
);
3861 * Set the pending element (and clean up any existing one).
3863 * @param {jQuery} $pending The element to set to pending.
3865 OO
.ui
.mixin
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
3866 if ( this.$pending
) {
3867 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
3870 this.$pending
= $pending
;
3871 if ( this.pending
> 0 ) {
3872 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
3877 * Check if an element is pending.
3879 * @return {boolean} Element is pending
3881 OO
.ui
.mixin
.PendingElement
.prototype.isPending = function () {
3882 return !!this.pending
;
3886 * Increase the pending counter. The pending state will remain active until the counter is zero
3887 * (i.e., the number of calls to #pushPending and #popPending is the same).
3891 OO
.ui
.mixin
.PendingElement
.prototype.pushPending = function () {
3892 if ( this.pending
=== 0 ) {
3893 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
3894 this.updateThemeClasses();
3902 * Decrease the pending counter. The pending state will remain active until the counter is zero
3903 * (i.e., the number of calls to #pushPending and #popPending is the same).
3907 OO
.ui
.mixin
.PendingElement
.prototype.popPending = function () {
3908 if ( this.pending
=== 1 ) {
3909 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
3910 this.updateThemeClasses();
3912 this.pending
= Math
.max( 0, this.pending
- 1 );
3918 * Element that can be automatically clipped to visible boundaries.
3920 * Whenever the element's natural height changes, you have to call
3921 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
3922 * clipping correctly.
3924 * The dimensions of #$clippableContainer will be compared to the boundaries of the
3925 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
3926 * then #$clippable will be given a fixed reduced height and/or width and will be made
3927 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
3928 * but you can build a static footer by setting #$clippableContainer to an element that contains
3929 * #$clippable and the footer.
3935 * @param {Object} [config] Configuration options
3936 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
3937 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
3938 * omit to use #$clippable
3940 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
3941 // Configuration initialization
3942 config
= config
|| {};
3945 this.$clippable
= null;
3946 this.$clippableContainer
= null;
3947 this.clipping
= false;
3948 this.clippedHorizontally
= false;
3949 this.clippedVertically
= false;
3950 this.$clippableScrollableContainer
= null;
3951 this.$clippableScroller
= null;
3952 this.$clippableWindow
= null;
3953 this.idealWidth
= null;
3954 this.idealHeight
= null;
3955 this.onClippableScrollHandler
= this.clip
.bind( this );
3956 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
3959 if ( config
.$clippableContainer
) {
3960 this.setClippableContainer( config
.$clippableContainer
);
3962 this.setClippableElement( config
.$clippable
|| this.$element
);
3968 * Set clippable element.
3970 * If an element is already set, it will be cleaned up before setting up the new element.
3972 * @param {jQuery} $clippable Element to make clippable
3974 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
3975 if ( this.$clippable
) {
3976 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
3977 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
3978 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
3981 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
3986 * Set clippable container.
3988 * This is the container that will be measured when deciding whether to clip. When clipping,
3989 * #$clippable will be resized in order to keep the clippable container fully visible.
3991 * If the clippable container is unset, #$clippable will be used.
3993 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
3995 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableContainer = function ( $clippableContainer
) {
3996 this.$clippableContainer
= $clippableContainer
;
3997 if ( this.$clippable
) {
4005 * Do not turn clipping on until after the element is attached to the DOM and visible.
4007 * @param {boolean} [clipping] Enable clipping, omit to toggle
4010 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
4011 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
4013 if ( this.clipping
!== clipping
) {
4014 this.clipping
= clipping
;
4016 this.$clippableScrollableContainer
= $( this.getClosestScrollableElementContainer() );
4017 // If the clippable container is the root, we have to listen to scroll events and check
4018 // jQuery.scrollTop on the window because of browser inconsistencies
4019 this.$clippableScroller
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
4020 $( OO
.ui
.Element
.static.getWindow( this.$clippableScrollableContainer
) ) :
4021 this.$clippableScrollableContainer
;
4022 this.$clippableScroller
.on( 'scroll', this.onClippableScrollHandler
);
4023 this.$clippableWindow
= $( this.getElementWindow() )
4024 .on( 'resize', this.onClippableWindowResizeHandler
);
4025 // Initial clip after visible
4028 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
4029 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4031 this.$clippableScrollableContainer
= null;
4032 this.$clippableScroller
.off( 'scroll', this.onClippableScrollHandler
);
4033 this.$clippableScroller
= null;
4034 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
4035 this.$clippableWindow
= null;
4043 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4045 * @return {boolean} Element will be clipped to the visible area
4047 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
4048 return this.clipping
;
4052 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
4054 * @return {boolean} Part of the element is being clipped
4056 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
4057 return this.clippedHorizontally
|| this.clippedVertically
;
4061 * Check if the right of the element is being clipped by the nearest scrollable container.
4063 * @return {boolean} Part of the element is being clipped
4065 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
4066 return this.clippedHorizontally
;
4070 * Check if the bottom of the element is being clipped by the nearest scrollable container.
4072 * @return {boolean} Part of the element is being clipped
4074 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
4075 return this.clippedVertically
;
4079 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
4081 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
4082 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
4084 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
4085 this.idealWidth
= width
;
4086 this.idealHeight
= height
;
4088 if ( !this.clipping
) {
4089 // Update dimensions
4090 this.$clippable
.css( { width
: width
, height
: height
} );
4092 // While clipping, idealWidth and idealHeight are not considered
4096 * Clip element to visible boundaries and allow scrolling when needed. You should call this method
4097 * when the element's natural height changes.
4099 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
4100 * overlapped by, the visible area of the nearest scrollable container.
4102 * Because calling clip() when the natural height changes isn't always possible, we also set
4103 * max-height when the element isn't being clipped. This means that if the element tries to grow
4104 * beyond the edge, something reasonable will happen before clip() is called.
4108 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
4109 var $container
, extraHeight
, extraWidth
, ccOffset
,
4110 $scrollableContainer
, scOffset
, scHeight
, scWidth
,
4111 ccWidth
, scrollerIsWindow
, scrollTop
, scrollLeft
,
4112 desiredWidth
, desiredHeight
, allotedWidth
, allotedHeight
,
4113 naturalWidth
, naturalHeight
, clipWidth
, clipHeight
,
4114 buffer
= 7; // Chosen by fair dice roll
4116 if ( !this.clipping
) {
4117 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
4121 $container
= this.$clippableContainer
|| this.$clippable
;
4122 extraHeight
= $container
.outerHeight() - this.$clippable
.outerHeight();
4123 extraWidth
= $container
.outerWidth() - this.$clippable
.outerWidth();
4124 ccOffset
= $container
.offset();
4125 $scrollableContainer
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
4126 this.$clippableWindow
: this.$clippableScrollableContainer
;
4127 scOffset
= $scrollableContainer
.offset() || { top
: 0, left
: 0 };
4128 scHeight
= $scrollableContainer
.innerHeight() - buffer
;
4129 scWidth
= $scrollableContainer
.innerWidth() - buffer
;
4130 ccWidth
= $container
.outerWidth() + buffer
;
4131 scrollerIsWindow
= this.$clippableScroller
[ 0 ] === this.$clippableWindow
[ 0 ];
4132 scrollTop
= scrollerIsWindow
? this.$clippableScroller
.scrollTop() : 0;
4133 scrollLeft
= scrollerIsWindow
? this.$clippableScroller
.scrollLeft() : 0;
4134 desiredWidth
= ccOffset
.left
< 0 ?
4135 ccWidth
+ ccOffset
.left
:
4136 ( scOffset
.left
+ scrollLeft
+ scWidth
) - ccOffset
.left
;
4137 desiredHeight
= ( scOffset
.top
+ scrollTop
+ scHeight
) - ccOffset
.top
;
4138 // It should never be desirable to exceed the dimensions of the browser viewport... right?
4139 desiredWidth
= Math
.min( desiredWidth
, document
.documentElement
.clientWidth
);
4140 desiredHeight
= Math
.min( desiredHeight
, document
.documentElement
.clientHeight
);
4141 allotedWidth
= Math
.ceil( desiredWidth
- extraWidth
);
4142 allotedHeight
= Math
.ceil( desiredHeight
- extraHeight
);
4143 naturalWidth
= this.$clippable
.prop( 'scrollWidth' );
4144 naturalHeight
= this.$clippable
.prop( 'scrollHeight' );
4145 clipWidth
= allotedWidth
< naturalWidth
;
4146 clipHeight
= allotedHeight
< naturalHeight
;
4149 this.$clippable
.css( {
4150 overflowX
: 'scroll',
4151 width
: Math
.max( 0, allotedWidth
),
4155 this.$clippable
.css( {
4157 width
: this.idealWidth
? this.idealWidth
- extraWidth
: '',
4158 maxWidth
: Math
.max( 0, allotedWidth
)
4162 this.$clippable
.css( {
4163 overflowY
: 'scroll',
4164 height
: Math
.max( 0, allotedHeight
),
4168 this.$clippable
.css( {
4170 height
: this.idealHeight
? this.idealHeight
- extraHeight
: '',
4171 maxHeight
: Math
.max( 0, allotedHeight
)
4175 // If we stopped clipping in at least one of the dimensions
4176 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
4177 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4180 this.clippedHorizontally
= clipWidth
;
4181 this.clippedVertically
= clipHeight
;
4187 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
4188 * By default, each popup has an anchor that points toward its origin.
4189 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
4192 * // A popup widget.
4193 * var popup = new OO.ui.PopupWidget( {
4194 * $content: $( '<p>Hi there!</p>' ),
4199 * $( 'body' ).append( popup.$element );
4200 * // To display the popup, toggle the visibility to 'true'.
4201 * popup.toggle( true );
4203 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
4206 * @extends OO.ui.Widget
4207 * @mixins OO.ui.mixin.LabelElement
4208 * @mixins OO.ui.mixin.ClippableElement
4211 * @param {Object} [config] Configuration options
4212 * @cfg {number} [width=320] Width of popup in pixels
4213 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
4214 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
4215 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
4216 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
4217 * popup is leaning towards the right of the screen.
4218 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
4219 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
4220 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
4221 * sentence in the given language.
4222 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
4223 * See the [OOjs UI docs on MediaWiki][3] for an example.
4224 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
4225 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
4226 * @cfg {jQuery} [$content] Content to append to the popup's body
4227 * @cfg {jQuery} [$footer] Content to append to the popup's footer
4228 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
4229 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
4230 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
4232 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
4233 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
4235 * @cfg {boolean} [padded=false] Add padding to the popup's body
4237 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
4238 // Configuration initialization
4239 config
= config
|| {};
4241 // Parent constructor
4242 OO
.ui
.PopupWidget
.parent
.call( this, config
);
4244 // Properties (must be set before ClippableElement constructor call)
4245 this.$body
= $( '<div>' );
4246 this.$popup
= $( '<div>' );
4248 // Mixin constructors
4249 OO
.ui
.mixin
.LabelElement
.call( this, config
);
4250 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, {
4251 $clippable
: this.$body
,
4252 $clippableContainer
: this.$popup
4256 this.$anchor
= $( '<div>' );
4257 // If undefined, will be computed lazily in updateDimensions()
4258 this.$container
= config
.$container
;
4259 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
4260 this.autoClose
= !!config
.autoClose
;
4261 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
4262 this.transitionTimeout
= null;
4264 this.width
= config
.width
!== undefined ? config
.width
: 320;
4265 this.height
= config
.height
!== undefined ? config
.height
: null;
4266 this.setAlignment( config
.align
);
4267 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
4268 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
4271 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
4272 this.$body
.addClass( 'oo-ui-popupWidget-body' );
4273 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
4275 .addClass( 'oo-ui-popupWidget-popup' )
4276 .append( this.$body
);
4278 .addClass( 'oo-ui-popupWidget' )
4279 .append( this.$popup
, this.$anchor
);
4280 // Move content, which was added to #$element by OO.ui.Widget, to the body
4281 // FIXME This is gross, we should use '$body' or something for the config
4282 if ( config
.$content
instanceof jQuery
) {
4283 this.$body
.append( config
.$content
);
4286 if ( config
.padded
) {
4287 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
4290 if ( config
.head
) {
4291 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
4292 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
4293 this.$head
= $( '<div>' )
4294 .addClass( 'oo-ui-popupWidget-head' )
4295 .append( this.$label
, this.closeButton
.$element
);
4296 this.$popup
.prepend( this.$head
);
4299 if ( config
.$footer
) {
4300 this.$footer
= $( '<div>' )
4301 .addClass( 'oo-ui-popupWidget-footer' )
4302 .append( config
.$footer
);
4303 this.$popup
.append( this.$footer
);
4306 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
4307 // that reference properties not initialized at that time of parent class construction
4308 // TODO: Find a better way to handle post-constructor setup
4309 this.visible
= false;
4310 this.$element
.addClass( 'oo-ui-element-hidden' );
4315 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
4316 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
4317 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
4322 * Handles mouse down events.
4325 * @param {MouseEvent} e Mouse down event
4327 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
4330 !$.contains( this.$element
[ 0 ], e
.target
) &&
4331 ( !this.$autoCloseIgnore
|| !this.$autoCloseIgnore
.has( e
.target
).length
)
4333 this.toggle( false );
4338 * Bind mouse down listener.
4342 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
4343 // Capture clicks outside popup
4344 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler
, true );
4348 * Handles close button click events.
4352 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
4353 if ( this.isVisible() ) {
4354 this.toggle( false );
4359 * Unbind mouse down listener.
4363 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
4364 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler
, true );
4368 * Handles key down events.
4371 * @param {KeyboardEvent} e Key down event
4373 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
4375 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
4378 this.toggle( false );
4380 e
.stopPropagation();
4385 * Bind key down listener.
4389 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
4390 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
4394 * Unbind key down listener.
4398 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
4399 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
4403 * Show, hide, or toggle the visibility of the anchor.
4405 * @param {boolean} [show] Show anchor, omit to toggle
4407 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
4408 show
= show
=== undefined ? !this.anchored
: !!show
;
4410 if ( this.anchored
!== show
) {
4412 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
4414 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
4416 this.anchored
= show
;
4421 * Check if the anchor is visible.
4423 * @return {boolean} Anchor is visible
4425 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
4432 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
4434 show
= show
=== undefined ? !this.isVisible() : !!show
;
4436 change
= show
!== this.isVisible();
4439 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
4443 if ( this.autoClose
) {
4444 this.bindMouseDownListener();
4445 this.bindKeyDownListener();
4447 this.updateDimensions();
4448 this.toggleClipping( true );
4450 this.toggleClipping( false );
4451 if ( this.autoClose
) {
4452 this.unbindMouseDownListener();
4453 this.unbindKeyDownListener();
4462 * Set the size of the popup.
4464 * Changing the size may also change the popup's position depending on the alignment.
4466 * @param {number} width Width in pixels
4467 * @param {number} height Height in pixels
4468 * @param {boolean} [transition=false] Use a smooth transition
4471 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
4473 this.height
= height
!== undefined ? height
: null;
4474 if ( this.isVisible() ) {
4475 this.updateDimensions( transition
);
4480 * Update the size and position.
4482 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
4483 * be called automatically.
4485 * @param {boolean} [transition=false] Use a smooth transition
4488 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
4489 var popupOffset
, originOffset
, containerLeft
, containerWidth
, containerRight
,
4490 popupLeft
, popupRight
, overlapLeft
, overlapRight
, anchorWidth
,
4494 if ( !this.$container
) {
4495 // Lazy-initialize $container if not specified in constructor
4496 this.$container
= $( this.getClosestScrollableElementContainer() );
4499 // Set height and width before measuring things, since it might cause our measurements
4500 // to change (e.g. due to scrollbars appearing or disappearing)
4503 height
: this.height
!== null ? this.height
: 'auto'
4506 // If we are in RTL, we need to flip the alignment, unless it is center
4507 if ( align
=== 'forwards' || align
=== 'backwards' ) {
4508 if ( this.$container
.css( 'direction' ) === 'rtl' ) {
4509 align
= ( { forwards
: 'force-left', backwards
: 'force-right' } )[ this.align
];
4511 align
= ( { forwards
: 'force-right', backwards
: 'force-left' } )[ this.align
];
4516 // Compute initial popupOffset based on alignment
4517 popupOffset
= this.width
* ( { 'force-left': -1, center
: -0.5, 'force-right': 0 } )[ align
];
4519 // Figure out if this will cause the popup to go beyond the edge of the container
4520 originOffset
= this.$element
.offset().left
;
4521 containerLeft
= this.$container
.offset().left
;
4522 containerWidth
= this.$container
.innerWidth();
4523 containerRight
= containerLeft
+ containerWidth
;
4524 popupLeft
= popupOffset
- this.containerPadding
;
4525 popupRight
= popupOffset
+ this.containerPadding
+ this.width
+ this.containerPadding
;
4526 overlapLeft
= ( originOffset
+ popupLeft
) - containerLeft
;
4527 overlapRight
= containerRight
- ( originOffset
+ popupRight
);
4529 // Adjust offset to make the popup not go beyond the edge, if needed
4530 if ( overlapRight
< 0 ) {
4531 popupOffset
+= overlapRight
;
4532 } else if ( overlapLeft
< 0 ) {
4533 popupOffset
-= overlapLeft
;
4536 // Adjust offset to avoid anchor being rendered too close to the edge
4537 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
4538 // TODO: Find a measurement that works for CSS anchors and image anchors
4539 anchorWidth
= this.$anchor
[ 0 ].scrollWidth
* 2;
4540 if ( popupOffset
+ this.width
< anchorWidth
) {
4541 popupOffset
= anchorWidth
- this.width
;
4542 } else if ( -popupOffset
< anchorWidth
) {
4543 popupOffset
= -anchorWidth
;
4546 // Prevent transition from being interrupted
4547 clearTimeout( this.transitionTimeout
);
4549 // Enable transition
4550 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
4553 // Position body relative to anchor
4554 this.$popup
.css( 'margin-left', popupOffset
);
4557 // Prevent transitioning after transition is complete
4558 this.transitionTimeout
= setTimeout( function () {
4559 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
4562 // Prevent transitioning immediately
4563 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
4566 // Reevaluate clipping state since we've relocated and resized the popup
4573 * Set popup alignment
4575 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
4576 * `backwards` or `forwards`.
4578 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
4579 // Validate alignment and transform deprecated values
4580 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
4581 this.align
= { left
: 'force-right', right
: 'force-left' }[ align
] || align
;
4583 this.align
= 'center';
4588 * Get popup alignment
4590 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
4591 * `backwards` or `forwards`.
4593 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
4598 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
4599 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
4600 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
4601 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
4607 * @param {Object} [config] Configuration options
4608 * @cfg {Object} [popup] Configuration to pass to popup
4609 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
4611 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
4612 // Configuration initialization
4613 config
= config
|| {};
4616 this.popup
= new OO
.ui
.PopupWidget( $.extend(
4617 { autoClose
: true },
4619 { $autoCloseIgnore
: this.$element
}
4628 * @return {OO.ui.PopupWidget} Popup widget
4630 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
4635 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
4636 * which is used to display additional information or options.
4639 * // Example of a popup button.
4640 * var popupButton = new OO.ui.PopupButtonWidget( {
4641 * label: 'Popup button with options',
4644 * $content: $( '<p>Additional options here.</p>' ),
4646 * align: 'force-left'
4649 * // Append the button to the DOM.
4650 * $( 'body' ).append( popupButton.$element );
4653 * @extends OO.ui.ButtonWidget
4654 * @mixins OO.ui.mixin.PopupElement
4657 * @param {Object} [config] Configuration options
4659 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
4660 // Parent constructor
4661 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
4663 // Mixin constructors
4664 OO
.ui
.mixin
.PopupElement
.call( this, config
);
4667 this.connect( this, { click
: 'onAction' } );
4671 .addClass( 'oo-ui-popupButtonWidget' )
4672 .attr( 'aria-haspopup', 'true' )
4673 .append( this.popup
.$element
);
4678 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
4679 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
4684 * Handle the button action being triggered.
4688 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
4689 this.popup
.toggle();
4693 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
4695 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
4700 * @extends OO.ui.mixin.GroupElement
4703 * @param {Object} [config] Configuration options
4705 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
4706 // Parent constructor
4707 OO
.ui
.mixin
.GroupWidget
.parent
.call( this, config
);
4712 OO
.inheritClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
4717 * Set the disabled state of the widget.
4719 * This will also update the disabled state of child widgets.
4721 * @param {boolean} disabled Disable widget
4724 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
4728 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
4729 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
4731 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
4733 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4734 this.items
[ i
].updateDisabled();
4742 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
4744 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
4745 * allows bidirectional communication.
4747 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
4755 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
4762 * Check if widget is disabled.
4764 * Checks parent if present, making disabled state inheritable.
4766 * @return {boolean} Widget is disabled
4768 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
4769 return this.disabled
||
4770 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
4774 * Set group element is in.
4776 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
4779 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
4781 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
4782 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
4784 // Initialize item disabled states
4785 this.updateDisabled();
4791 * OptionWidgets are special elements that can be selected and configured with data. The
4792 * data is often unique for each option, but it does not have to be. OptionWidgets are used
4793 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
4794 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
4796 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
4799 * @extends OO.ui.Widget
4800 * @mixins OO.ui.mixin.LabelElement
4801 * @mixins OO.ui.mixin.FlaggedElement
4804 * @param {Object} [config] Configuration options
4806 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
4807 // Configuration initialization
4808 config
= config
|| {};
4810 // Parent constructor
4811 OO
.ui
.OptionWidget
.parent
.call( this, config
);
4813 // Mixin constructors
4814 OO
.ui
.mixin
.ItemWidget
.call( this );
4815 OO
.ui
.mixin
.LabelElement
.call( this, config
);
4816 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
4819 this.selected
= false;
4820 this.highlighted
= false;
4821 this.pressed
= false;
4825 .data( 'oo-ui-optionWidget', this )
4826 .attr( 'role', 'option' )
4827 .attr( 'aria-selected', 'false' )
4828 .addClass( 'oo-ui-optionWidget' )
4829 .append( this.$label
);
4834 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
4835 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
4836 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
4837 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
4839 /* Static Properties */
4841 OO
.ui
.OptionWidget
.static.selectable
= true;
4843 OO
.ui
.OptionWidget
.static.highlightable
= true;
4845 OO
.ui
.OptionWidget
.static.pressable
= true;
4847 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
4852 * Check if the option can be selected.
4854 * @return {boolean} Item is selectable
4856 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
4857 return this.constructor.static.selectable
&& !this.isDisabled() && this.isVisible();
4861 * Check if the option can be highlighted. A highlight indicates that the option
4862 * may be selected when a user presses enter or clicks. Disabled items cannot
4865 * @return {boolean} Item is highlightable
4867 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
4868 return this.constructor.static.highlightable
&& !this.isDisabled() && this.isVisible();
4872 * Check if the option can be pressed. The pressed state occurs when a user mouses
4873 * down on an item, but has not yet let go of the mouse.
4875 * @return {boolean} Item is pressable
4877 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
4878 return this.constructor.static.pressable
&& !this.isDisabled() && this.isVisible();
4882 * Check if the option is selected.
4884 * @return {boolean} Item is selected
4886 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
4887 return this.selected
;
4891 * Check if the option is highlighted. A highlight indicates that the
4892 * item may be selected when a user presses enter or clicks.
4894 * @return {boolean} Item is highlighted
4896 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
4897 return this.highlighted
;
4901 * Check if the option is pressed. The pressed state occurs when a user mouses
4902 * down on an item, but has not yet let go of the mouse. The item may appear
4903 * selected, but it will not be selected until the user releases the mouse.
4905 * @return {boolean} Item is pressed
4907 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
4908 return this.pressed
;
4912 * Set the option’s selected state. In general, all modifications to the selection
4913 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
4914 * method instead of this method.
4916 * @param {boolean} [state=false] Select option
4919 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
4920 if ( this.constructor.static.selectable
) {
4921 this.selected
= !!state
;
4923 .toggleClass( 'oo-ui-optionWidget-selected', state
)
4924 .attr( 'aria-selected', state
.toString() );
4925 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
4926 this.scrollElementIntoView();
4928 this.updateThemeClasses();
4934 * Set the option’s highlighted state. In general, all programmatic
4935 * modifications to the highlight should be handled by the
4936 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
4937 * method instead of this method.
4939 * @param {boolean} [state=false] Highlight option
4942 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
4943 if ( this.constructor.static.highlightable
) {
4944 this.highlighted
= !!state
;
4945 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
4946 this.updateThemeClasses();
4952 * Set the option’s pressed state. In general, all
4953 * programmatic modifications to the pressed state should be handled by the
4954 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
4955 * method instead of this method.
4957 * @param {boolean} [state=false] Press option
4960 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
4961 if ( this.constructor.static.pressable
) {
4962 this.pressed
= !!state
;
4963 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
4964 this.updateThemeClasses();
4970 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
4971 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
4972 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
4975 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
4976 * information, please see the [OOjs UI documentation on MediaWiki][1].
4979 * // Example of a select widget with three options
4980 * var select = new OO.ui.SelectWidget( {
4982 * new OO.ui.OptionWidget( {
4984 * label: 'Option One',
4986 * new OO.ui.OptionWidget( {
4988 * label: 'Option Two',
4990 * new OO.ui.OptionWidget( {
4992 * label: 'Option Three',
4996 * $( 'body' ).append( select.$element );
4998 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5002 * @extends OO.ui.Widget
5003 * @mixins OO.ui.mixin.GroupWidget
5006 * @param {Object} [config] Configuration options
5007 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
5008 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
5009 * the [OOjs UI documentation on MediaWiki] [2] for examples.
5010 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5012 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
5013 // Configuration initialization
5014 config
= config
|| {};
5016 // Parent constructor
5017 OO
.ui
.SelectWidget
.parent
.call( this, config
);
5019 // Mixin constructors
5020 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
5023 this.pressed
= false;
5024 this.selecting
= null;
5025 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
5026 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
5027 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
5028 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
5029 this.keyPressBuffer
= '';
5030 this.keyPressBufferTimer
= null;
5031 this.blockMouseOverEvents
= 0;
5034 this.connect( this, {
5038 focus
: this.onFocus
.bind( this ),
5039 mousedown
: this.onMouseDown
.bind( this ),
5040 mouseover
: this.onMouseOver
.bind( this ),
5041 mouseleave
: this.onMouseLeave
.bind( this )
5046 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
5047 .attr( 'role', 'listbox' );
5048 if ( Array
.isArray( config
.items
) ) {
5049 this.addItems( config
.items
);
5055 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
5057 // Need to mixin base class as well
5058 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupElement
);
5059 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
5062 OO
.ui
.SelectWidget
.static.passAllFilter = function () {
5071 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
5073 * @param {OO.ui.OptionWidget|null} item Highlighted item
5079 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
5080 * pressed state of an option.
5082 * @param {OO.ui.OptionWidget|null} item Pressed item
5088 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
5090 * @param {OO.ui.OptionWidget|null} item Selected item
5095 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
5096 * @param {OO.ui.OptionWidget} item Chosen item
5102 * An `add` event is emitted when options are added to the select with the #addItems method.
5104 * @param {OO.ui.OptionWidget[]} items Added items
5105 * @param {number} index Index of insertion point
5111 * A `remove` event is emitted when options are removed from the select with the #clearItems
5112 * or #removeItems methods.
5114 * @param {OO.ui.OptionWidget[]} items Removed items
5120 * Handle focus events
5123 * @param {jQuery.Event} event
5125 OO
.ui
.SelectWidget
.prototype.onFocus = function () {
5126 // The styles for focus state depend on one of the items being selected.
5127 if ( !this.getSelectedItem() ) {
5128 this.selectItem( this.getFirstSelectableItem() );
5133 * Handle mouse down events.
5136 * @param {jQuery.Event} e Mouse down event
5138 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
5141 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
5142 this.togglePressed( true );
5143 item
= this.getTargetItem( e
);
5144 if ( item
&& item
.isSelectable() ) {
5145 this.pressItem( item
);
5146 this.selecting
= item
;
5147 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
5148 this.getElementDocument().addEventListener( 'mousemove', this.onMouseMoveHandler
, true );
5155 * Handle mouse up events.
5158 * @param {MouseEvent} e Mouse up event
5160 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
5163 this.togglePressed( false );
5164 if ( !this.selecting
) {
5165 item
= this.getTargetItem( e
);
5166 if ( item
&& item
.isSelectable() ) {
5167 this.selecting
= item
;
5170 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
&& this.selecting
) {
5171 this.pressItem( null );
5172 this.chooseItem( this.selecting
);
5173 this.selecting
= null;
5176 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
5177 this.getElementDocument().removeEventListener( 'mousemove', this.onMouseMoveHandler
, true );
5183 * Handle mouse move events.
5186 * @param {MouseEvent} e Mouse move event
5188 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
5191 if ( !this.isDisabled() && this.pressed
) {
5192 item
= this.getTargetItem( e
);
5193 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
5194 this.pressItem( item
);
5195 this.selecting
= item
;
5201 * Handle mouse over events.
5204 * @param {jQuery.Event} e Mouse over event
5206 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
5208 if ( this.blockMouseOverEvents
) {
5211 if ( !this.isDisabled() ) {
5212 item
= this.getTargetItem( e
);
5213 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
5219 * Handle mouse leave events.
5222 * @param {jQuery.Event} e Mouse over event
5224 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
5225 if ( !this.isDisabled() ) {
5226 this.highlightItem( null );
5232 * Handle key down events.
5235 * @param {KeyboardEvent} e Key down event
5237 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
5240 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
5242 if ( !this.isDisabled() && this.isVisible() ) {
5243 switch ( e
.keyCode
) {
5244 case OO
.ui
.Keys
.ENTER
:
5245 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
5246 // Was only highlighted, now let's select it. No-op if already selected.
5247 this.chooseItem( currentItem
);
5252 case OO
.ui
.Keys
.LEFT
:
5253 this.clearKeyPressBuffer();
5254 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
5257 case OO
.ui
.Keys
.DOWN
:
5258 case OO
.ui
.Keys
.RIGHT
:
5259 this.clearKeyPressBuffer();
5260 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
5263 case OO
.ui
.Keys
.ESCAPE
:
5264 case OO
.ui
.Keys
.TAB
:
5265 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
5266 currentItem
.setHighlighted( false );
5268 this.unbindKeyDownListener();
5269 this.unbindKeyPressListener();
5270 // Don't prevent tabbing away / defocusing
5276 if ( nextItem
.constructor.static.highlightable
) {
5277 this.highlightItem( nextItem
);
5279 this.chooseItem( nextItem
);
5281 this.scrollItemIntoView( nextItem
);
5286 e
.stopPropagation();
5292 * Bind key down listener.
5296 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
5297 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler
, true );
5301 * Unbind key down listener.
5305 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
5306 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler
, true );
5310 * Scroll item into view, preventing spurious mouse highlight actions from happening.
5312 * @param {OO.ui.OptionWidget} item Item to scroll into view
5314 OO
.ui
.SelectWidget
.prototype.scrollItemIntoView = function ( item
) {
5316 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling
5317 // and around 100-150 ms after it is finished.
5318 this.blockMouseOverEvents
++;
5319 item
.scrollElementIntoView().done( function () {
5320 setTimeout( function () {
5321 widget
.blockMouseOverEvents
--;
5327 * Clear the key-press buffer
5331 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
5332 if ( this.keyPressBufferTimer
) {
5333 clearTimeout( this.keyPressBufferTimer
);
5334 this.keyPressBufferTimer
= null;
5336 this.keyPressBuffer
= '';
5340 * Handle key press events.
5343 * @param {KeyboardEvent} e Key press event
5345 OO
.ui
.SelectWidget
.prototype.onKeyPress = function ( e
) {
5346 var c
, filter
, item
;
5348 if ( !e
.charCode
) {
5349 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
5350 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
5355 if ( String
.fromCodePoint
) {
5356 c
= String
.fromCodePoint( e
.charCode
);
5358 c
= String
.fromCharCode( e
.charCode
);
5361 if ( this.keyPressBufferTimer
) {
5362 clearTimeout( this.keyPressBufferTimer
);
5364 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
5366 item
= this.getHighlightedItem() || this.getSelectedItem();
5368 if ( this.keyPressBuffer
=== c
) {
5369 // Common (if weird) special case: typing "xxxx" will cycle through all
5370 // the items beginning with "x".
5372 item
= this.getRelativeSelectableItem( item
, 1 );
5375 this.keyPressBuffer
+= c
;
5378 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
5379 if ( !item
|| !filter( item
) ) {
5380 item
= this.getRelativeSelectableItem( item
, 1, filter
);
5383 if ( item
.constructor.static.highlightable
) {
5384 this.highlightItem( item
);
5386 this.chooseItem( item
);
5388 this.scrollItemIntoView( item
);
5392 e
.stopPropagation();
5396 * Get a matcher for the specific string
5399 * @param {string} s String to match against items
5400 * @param {boolean} [exact=false] Only accept exact matches
5401 * @return {Function} function ( OO.ui.OptionItem ) => boolean
5403 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
, exact
) {
5406 if ( s
.normalize
) {
5409 s
= exact
? s
.trim() : s
.replace( /^\s+/, '' );
5410 re
= '^\\s*' + s
.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
5414 re
= new RegExp( re
, 'i' );
5415 return function ( item
) {
5416 var l
= item
.getLabel();
5417 if ( typeof l
!== 'string' ) {
5418 l
= item
.$label
.text();
5420 if ( l
.normalize
) {
5423 return re
.test( l
);
5428 * Bind key press listener.
5432 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
5433 this.getElementWindow().addEventListener( 'keypress', this.onKeyPressHandler
, true );
5437 * Unbind key down listener.
5439 * If you override this, be sure to call this.clearKeyPressBuffer() from your
5444 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
5445 this.getElementWindow().removeEventListener( 'keypress', this.onKeyPressHandler
, true );
5446 this.clearKeyPressBuffer();
5450 * Visibility change handler
5453 * @param {boolean} visible
5455 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
5457 this.clearKeyPressBuffer();
5462 * Get the closest item to a jQuery.Event.
5465 * @param {jQuery.Event} e
5466 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
5468 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
5469 return $( e
.target
).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
5473 * Get selected item.
5475 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
5477 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
5480 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5481 if ( this.items
[ i
].isSelected() ) {
5482 return this.items
[ i
];
5489 * Get highlighted item.
5491 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
5493 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
5496 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5497 if ( this.items
[ i
].isHighlighted() ) {
5498 return this.items
[ i
];
5505 * Toggle pressed state.
5507 * Press is a state that occurs when a user mouses down on an item, but
5508 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
5509 * until the user releases the mouse.
5511 * @param {boolean} pressed An option is being pressed
5513 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
5514 if ( pressed
=== undefined ) {
5515 pressed
= !this.pressed
;
5517 if ( pressed
!== this.pressed
) {
5519 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
5520 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
5521 this.pressed
= pressed
;
5526 * Highlight an option. If the `item` param is omitted, no options will be highlighted
5527 * and any existing highlight will be removed. The highlight is mutually exclusive.
5529 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
5533 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
5534 var i
, len
, highlighted
,
5537 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5538 highlighted
= this.items
[ i
] === item
;
5539 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
5540 this.items
[ i
].setHighlighted( highlighted
);
5545 this.emit( 'highlight', item
);
5552 * Fetch an item by its label.
5554 * @param {string} label Label of the item to select.
5555 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
5556 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
5558 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
5560 len
= this.items
.length
,
5561 filter
= this.getItemMatcher( label
, true );
5563 for ( i
= 0; i
< len
; i
++ ) {
5564 item
= this.items
[ i
];
5565 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
5572 filter
= this.getItemMatcher( label
, false );
5573 for ( i
= 0; i
< len
; i
++ ) {
5574 item
= this.items
[ i
];
5575 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
5591 * Programmatically select an option by its label. If the item does not exist,
5592 * all options will be deselected.
5594 * @param {string} [label] Label of the item to select.
5595 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
5599 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
5600 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
5601 if ( label
=== undefined || !itemFromLabel
) {
5602 return this.selectItem();
5604 return this.selectItem( itemFromLabel
);
5608 * Programmatically select an option by its data. If the `data` parameter is omitted,
5609 * or if the item does not exist, all options will be deselected.
5611 * @param {Object|string} [data] Value of the item to select, omit to deselect all
5615 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
5616 var itemFromData
= this.getItemFromData( data
);
5617 if ( data
=== undefined || !itemFromData
) {
5618 return this.selectItem();
5620 return this.selectItem( itemFromData
);
5624 * Programmatically select an option by its reference. If the `item` parameter is omitted,
5625 * all options will be deselected.
5627 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
5631 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
5632 var i
, len
, selected
,
5635 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5636 selected
= this.items
[ i
] === item
;
5637 if ( this.items
[ i
].isSelected() !== selected
) {
5638 this.items
[ i
].setSelected( selected
);
5643 this.emit( 'select', item
);
5652 * Press is a state that occurs when a user mouses down on an item, but has not
5653 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
5654 * releases the mouse.
5656 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
5660 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
5661 var i
, len
, pressed
,
5664 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5665 pressed
= this.items
[ i
] === item
;
5666 if ( this.items
[ i
].isPressed() !== pressed
) {
5667 this.items
[ i
].setPressed( pressed
);
5672 this.emit( 'press', item
);
5681 * Note that ‘choose’ should never be modified programmatically. A user can choose
5682 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
5683 * use the #selectItem method.
5685 * This method is identical to #selectItem, but may vary in subclasses that take additional action
5686 * when users choose an item with the keyboard or mouse.
5688 * @param {OO.ui.OptionWidget} item Item to choose
5692 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
5694 this.selectItem( item
);
5695 this.emit( 'choose', item
);
5702 * Get an option by its position relative to the specified item (or to the start of the option array,
5703 * if item is `null`). The direction in which to search through the option array is specified with a
5704 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
5705 * `null` if there are no options in the array.
5707 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
5708 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
5709 * @param {Function} filter Only consider items for which this function returns
5710 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
5711 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
5713 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
, filter
) {
5714 var currentIndex
, nextIndex
, i
,
5715 increase
= direction
> 0 ? 1 : -1,
5716 len
= this.items
.length
;
5718 if ( !$.isFunction( filter
) ) {
5719 filter
= OO
.ui
.SelectWidget
.static.passAllFilter
;
5722 if ( item
instanceof OO
.ui
.OptionWidget
) {
5723 currentIndex
= this.items
.indexOf( item
);
5724 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
5726 // If no item is selected and moving forward, start at the beginning.
5727 // If moving backward, start at the end.
5728 nextIndex
= direction
> 0 ? 0 : len
- 1;
5731 for ( i
= 0; i
< len
; i
++ ) {
5732 item
= this.items
[ nextIndex
];
5733 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
5736 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
5742 * Get the next selectable item or `null` if there are no selectable items.
5743 * Disabled options and menu-section markers and breaks are not selectable.
5745 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
5747 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
5750 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5751 item
= this.items
[ i
];
5752 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() ) {
5761 * Add an array of options to the select. Optionally, an index number can be used to
5762 * specify an insertion point.
5764 * @param {OO.ui.OptionWidget[]} items Items to add
5765 * @param {number} [index] Index to insert items after
5769 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
5771 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
5773 // Always provide an index, even if it was omitted
5774 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
5780 * Remove the specified array of options from the select. Options will be detached
5781 * from the DOM, not removed, so they can be reused later. To remove all options from
5782 * the select, you may wish to use the #clearItems method instead.
5784 * @param {OO.ui.OptionWidget[]} items Items to remove
5788 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
5791 // Deselect items being removed
5792 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
5794 if ( item
.isSelected() ) {
5795 this.selectItem( null );
5800 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
5802 this.emit( 'remove', items
);
5808 * Clear all options from the select. Options will be detached from the DOM, not removed,
5809 * so that they can be reused later. To remove a subset of options from the select, use
5810 * the #removeItems method.
5815 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
5816 var items
= this.items
.slice();
5819 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
5822 this.selectItem( null );
5824 this.emit( 'remove', items
);
5830 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
5831 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
5832 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
5833 * options. For more information about options and selects, please see the
5834 * [OOjs UI documentation on MediaWiki][1].
5837 * // Decorated options in a select widget
5838 * var select = new OO.ui.SelectWidget( {
5840 * new OO.ui.DecoratedOptionWidget( {
5842 * label: 'Option with icon',
5845 * new OO.ui.DecoratedOptionWidget( {
5847 * label: 'Option with indicator',
5852 * $( 'body' ).append( select.$element );
5854 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5857 * @extends OO.ui.OptionWidget
5858 * @mixins OO.ui.mixin.IconElement
5859 * @mixins OO.ui.mixin.IndicatorElement
5862 * @param {Object} [config] Configuration options
5864 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
5865 // Parent constructor
5866 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
5868 // Mixin constructors
5869 OO
.ui
.mixin
.IconElement
.call( this, config
);
5870 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
5874 .addClass( 'oo-ui-decoratedOptionWidget' )
5875 .prepend( this.$icon
)
5876 .append( this.$indicator
);
5881 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
5882 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
5883 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
5886 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
5887 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
5888 * the [OOjs UI documentation on MediaWiki] [1] for more information.
5890 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
5893 * @extends OO.ui.DecoratedOptionWidget
5896 * @param {Object} [config] Configuration options
5898 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
5899 // Configuration initialization
5900 config
= $.extend( { icon
: 'check' }, config
);
5902 // Parent constructor
5903 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
5907 .attr( 'role', 'menuitem' )
5908 .addClass( 'oo-ui-menuOptionWidget' );
5913 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
5915 /* Static Properties */
5917 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
5920 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
5921 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
5924 * var myDropdown = new OO.ui.DropdownWidget( {
5927 * new OO.ui.MenuSectionOptionWidget( {
5930 * new OO.ui.MenuOptionWidget( {
5932 * label: 'Welsh Corgi'
5934 * new OO.ui.MenuOptionWidget( {
5936 * label: 'Standard Poodle'
5938 * new OO.ui.MenuSectionOptionWidget( {
5941 * new OO.ui.MenuOptionWidget( {
5948 * $( 'body' ).append( myDropdown.$element );
5951 * @extends OO.ui.DecoratedOptionWidget
5954 * @param {Object} [config] Configuration options
5956 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
5957 // Parent constructor
5958 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
5961 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' );
5966 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
5968 /* Static Properties */
5970 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
5972 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
5975 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
5976 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
5977 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
5978 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
5979 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
5980 * and customized to be opened, closed, and displayed as needed.
5982 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
5983 * mouse outside the menu.
5985 * Menus also have support for keyboard interaction:
5987 * - Enter/Return key: choose and select a menu option
5988 * - Up-arrow key: highlight the previous menu option
5989 * - Down-arrow key: highlight the next menu option
5990 * - Esc key: hide the menu
5992 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
5993 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5996 * @extends OO.ui.SelectWidget
5997 * @mixins OO.ui.mixin.ClippableElement
6000 * @param {Object} [config] Configuration options
6001 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
6002 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
6003 * and {@link OO.ui.mixin.LookupElement LookupElement}
6004 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
6005 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiSelectWidget CapsuleMultiSelectWidget}
6006 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
6007 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
6008 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
6009 * that button, unless the button (or its parent widget) is passed in here.
6010 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
6011 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
6013 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
6014 // Configuration initialization
6015 config
= config
|| {};
6017 // Parent constructor
6018 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
6020 // Mixin constructors
6021 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
6024 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
6025 this.filterFromInput
= !!config
.filterFromInput
;
6026 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
6027 this.$widget
= config
.widget
? config
.widget
.$element
: null;
6028 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
6029 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
6033 .addClass( 'oo-ui-menuSelectWidget' )
6034 .attr( 'role', 'menu' );
6036 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
6037 // that reference properties not initialized at that time of parent class construction
6038 // TODO: Find a better way to handle post-constructor setup
6039 this.visible
= false;
6040 this.$element
.addClass( 'oo-ui-element-hidden' );
6045 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
6046 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
6051 * Handles document mouse down events.
6054 * @param {MouseEvent} e Mouse down event
6056 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
6058 !OO
.ui
.contains( this.$element
[ 0 ], e
.target
, true ) &&
6059 ( !this.$widget
|| !OO
.ui
.contains( this.$widget
[ 0 ], e
.target
, true ) )
6061 this.toggle( false );
6068 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
6069 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
6071 if ( !this.isDisabled() && this.isVisible() ) {
6072 switch ( e
.keyCode
) {
6073 case OO
.ui
.Keys
.LEFT
:
6074 case OO
.ui
.Keys
.RIGHT
:
6075 // Do nothing if a text field is associated, arrow keys will be handled natively
6076 if ( !this.$input
) {
6077 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
6080 case OO
.ui
.Keys
.ESCAPE
:
6081 case OO
.ui
.Keys
.TAB
:
6082 if ( currentItem
) {
6083 currentItem
.setHighlighted( false );
6085 this.toggle( false );
6086 // Don't prevent tabbing away, prevent defocusing
6087 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
6089 e
.stopPropagation();
6093 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
6100 * Update menu item visibility after input changes.
6104 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
6106 len
= this.items
.length
,
6107 showAll
= !this.isVisible(),
6108 filter
= showAll
? null : this.getItemMatcher( this.$input
.val() );
6110 for ( i
= 0; i
< len
; i
++ ) {
6111 item
= this.items
[ i
];
6112 if ( item
instanceof OO
.ui
.OptionWidget
) {
6113 item
.toggle( showAll
|| filter( item
) );
6117 // Reevaluate clipping
6124 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
6125 if ( this.$input
) {
6126 this.$input
.on( 'keydown', this.onKeyDownHandler
);
6128 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyDownListener
.call( this );
6135 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
6136 if ( this.$input
) {
6137 this.$input
.off( 'keydown', this.onKeyDownHandler
);
6139 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyDownListener
.call( this );
6146 OO
.ui
.MenuSelectWidget
.prototype.bindKeyPressListener = function () {
6147 if ( this.$input
) {
6148 if ( this.filterFromInput
) {
6149 this.$input
.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
6152 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyPressListener
.call( this );
6159 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyPressListener = function () {
6160 if ( this.$input
) {
6161 if ( this.filterFromInput
) {
6162 this.$input
.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
6163 this.updateItemVisibility();
6166 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyPressListener
.call( this );
6173 * When a user chooses an item, the menu is closed.
6175 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
6176 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
6178 * @param {OO.ui.OptionWidget} item Item to choose
6181 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
6182 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
6183 this.toggle( false );
6190 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
6192 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
6194 // Reevaluate clipping
6203 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
6205 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
6207 // Reevaluate clipping
6216 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
6218 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
6220 // Reevaluate clipping
6229 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
6232 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
6233 change
= visible
!== this.isVisible();
6236 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
6240 this.bindKeyDownListener();
6241 this.bindKeyPressListener();
6243 this.toggleClipping( true );
6245 if ( this.getSelectedItem() ) {
6246 this.getSelectedItem().scrollElementIntoView( { duration
: 0 } );
6250 if ( this.autoHide
) {
6251 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
6254 this.unbindKeyDownListener();
6255 this.unbindKeyPressListener();
6256 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
6257 this.toggleClipping( false );
6265 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
6266 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
6267 * users can interact with it.
6269 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
6270 * OO.ui.DropdownInputWidget instead.
6273 * // Example: A DropdownWidget with a menu that contains three options
6274 * var dropDown = new OO.ui.DropdownWidget( {
6275 * label: 'Dropdown menu: Select a menu option',
6278 * new OO.ui.MenuOptionWidget( {
6282 * new OO.ui.MenuOptionWidget( {
6286 * new OO.ui.MenuOptionWidget( {
6294 * $( 'body' ).append( dropDown.$element );
6296 * dropDown.getMenu().selectItemByData( 'b' );
6298 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
6300 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
6302 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
6305 * @extends OO.ui.Widget
6306 * @mixins OO.ui.mixin.IconElement
6307 * @mixins OO.ui.mixin.IndicatorElement
6308 * @mixins OO.ui.mixin.LabelElement
6309 * @mixins OO.ui.mixin.TitledElement
6310 * @mixins OO.ui.mixin.TabIndexedElement
6313 * @param {Object} [config] Configuration options
6314 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
6315 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
6316 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
6317 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
6319 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
6320 // Configuration initialization
6321 config
= $.extend( { indicator
: 'down' }, config
);
6323 // Parent constructor
6324 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
6326 // Properties (must be set before TabIndexedElement constructor call)
6327 this.$handle
= this.$( '<span>' );
6328 this.$overlay
= config
.$overlay
|| this.$element
;
6330 // Mixin constructors
6331 OO
.ui
.mixin
.IconElement
.call( this, config
);
6332 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
6333 OO
.ui
.mixin
.LabelElement
.call( this, config
);
6334 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
6335 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
6338 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend( {
6340 $container
: this.$element
6345 click
: this.onClick
.bind( this ),
6346 keydown
: this.onKeyDown
.bind( this )
6348 this.menu
.connect( this, { select
: 'onMenuSelect' } );
6352 .addClass( 'oo-ui-dropdownWidget-handle' )
6353 .append( this.$icon
, this.$label
, this.$indicator
);
6355 .addClass( 'oo-ui-dropdownWidget' )
6356 .append( this.$handle
);
6357 this.$overlay
.append( this.menu
.$element
);
6362 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
6363 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
6364 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
6365 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
6366 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
6367 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
6374 * @return {OO.ui.MenuSelectWidget} Menu of widget
6376 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
6381 * Handles menu select events.
6384 * @param {OO.ui.MenuOptionWidget} item Selected menu item
6386 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
6390 this.setLabel( null );
6394 selectedLabel
= item
.getLabel();
6396 // If the label is a DOM element, clone it, because setLabel will append() it
6397 if ( selectedLabel
instanceof jQuery
) {
6398 selectedLabel
= selectedLabel
.clone();
6401 this.setLabel( selectedLabel
);
6405 * Handle mouse click events.
6408 * @param {jQuery.Event} e Mouse click event
6410 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
6411 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
6418 * Handle key down events.
6421 * @param {jQuery.Event} e Key down event
6423 OO
.ui
.DropdownWidget
.prototype.onKeyDown = function ( e
) {
6425 !this.isDisabled() &&
6427 e
.which
=== OO
.ui
.Keys
.ENTER
||
6429 !this.menu
.isVisible() &&
6431 e
.which
=== OO
.ui
.Keys
.SPACE
||
6432 e
.which
=== OO
.ui
.Keys
.UP
||
6433 e
.which
=== OO
.ui
.Keys
.DOWN
6444 * RadioOptionWidget is an option widget that looks like a radio button.
6445 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
6446 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6448 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
6451 * @extends OO.ui.OptionWidget
6454 * @param {Object} [config] Configuration options
6456 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
6457 // Configuration initialization
6458 config
= config
|| {};
6460 // Properties (must be done before parent constructor which calls #setDisabled)
6461 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
6463 // Parent constructor
6464 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
6467 this.radio
.$input
.on( 'focus', this.onInputFocus
.bind( this ) );
6470 // Remove implicit role, we're handling it ourselves
6471 this.radio
.$input
.attr( 'role', 'presentation' );
6473 .addClass( 'oo-ui-radioOptionWidget' )
6474 .attr( 'role', 'radio' )
6475 .attr( 'aria-checked', 'false' )
6476 .removeAttr( 'aria-selected' )
6477 .prepend( this.radio
.$element
);
6482 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
6484 /* Static Properties */
6486 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
6488 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
6490 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
6492 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
6497 * @param {jQuery.Event} e Focus event
6500 OO
.ui
.RadioOptionWidget
.prototype.onInputFocus = function () {
6501 this.radio
.$input
.blur();
6502 this.$element
.parent().focus();
6508 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
6509 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
6511 this.radio
.setSelected( state
);
6513 .attr( 'aria-checked', state
.toString() )
6514 .removeAttr( 'aria-selected' );
6522 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
6523 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
6525 this.radio
.setDisabled( this.isDisabled() );
6531 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
6532 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
6533 * an interface for adding, removing and selecting options.
6534 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
6536 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
6537 * OO.ui.RadioSelectInputWidget instead.
6540 * // A RadioSelectWidget with RadioOptions.
6541 * var option1 = new OO.ui.RadioOptionWidget( {
6543 * label: 'Selected radio option'
6546 * var option2 = new OO.ui.RadioOptionWidget( {
6548 * label: 'Unselected radio option'
6551 * var radioSelect=new OO.ui.RadioSelectWidget( {
6552 * items: [ option1, option2 ]
6555 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
6556 * radioSelect.selectItem( option1 );
6558 * $( 'body' ).append( radioSelect.$element );
6560 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6564 * @extends OO.ui.SelectWidget
6565 * @mixins OO.ui.mixin.TabIndexedElement
6568 * @param {Object} [config] Configuration options
6570 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
6571 // Parent constructor
6572 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
6574 // Mixin constructors
6575 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
6579 focus
: this.bindKeyDownListener
.bind( this ),
6580 blur
: this.unbindKeyDownListener
.bind( this )
6585 .addClass( 'oo-ui-radioSelectWidget' )
6586 .attr( 'role', 'radiogroup' );
6591 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
6592 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
6595 * Element that will stick under a specified container, even when it is inserted elsewhere in the
6596 * document (for example, in a OO.ui.Window's $overlay).
6598 * The elements's position is automatically calculated and maintained when window is resized or the
6599 * page is scrolled. If you reposition the container manually, you have to call #position to make
6600 * sure the element is still placed correctly.
6602 * As positioning is only possible when both the element and the container are attached to the DOM
6603 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
6604 * the #toggle method to display a floating popup, for example.
6610 * @param {Object} [config] Configuration options
6611 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
6612 * @cfg {jQuery} [$floatableContainer] Node to position below
6614 OO
.ui
.mixin
.FloatableElement
= function OoUiMixinFloatableElement( config
) {
6615 // Configuration initialization
6616 config
= config
|| {};
6619 this.$floatable
= null;
6620 this.$floatableContainer
= null;
6621 this.$floatableWindow
= null;
6622 this.$floatableClosestScrollable
= null;
6623 this.onFloatableScrollHandler
= this.position
.bind( this );
6624 this.onFloatableWindowResizeHandler
= this.position
.bind( this );
6627 this.setFloatableContainer( config
.$floatableContainer
);
6628 this.setFloatableElement( config
.$floatable
|| this.$element
);
6634 * Set floatable element.
6636 * If an element is already set, it will be cleaned up before setting up the new element.
6638 * @param {jQuery} $floatable Element to make floatable
6640 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableElement = function ( $floatable
) {
6641 if ( this.$floatable
) {
6642 this.$floatable
.removeClass( 'oo-ui-floatableElement-floatable' );
6643 this.$floatable
.css( { left
: '', top
: '' } );
6646 this.$floatable
= $floatable
.addClass( 'oo-ui-floatableElement-floatable' );
6651 * Set floatable container.
6653 * The element will be always positioned under the specified container.
6655 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
6657 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableContainer = function ( $floatableContainer
) {
6658 this.$floatableContainer
= $floatableContainer
;
6659 if ( this.$floatable
) {
6665 * Toggle positioning.
6667 * Do not turn positioning on until after the element is attached to the DOM and visible.
6669 * @param {boolean} [positioning] Enable positioning, omit to toggle
6672 OO
.ui
.mixin
.FloatableElement
.prototype.togglePositioning = function ( positioning
) {
6673 var closestScrollableOfContainer
, closestScrollableOfFloatable
;
6675 positioning
= positioning
=== undefined ? !this.positioning
: !!positioning
;
6677 if ( this.positioning
!== positioning
) {
6678 this.positioning
= positioning
;
6680 closestScrollableOfContainer
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatableContainer
[ 0 ] );
6681 closestScrollableOfFloatable
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatable
[ 0 ] );
6682 this.needsCustomPosition
= closestScrollableOfContainer
!== closestScrollableOfFloatable
;
6683 // If the scrollable is the root, we have to listen to scroll events
6684 // on the window because of browser inconsistencies.
6685 if ( $( closestScrollableOfContainer
).is( 'html, body' ) ) {
6686 closestScrollableOfContainer
= OO
.ui
.Element
.static.getWindow( closestScrollableOfContainer
);
6689 if ( positioning
) {
6690 this.$floatableWindow
= $( this.getElementWindow() );
6691 this.$floatableWindow
.on( 'resize', this.onFloatableWindowResizeHandler
);
6693 this.$floatableClosestScrollable
= $( closestScrollableOfContainer
);
6694 this.$floatableClosestScrollable
.on( 'scroll', this.onFloatableScrollHandler
);
6696 // Initial position after visible
6699 if ( this.$floatableWindow
) {
6700 this.$floatableWindow
.off( 'resize', this.onFloatableWindowResizeHandler
);
6701 this.$floatableWindow
= null;
6704 if ( this.$floatableClosestScrollable
) {
6705 this.$floatableClosestScrollable
.off( 'scroll', this.onFloatableScrollHandler
);
6706 this.$floatableClosestScrollable
= null;
6709 this.$floatable
.css( { left
: '', top
: '' } );
6717 * Check whether the bottom edge of the given element is within the viewport of the given container.
6720 * @param {jQuery} $element
6721 * @param {jQuery} $container
6724 OO
.ui
.mixin
.FloatableElement
.prototype.isElementInViewport = function ( $element
, $container
) {
6725 var elemRect
, contRect
,
6726 topEdgeInBounds
= false,
6727 leftEdgeInBounds
= false,
6728 bottomEdgeInBounds
= false,
6729 rightEdgeInBounds
= false;
6731 elemRect
= $element
[ 0 ].getBoundingClientRect();
6732 if ( $container
[ 0 ] === window
) {
6736 right
: document
.documentElement
.clientWidth
,
6737 bottom
: document
.documentElement
.clientHeight
6740 contRect
= $container
[ 0 ].getBoundingClientRect();
6743 if ( elemRect
.top
>= contRect
.top
&& elemRect
.top
<= contRect
.bottom
) {
6744 topEdgeInBounds
= true;
6746 if ( elemRect
.left
>= contRect
.left
&& elemRect
.left
<= contRect
.right
) {
6747 leftEdgeInBounds
= true;
6749 if ( elemRect
.bottom
>= contRect
.top
&& elemRect
.bottom
<= contRect
.bottom
) {
6750 bottomEdgeInBounds
= true;
6752 if ( elemRect
.right
>= contRect
.left
&& elemRect
.right
<= contRect
.right
) {
6753 rightEdgeInBounds
= true;
6756 // We only care that any part of the bottom edge is visible
6757 return bottomEdgeInBounds
&& ( leftEdgeInBounds
|| rightEdgeInBounds
);
6761 * Position the floatable below its container.
6763 * This should only be done when both of them are attached to the DOM and visible.
6767 OO
.ui
.mixin
.FloatableElement
.prototype.position = function () {
6770 if ( !this.positioning
) {
6774 if ( !this.isElementInViewport( this.$floatableContainer
, this.$floatableClosestScrollable
) ) {
6775 this.$floatable
.addClass( 'oo-ui-floatableElement-hidden' );
6778 this.$floatable
.removeClass( 'oo-ui-floatableElement-hidden' );
6781 if ( !this.needsCustomPosition
) {
6785 pos
= OO
.ui
.Element
.static.getRelativePosition( this.$floatableContainer
, this.$floatable
.offsetParent() );
6787 // Position under container
6788 pos
.top
+= this.$floatableContainer
.height();
6789 this.$floatable
.css( pos
);
6791 // We updated the position, so re-evaluate the clipping state.
6792 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
6793 // will not notice the need to update itself.)
6794 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
6795 // it not listen to the right events in the right places?
6804 * FloatingMenuSelectWidget is a menu that will stick under a specified
6805 * container, even when it is inserted elsewhere in the document (for example,
6806 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
6807 * menu from being clipped too aggresively.
6809 * The menu's position is automatically calculated and maintained when the menu
6810 * is toggled or the window is resized.
6812 * See OO.ui.ComboBoxInputWidget for an example of a widget that uses this class.
6815 * @extends OO.ui.MenuSelectWidget
6816 * @mixins OO.ui.mixin.FloatableElement
6819 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
6820 * Deprecated, omit this parameter and specify `$container` instead.
6821 * @param {Object} [config] Configuration options
6822 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
6824 OO
.ui
.FloatingMenuSelectWidget
= function OoUiFloatingMenuSelectWidget( inputWidget
, config
) {
6825 // Allow 'inputWidget' parameter and config for backwards compatibility
6826 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
6827 config
= inputWidget
;
6828 inputWidget
= config
.inputWidget
;
6831 // Configuration initialization
6832 config
= config
|| {};
6834 // Parent constructor
6835 OO
.ui
.FloatingMenuSelectWidget
.parent
.call( this, config
);
6837 // Properties (must be set before mixin constructors)
6838 this.inputWidget
= inputWidget
; // For backwards compatibility
6839 this.$container
= config
.$container
|| this.inputWidget
.$element
;
6841 // Mixins constructors
6842 OO
.ui
.mixin
.FloatableElement
.call( this, $.extend( {}, config
, { $floatableContainer
: this.$container
} ) );
6845 this.$element
.addClass( 'oo-ui-floatingMenuSelectWidget' );
6846 // For backwards compatibility
6847 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
6852 OO
.inheritClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
6853 OO
.mixinClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.mixin
.FloatableElement
);
6855 // For backwards compatibility
6856 OO
.ui
.TextInputMenuSelectWidget
= OO
.ui
.FloatingMenuSelectWidget
;
6863 OO
.ui
.FloatingMenuSelectWidget
.prototype.toggle = function ( visible
) {
6865 visible
= visible
=== undefined ? !this.isVisible() : !!visible
;
6866 change
= visible
!== this.isVisible();
6868 if ( change
&& visible
) {
6869 // Make sure the width is set before the parent method runs.
6870 this.setIdealSize( this.$container
.width() );
6874 // This will call this.clip(), which is nonsensical since we're not positioned yet...
6875 OO
.ui
.FloatingMenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
6878 this.togglePositioning( this.isVisible() );
6885 * InputWidget is the base class for all input widgets, which
6886 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
6887 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
6888 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
6890 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
6894 * @extends OO.ui.Widget
6895 * @mixins OO.ui.mixin.FlaggedElement
6896 * @mixins OO.ui.mixin.TabIndexedElement
6897 * @mixins OO.ui.mixin.TitledElement
6898 * @mixins OO.ui.mixin.AccessKeyedElement
6901 * @param {Object} [config] Configuration options
6902 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
6903 * @cfg {string} [value=''] The value of the input.
6904 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
6905 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
6906 * before it is accepted.
6908 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
6909 // Configuration initialization
6910 config
= config
|| {};
6912 // Parent constructor
6913 OO
.ui
.InputWidget
.parent
.call( this, config
);
6916 // See #reusePreInfuseDOM about config.$input
6917 this.$input
= config
.$input
|| this.getInputElement( config
);
6919 this.inputFilter
= config
.inputFilter
;
6921 // Mixin constructors
6922 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
6923 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
6924 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
6925 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$input
} ) );
6928 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
6932 .addClass( 'oo-ui-inputWidget-input' )
6933 .attr( 'name', config
.name
)
6934 .prop( 'disabled', this.isDisabled() );
6936 .addClass( 'oo-ui-inputWidget' )
6937 .append( this.$input
);
6938 this.setValue( config
.value
);
6940 this.setDir( config
.dir
);
6946 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
6947 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
6948 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
6949 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
6950 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
6952 /* Static Properties */
6954 OO
.ui
.InputWidget
.static.supportsSimpleLabel
= true;
6956 /* Static Methods */
6961 OO
.ui
.InputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
6962 config
= OO
.ui
.InputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
6963 // Reusing $input lets browsers preserve inputted values across page reloads (T114134)
6964 config
.$input
= $( node
).find( '.oo-ui-inputWidget-input' );
6971 OO
.ui
.InputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
6972 var state
= OO
.ui
.InputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
6973 if ( config
.$input
&& config
.$input
.length
) {
6974 state
.value
= config
.$input
.val();
6975 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
6976 state
.focus
= config
.$input
.is( ':focus' );
6986 * A change event is emitted when the value of the input changes.
6988 * @param {string} value
6994 * Get input element.
6996 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
6997 * different circumstances. The element must have a `value` property (like form elements).
7000 * @param {Object} config Configuration options
7001 * @return {jQuery} Input element
7003 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
7004 return $( '<input>' );
7008 * Handle potentially value-changing events.
7011 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
7013 OO
.ui
.InputWidget
.prototype.onEdit = function () {
7015 if ( !this.isDisabled() ) {
7016 // Allow the stack to clear so the value will be updated
7017 setTimeout( function () {
7018 widget
.setValue( widget
.$input
.val() );
7024 * Get the value of the input.
7026 * @return {string} Input value
7028 OO
.ui
.InputWidget
.prototype.getValue = function () {
7029 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
7030 // it, and we won't know unless they're kind enough to trigger a 'change' event.
7031 var value
= this.$input
.val();
7032 if ( this.value
!== value
) {
7033 this.setValue( value
);
7039 * Set the directionality of the input, either RTL (right-to-left) or LTR (left-to-right).
7041 * @deprecated since v0.13.1; use #setDir directly
7042 * @param {boolean} isRTL Directionality is right-to-left
7045 OO
.ui
.InputWidget
.prototype.setRTL = function ( isRTL
) {
7046 this.setDir( isRTL
? 'rtl' : 'ltr' );
7051 * Set the directionality of the input.
7053 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
7056 OO
.ui
.InputWidget
.prototype.setDir = function ( dir
) {
7057 this.$input
.prop( 'dir', dir
);
7062 * Set the value of the input.
7064 * @param {string} value New value
7068 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
7069 value
= this.cleanUpValue( value
);
7070 // Update the DOM if it has changed. Note that with cleanUpValue, it
7071 // is possible for the DOM value to change without this.value changing.
7072 if ( this.$input
.val() !== value
) {
7073 this.$input
.val( value
);
7075 if ( this.value
!== value
) {
7077 this.emit( 'change', this.value
);
7083 * Clean up incoming value.
7085 * Ensures value is a string, and converts undefined and null to empty string.
7088 * @param {string} value Original value
7089 * @return {string} Cleaned up value
7091 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
7092 if ( value
=== undefined || value
=== null ) {
7094 } else if ( this.inputFilter
) {
7095 return this.inputFilter( String( value
) );
7097 return String( value
);
7102 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
7103 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
7106 OO
.ui
.InputWidget
.prototype.simulateLabelClick = function () {
7107 if ( !this.isDisabled() ) {
7108 if ( this.$input
.is( ':checkbox, :radio' ) ) {
7109 this.$input
.click();
7111 if ( this.$input
.is( ':input' ) ) {
7112 this.$input
[ 0 ].focus();
7120 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
7121 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
7122 if ( this.$input
) {
7123 this.$input
.prop( 'disabled', this.isDisabled() );
7133 OO
.ui
.InputWidget
.prototype.focus = function () {
7134 this.$input
[ 0 ].focus();
7143 OO
.ui
.InputWidget
.prototype.blur = function () {
7144 this.$input
[ 0 ].blur();
7151 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
7152 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
7153 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
7154 this.setValue( state
.value
);
7156 if ( state
.focus
) {
7162 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
7163 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
7164 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
7165 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
7166 * [OOjs UI documentation on MediaWiki] [1] for more information.
7169 * // A ButtonInputWidget rendered as an HTML button, the default.
7170 * var button = new OO.ui.ButtonInputWidget( {
7171 * label: 'Input button',
7175 * $( 'body' ).append( button.$element );
7177 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
7180 * @extends OO.ui.InputWidget
7181 * @mixins OO.ui.mixin.ButtonElement
7182 * @mixins OO.ui.mixin.IconElement
7183 * @mixins OO.ui.mixin.IndicatorElement
7184 * @mixins OO.ui.mixin.LabelElement
7185 * @mixins OO.ui.mixin.TitledElement
7188 * @param {Object} [config] Configuration options
7189 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
7190 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
7191 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
7192 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
7193 * be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
7195 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
7196 // Configuration initialization
7197 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
7199 // See InputWidget#reusePreInfuseDOM about config.$input
7200 if ( config
.$input
) {
7201 config
.$input
.empty();
7204 // Properties (must be set before parent constructor, which calls #setValue)
7205 this.useInputTag
= config
.useInputTag
;
7207 // Parent constructor
7208 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
7210 // Mixin constructors
7211 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
7212 OO
.ui
.mixin
.IconElement
.call( this, config
);
7213 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
7214 OO
.ui
.mixin
.LabelElement
.call( this, config
);
7215 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
7218 if ( !config
.useInputTag
) {
7219 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
7221 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
7226 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
7227 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
7228 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
7229 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
7230 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
7231 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
7233 /* Static Properties */
7236 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
7237 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
7239 OO
.ui
.ButtonInputWidget
.static.supportsSimpleLabel
= false;
7247 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
7249 type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ? config
.type
: 'button';
7250 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
7256 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
7258 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
7259 * text, or `null` for no label
7262 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
7263 if ( typeof label
=== 'function' ) {
7264 label
= OO
.ui
.resolveMsg( label
);
7267 if ( this.useInputTag
) {
7268 // Discard non-plaintext labels
7269 if ( typeof label
!== 'string' ) {
7273 this.$input
.val( label
);
7276 return OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
7280 * Set the value of the input.
7282 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
7283 * they do not support {@link #value values}.
7285 * @param {string} value New value
7288 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
7289 if ( !this.useInputTag
) {
7290 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
7296 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
7297 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
7298 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
7299 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
7301 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
7304 * // An example of selected, unselected, and disabled checkbox inputs
7305 * var checkbox1=new OO.ui.CheckboxInputWidget( {
7309 * var checkbox2=new OO.ui.CheckboxInputWidget( {
7312 * var checkbox3=new OO.ui.CheckboxInputWidget( {
7316 * // Create a fieldset layout with fields for each checkbox.
7317 * var fieldset = new OO.ui.FieldsetLayout( {
7318 * label: 'Checkboxes'
7320 * fieldset.addItems( [
7321 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
7322 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
7323 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
7325 * $( 'body' ).append( fieldset.$element );
7327 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7330 * @extends OO.ui.InputWidget
7333 * @param {Object} [config] Configuration options
7334 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
7336 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
7337 // Configuration initialization
7338 config
= config
|| {};
7340 // Parent constructor
7341 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
7345 .addClass( 'oo-ui-checkboxInputWidget' )
7346 // Required for pretty styling in MediaWiki theme
7347 .append( $( '<span>' ) );
7348 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
7353 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
7355 /* Static Methods */
7360 OO
.ui
.CheckboxInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
7361 var state
= OO
.ui
.CheckboxInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
7362 state
.checked
= config
.$input
.prop( 'checked' );
7372 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
7373 return $( '<input>' ).attr( 'type', 'checkbox' );
7379 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
7381 if ( !this.isDisabled() ) {
7382 // Allow the stack to clear so the value will be updated
7383 setTimeout( function () {
7384 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
7390 * Set selection state of this checkbox.
7392 * @param {boolean} state `true` for selected
7395 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
7397 if ( this.selected
!== state
) {
7398 this.selected
= state
;
7399 this.$input
.prop( 'checked', this.selected
);
7400 this.emit( 'change', this.selected
);
7406 * Check if this checkbox is selected.
7408 * @return {boolean} Checkbox is selected
7410 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
7411 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
7412 // it, and we won't know unless they're kind enough to trigger a 'change' event.
7413 var selected
= this.$input
.prop( 'checked' );
7414 if ( this.selected
!== selected
) {
7415 this.setSelected( selected
);
7417 return this.selected
;
7423 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
7424 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
7425 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
7426 this.setSelected( state
.checked
);
7431 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
7432 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
7433 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
7434 * more information about input widgets.
7436 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
7437 * are no options. If no `value` configuration option is provided, the first option is selected.
7438 * If you need a state representing no value (no option being selected), use a DropdownWidget.
7440 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
7443 * // Example: A DropdownInputWidget with three options
7444 * var dropdownInput = new OO.ui.DropdownInputWidget( {
7446 * { data: 'a', label: 'First' },
7447 * { data: 'b', label: 'Second'},
7448 * { data: 'c', label: 'Third' }
7451 * $( 'body' ).append( dropdownInput.$element );
7453 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7456 * @extends OO.ui.InputWidget
7457 * @mixins OO.ui.mixin.TitledElement
7460 * @param {Object} [config] Configuration options
7461 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
7462 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
7464 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
7465 // Configuration initialization
7466 config
= config
|| {};
7468 // See InputWidget#reusePreInfuseDOM about config.$input
7469 if ( config
.$input
) {
7470 config
.$input
.addClass( 'oo-ui-element-hidden' );
7473 // Properties (must be done before parent constructor which calls #setDisabled)
7474 this.dropdownWidget
= new OO
.ui
.DropdownWidget( config
.dropdown
);
7476 // Parent constructor
7477 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
7479 // Mixin constructors
7480 OO
.ui
.mixin
.TitledElement
.call( this, config
);
7483 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
7486 this.setOptions( config
.options
|| [] );
7488 .addClass( 'oo-ui-dropdownInputWidget' )
7489 .append( this.dropdownWidget
.$element
);
7494 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
7495 OO
.mixinClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.mixin
.TitledElement
);
7503 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
7504 return $( '<input>' ).attr( 'type', 'hidden' );
7508 * Handles menu select events.
7511 * @param {OO.ui.MenuOptionWidget} item Selected menu item
7513 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
7514 this.setValue( item
.getData() );
7520 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
7521 value
= this.cleanUpValue( value
);
7522 this.dropdownWidget
.getMenu().selectItemByData( value
);
7523 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
7530 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
7531 this.dropdownWidget
.setDisabled( state
);
7532 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
7537 * Set the options available for this input.
7539 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
7542 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
7544 value
= this.getValue(),
7547 // Rebuild the dropdown menu
7548 this.dropdownWidget
.getMenu()
7550 .addItems( options
.map( function ( opt
) {
7551 var optValue
= widget
.cleanUpValue( opt
.data
);
7552 return new OO
.ui
.MenuOptionWidget( {
7554 label
: opt
.label
!== undefined ? opt
.label
: optValue
7558 // Restore the previous value, or reset to something sensible
7559 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
7560 // Previous value is still available, ensure consistency with the dropdown
7561 this.setValue( value
);
7563 // No longer valid, reset
7564 if ( options
.length
) {
7565 this.setValue( options
[ 0 ].data
);
7575 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
7576 this.dropdownWidget
.getMenu().toggle( true );
7583 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
7584 this.dropdownWidget
.getMenu().toggle( false );
7589 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
7590 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
7591 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
7592 * please see the [OOjs UI documentation on MediaWiki][1].
7594 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
7597 * // An example of selected, unselected, and disabled radio inputs
7598 * var radio1 = new OO.ui.RadioInputWidget( {
7602 * var radio2 = new OO.ui.RadioInputWidget( {
7605 * var radio3 = new OO.ui.RadioInputWidget( {
7609 * // Create a fieldset layout with fields for each radio button.
7610 * var fieldset = new OO.ui.FieldsetLayout( {
7611 * label: 'Radio inputs'
7613 * fieldset.addItems( [
7614 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
7615 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
7616 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
7618 * $( 'body' ).append( fieldset.$element );
7620 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7623 * @extends OO.ui.InputWidget
7626 * @param {Object} [config] Configuration options
7627 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
7629 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
7630 // Configuration initialization
7631 config
= config
|| {};
7633 // Parent constructor
7634 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
7638 .addClass( 'oo-ui-radioInputWidget' )
7639 // Required for pretty styling in MediaWiki theme
7640 .append( $( '<span>' ) );
7641 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
7646 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
7648 /* Static Methods */
7653 OO
.ui
.RadioInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
7654 var state
= OO
.ui
.RadioInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
7655 state
.checked
= config
.$input
.prop( 'checked' );
7665 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
7666 return $( '<input>' ).attr( 'type', 'radio' );
7672 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
7673 // RadioInputWidget doesn't track its state.
7677 * Set selection state of this radio button.
7679 * @param {boolean} state `true` for selected
7682 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
7683 // RadioInputWidget doesn't track its state.
7684 this.$input
.prop( 'checked', state
);
7689 * Check if this radio button is selected.
7691 * @return {boolean} Radio is selected
7693 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
7694 return this.$input
.prop( 'checked' );
7700 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
7701 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
7702 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
7703 this.setSelected( state
.checked
);
7708 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
7709 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
7710 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
7711 * more information about input widgets.
7713 * This and OO.ui.DropdownInputWidget support the same configuration options.
7716 * // Example: A RadioSelectInputWidget with three options
7717 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
7719 * { data: 'a', label: 'First' },
7720 * { data: 'b', label: 'Second'},
7721 * { data: 'c', label: 'Third' }
7724 * $( 'body' ).append( radioSelectInput.$element );
7726 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7729 * @extends OO.ui.InputWidget
7732 * @param {Object} [config] Configuration options
7733 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
7735 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
7736 // Configuration initialization
7737 config
= config
|| {};
7739 // Properties (must be done before parent constructor which calls #setDisabled)
7740 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
7742 // Parent constructor
7743 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
7746 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
7749 this.setOptions( config
.options
|| [] );
7751 .addClass( 'oo-ui-radioSelectInputWidget' )
7752 .append( this.radioSelectWidget
.$element
);
7757 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
7759 /* Static Properties */
7761 OO
.ui
.RadioSelectInputWidget
.static.supportsSimpleLabel
= false;
7763 /* Static Methods */
7768 OO
.ui
.RadioSelectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
7769 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
7770 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
7777 OO
.ui
.RadioSelectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
7778 config
= OO
.ui
.RadioSelectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
7779 // Cannot reuse the `<input type=radio>` set
7780 delete config
.$input
;
7790 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
7791 return $( '<input>' ).attr( 'type', 'hidden' );
7795 * Handles menu select events.
7798 * @param {OO.ui.RadioOptionWidget} item Selected menu item
7800 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
7801 this.setValue( item
.getData() );
7807 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
7808 value
= this.cleanUpValue( value
);
7809 this.radioSelectWidget
.selectItemByData( value
);
7810 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
7817 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
7818 this.radioSelectWidget
.setDisabled( state
);
7819 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
7824 * Set the options available for this input.
7826 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
7829 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
7831 value
= this.getValue(),
7834 // Rebuild the radioSelect menu
7835 this.radioSelectWidget
7837 .addItems( options
.map( function ( opt
) {
7838 var optValue
= widget
.cleanUpValue( opt
.data
);
7839 return new OO
.ui
.RadioOptionWidget( {
7841 label
: opt
.label
!== undefined ? opt
.label
: optValue
7845 // Restore the previous value, or reset to something sensible
7846 if ( this.radioSelectWidget
.getItemFromData( value
) ) {
7847 // Previous value is still available, ensure consistency with the radioSelect
7848 this.setValue( value
);
7850 // No longer valid, reset
7851 if ( options
.length
) {
7852 this.setValue( options
[ 0 ].data
);
7860 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
7861 * size of the field as well as its presentation. In addition, these widgets can be configured
7862 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
7863 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
7864 * which modifies incoming values rather than validating them.
7865 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
7867 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
7870 * // Example of a text input widget
7871 * var textInput = new OO.ui.TextInputWidget( {
7872 * value: 'Text input'
7874 * $( 'body' ).append( textInput.$element );
7876 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7879 * @extends OO.ui.InputWidget
7880 * @mixins OO.ui.mixin.IconElement
7881 * @mixins OO.ui.mixin.IndicatorElement
7882 * @mixins OO.ui.mixin.PendingElement
7883 * @mixins OO.ui.mixin.LabelElement
7886 * @param {Object} [config] Configuration options
7887 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
7888 * 'email', 'url', 'date' or 'number'. Ignored if `multiline` is true.
7890 * Some values of `type` result in additional behaviors:
7892 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
7893 * empties the text field
7894 * @cfg {string} [placeholder] Placeholder text
7895 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
7896 * instruct the browser to focus this widget.
7897 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
7898 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
7899 * @cfg {boolean} [multiline=false] Allow multiple lines of text
7900 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
7901 * specifies minimum number of rows to display.
7902 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
7903 * Use the #maxRows config to specify a maximum number of displayed rows.
7904 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
7905 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
7906 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
7907 * the value or placeholder text: `'before'` or `'after'`
7908 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
7909 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
7910 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
7911 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
7912 * (the value must contain only numbers); when RegExp, a regular expression that must match the
7913 * value for it to be considered valid; when Function, a function receiving the value as parameter
7914 * that must return true, or promise resolving to true, for it to be considered valid.
7916 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
7917 // Configuration initialization
7918 config
= $.extend( {
7920 labelPosition
: 'after'
7922 if ( config
.type
=== 'search' ) {
7923 if ( config
.icon
=== undefined ) {
7924 config
.icon
= 'search';
7926 // indicator: 'clear' is set dynamically later, depending on value
7928 if ( config
.required
) {
7929 if ( config
.indicator
=== undefined ) {
7930 config
.indicator
= 'required';
7934 // Parent constructor
7935 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
7937 // Mixin constructors
7938 OO
.ui
.mixin
.IconElement
.call( this, config
);
7939 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
7940 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
7941 OO
.ui
.mixin
.LabelElement
.call( this, config
);
7944 this.type
= this.getSaneType( config
);
7945 this.readOnly
= false;
7946 this.multiline
= !!config
.multiline
;
7947 this.autosize
= !!config
.autosize
;
7948 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
7949 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
7950 this.validate
= null;
7951 this.styleHeight
= null;
7952 this.scrollWidth
= null;
7954 // Clone for resizing
7955 if ( this.autosize
) {
7956 this.$clone
= this.$input
7958 .insertAfter( this.$input
)
7959 .attr( 'aria-hidden', 'true' )
7960 .addClass( 'oo-ui-element-hidden' );
7963 this.setValidation( config
.validate
);
7964 this.setLabelPosition( config
.labelPosition
);
7968 keypress
: this.onKeyPress
.bind( this ),
7969 blur
: this.onBlur
.bind( this )
7972 focus
: this.onElementAttach
.bind( this )
7974 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
7975 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
7976 this.on( 'labelChange', this.updatePosition
.bind( this ) );
7977 this.connect( this, {
7979 disable
: 'onDisable'
7984 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
7985 .append( this.$icon
, this.$indicator
);
7986 this.setReadOnly( !!config
.readOnly
);
7987 this.updateSearchIndicator();
7988 if ( config
.placeholder
!== undefined ) {
7989 this.$input
.attr( 'placeholder', config
.placeholder
);
7991 if ( config
.maxLength
!== undefined ) {
7992 this.$input
.attr( 'maxlength', config
.maxLength
);
7994 if ( config
.autofocus
) {
7995 this.$input
.attr( 'autofocus', 'autofocus' );
7997 if ( config
.required
) {
7998 this.$input
.attr( 'required', 'required' );
7999 this.$input
.attr( 'aria-required', 'true' );
8001 if ( config
.autocomplete
=== false ) {
8002 this.$input
.attr( 'autocomplete', 'off' );
8003 // Turning off autocompletion also disables "form caching" when the user navigates to a
8004 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
8006 beforeunload: function () {
8007 this.$input
.removeAttr( 'autocomplete' );
8009 pageshow: function () {
8010 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
8011 // whole page... it shouldn't hurt, though.
8012 this.$input
.attr( 'autocomplete', 'off' );
8016 if ( this.multiline
&& config
.rows
) {
8017 this.$input
.attr( 'rows', config
.rows
);
8019 if ( this.label
|| config
.autosize
) {
8020 this.installParentChangeDetector();
8026 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
8027 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
8028 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
8029 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
8030 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
8032 /* Static Properties */
8034 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
8039 /* Static Methods */
8044 OO
.ui
.TextInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8045 var state
= OO
.ui
.TextInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8046 if ( config
.multiline
) {
8047 state
.scrollTop
= config
.$input
.scrollTop();
8055 * An `enter` event is emitted when the user presses 'enter' inside the text box.
8057 * Not emitted if the input is multiline.
8063 * A `resize` event is emitted when autosize is set and the widget resizes
8071 * Handle icon mouse down events.
8074 * @param {jQuery.Event} e Mouse down event
8076 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
8077 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
8078 this.$input
[ 0 ].focus();
8084 * Handle indicator mouse down events.
8087 * @param {jQuery.Event} e Mouse down event
8089 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
8090 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
8091 if ( this.type
=== 'search' ) {
8092 // Clear the text field
8093 this.setValue( '' );
8095 this.$input
[ 0 ].focus();
8101 * Handle key press events.
8104 * @param {jQuery.Event} e Key press event
8105 * @fires enter If enter key is pressed and input is not multiline
8107 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
8108 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
8109 this.emit( 'enter', e
);
8114 * Handle blur events.
8117 * @param {jQuery.Event} e Blur event
8119 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
8120 this.setValidityFlag();
8124 * Handle element attach events.
8127 * @param {jQuery.Event} e Element attach event
8129 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
8130 // Any previously calculated size is now probably invalid if we reattached elsewhere
8131 this.valCache
= null;
8133 this.positionLabel();
8137 * Handle change events.
8139 * @param {string} value
8142 OO
.ui
.TextInputWidget
.prototype.onChange = function () {
8143 this.updateSearchIndicator();
8144 this.setValidityFlag();
8149 * Handle disable events.
8151 * @param {boolean} disabled Element is disabled
8154 OO
.ui
.TextInputWidget
.prototype.onDisable = function () {
8155 this.updateSearchIndicator();
8159 * Check if the input is {@link #readOnly read-only}.
8163 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
8164 return this.readOnly
;
8168 * Set the {@link #readOnly read-only} state of the input.
8170 * @param {boolean} state Make input read-only
8173 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
8174 this.readOnly
= !!state
;
8175 this.$input
.prop( 'readOnly', this.readOnly
);
8176 this.updateSearchIndicator();
8181 * Support function for making #onElementAttach work across browsers.
8183 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
8184 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
8186 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
8187 * first time that the element gets attached to the documented.
8189 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
8190 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
8191 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
8194 if ( MutationObserver
) {
8195 // The new way. If only it wasn't so ugly.
8197 if ( this.$element
.closest( 'html' ).length
) {
8198 // Widget is attached already, do nothing. This breaks the functionality of this function when
8199 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
8200 // would require observation of the whole document, which would hurt performance of other,
8201 // more important code.
8205 // Find topmost node in the tree
8206 topmostNode
= this.$element
[ 0 ];
8207 while ( topmostNode
.parentNode
) {
8208 topmostNode
= topmostNode
.parentNode
;
8211 // We have no way to detect the $element being attached somewhere without observing the entire
8212 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
8213 // parent node of $element, and instead detect when $element is removed from it (and thus
8214 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
8215 // doesn't get attached, we end up back here and create the parent.
8217 mutationObserver
= new MutationObserver( function ( mutations
) {
8218 var i
, j
, removedNodes
;
8219 for ( i
= 0; i
< mutations
.length
; i
++ ) {
8220 removedNodes
= mutations
[ i
].removedNodes
;
8221 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
8222 if ( removedNodes
[ j
] === topmostNode
) {
8223 setTimeout( onRemove
, 0 );
8230 onRemove = function () {
8231 // If the node was attached somewhere else, report it
8232 if ( widget
.$element
.closest( 'html' ).length
) {
8233 widget
.onElementAttach();
8235 mutationObserver
.disconnect();
8236 widget
.installParentChangeDetector();
8239 // Create a fake parent and observe it
8240 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
8241 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
8243 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
8244 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
8245 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
8250 * Automatically adjust the size of the text input.
8252 * This only affects #multiline inputs that are {@link #autosize autosized}.
8257 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
8258 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
,
8259 idealHeight
, newHeight
, scrollWidth
, property
;
8261 if ( this.multiline
&& this.$input
.val() !== this.valCache
) {
8262 if ( this.autosize
) {
8264 .val( this.$input
.val() )
8265 .attr( 'rows', this.minRows
)
8266 // Set inline height property to 0 to measure scroll height
8267 .css( 'height', 0 );
8269 this.$clone
.removeClass( 'oo-ui-element-hidden' );
8271 this.valCache
= this.$input
.val();
8273 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
8275 // Remove inline height property to measure natural heights
8276 this.$clone
.css( 'height', '' );
8277 innerHeight
= this.$clone
.innerHeight();
8278 outerHeight
= this.$clone
.outerHeight();
8280 // Measure max rows height
8282 .attr( 'rows', this.maxRows
)
8283 .css( 'height', 'auto' )
8285 maxInnerHeight
= this.$clone
.innerHeight();
8287 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
8288 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
8289 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
8290 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
8292 this.$clone
.addClass( 'oo-ui-element-hidden' );
8294 // Only apply inline height when expansion beyond natural height is needed
8295 // Use the difference between the inner and outer height as a buffer
8296 newHeight
= idealHeight
> innerHeight
? idealHeight
+ ( outerHeight
- innerHeight
) : '';
8297 if ( newHeight
!== this.styleHeight
) {
8298 this.$input
.css( 'height', newHeight
);
8299 this.styleHeight
= newHeight
;
8300 this.emit( 'resize' );
8303 scrollWidth
= this.$input
[ 0 ].offsetWidth
- this.$input
[ 0 ].clientWidth
;
8304 if ( scrollWidth
!== this.scrollWidth
) {
8305 property
= this.$element
.css( 'direction' ) === 'rtl' ? 'left' : 'right';
8307 this.$label
.css( { right
: '', left
: '' } );
8308 this.$indicator
.css( { right
: '', left
: '' } );
8310 if ( scrollWidth
) {
8311 this.$indicator
.css( property
, scrollWidth
);
8312 if ( this.labelPosition
=== 'after' ) {
8313 this.$label
.css( property
, scrollWidth
);
8317 this.scrollWidth
= scrollWidth
;
8318 this.positionLabel();
8328 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
8329 if ( config
.multiline
) {
8330 return $( '<textarea>' );
8331 } else if ( this.getSaneType( config
) === 'number' ) {
8332 return $( '<input>' )
8333 .attr( 'step', 'any' )
8334 .attr( 'type', 'number' );
8336 return $( '<input>' ).attr( 'type', this.getSaneType( config
) );
8341 * Get sanitized value for 'type' for given config.
8343 * @param {Object} config Configuration options
8344 * @return {string|null}
8347 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
8348 var allowedTypes
= [
8357 type
= allowedTypes
.indexOf( config
.type
) !== -1 ? config
.type
: 'text';
8358 return config
.multiline
? 'multiline' : type
;
8362 * Check if the input supports multiple lines.
8366 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
8367 return !!this.multiline
;
8371 * Check if the input automatically adjusts its size.
8375 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
8376 return !!this.autosize
;
8380 * Focus the input and select a specified range within the text.
8382 * @param {number} from Select from offset
8383 * @param {number} [to] Select to offset, defaults to from
8386 OO
.ui
.TextInputWidget
.prototype.selectRange = function ( from, to
) {
8387 var isBackwards
, start
, end
,
8388 input
= this.$input
[ 0 ];
8392 isBackwards
= to
< from;
8393 start
= isBackwards
? to
: from;
8394 end
= isBackwards
? from : to
;
8399 input
.setSelectionRange( start
, end
, isBackwards
? 'backward' : 'forward' );
8401 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
8402 // Rather than expensively check if the input is attached every time, just check
8403 // if it was the cause of an error being thrown. If not, rethrow the error.
8404 if ( this.getElementDocument().body
.contains( input
) ) {
8412 * Get an object describing the current selection range in a directional manner
8414 * @return {Object} Object containing 'from' and 'to' offsets
8416 OO
.ui
.TextInputWidget
.prototype.getRange = function () {
8417 var input
= this.$input
[ 0 ],
8418 start
= input
.selectionStart
,
8419 end
= input
.selectionEnd
,
8420 isBackwards
= input
.selectionDirection
=== 'backward';
8423 from: isBackwards
? end
: start
,
8424 to
: isBackwards
? start
: end
8429 * Get the length of the text input value.
8431 * This could differ from the length of #getValue if the
8432 * value gets filtered
8434 * @return {number} Input length
8436 OO
.ui
.TextInputWidget
.prototype.getInputLength = function () {
8437 return this.$input
[ 0 ].value
.length
;
8441 * Focus the input and select the entire text.
8445 OO
.ui
.TextInputWidget
.prototype.select = function () {
8446 return this.selectRange( 0, this.getInputLength() );
8450 * Focus the input and move the cursor to the start.
8454 OO
.ui
.TextInputWidget
.prototype.moveCursorToStart = function () {
8455 return this.selectRange( 0 );
8459 * Focus the input and move the cursor to the end.
8463 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
8464 return this.selectRange( this.getInputLength() );
8468 * Insert new content into the input.
8470 * @param {string} content Content to be inserted
8473 OO
.ui
.TextInputWidget
.prototype.insertContent = function ( content
) {
8475 range
= this.getRange(),
8476 value
= this.getValue();
8478 start
= Math
.min( range
.from, range
.to
);
8479 end
= Math
.max( range
.from, range
.to
);
8481 this.setValue( value
.slice( 0, start
) + content
+ value
.slice( end
) );
8482 this.selectRange( start
+ content
.length
);
8487 * Insert new content either side of a selection.
8489 * @param {string} pre Content to be inserted before the selection
8490 * @param {string} post Content to be inserted after the selection
8493 OO
.ui
.TextInputWidget
.prototype.encapsulateContent = function ( pre
, post
) {
8495 range
= this.getRange(),
8496 offset
= pre
.length
;
8498 start
= Math
.min( range
.from, range
.to
);
8499 end
= Math
.max( range
.from, range
.to
);
8501 this.selectRange( start
).insertContent( pre
);
8502 this.selectRange( offset
+ end
).insertContent( post
);
8504 this.selectRange( offset
+ start
, offset
+ end
);
8509 * Set the validation pattern.
8511 * The validation pattern is either a regular expression, a function, or the symbolic name of a
8512 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
8513 * value must contain only numbers).
8515 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
8516 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
8518 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
8519 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
8520 this.validate
= validate
;
8522 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
8527 * Sets the 'invalid' flag appropriately.
8529 * @param {boolean} [isValid] Optionally override validation result
8531 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
8533 setFlag = function ( valid
) {
8535 widget
.$input
.attr( 'aria-invalid', 'true' );
8537 widget
.$input
.removeAttr( 'aria-invalid' );
8539 widget
.setFlags( { invalid
: !valid
} );
8542 if ( isValid
!== undefined ) {
8545 this.getValidity().then( function () {
8554 * Check if a value is valid.
8556 * This method returns a promise that resolves with a boolean `true` if the current value is
8557 * considered valid according to the supplied {@link #validate validation pattern}.
8559 * @deprecated since v0.12.3
8560 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
8562 OO
.ui
.TextInputWidget
.prototype.isValid = function () {
8565 if ( this.validate
instanceof Function
) {
8566 result
= this.validate( this.getValue() );
8567 if ( result
&& $.isFunction( result
.promise
) ) {
8568 return result
.promise();
8570 return $.Deferred().resolve( !!result
).promise();
8573 return $.Deferred().resolve( !!this.getValue().match( this.validate
) ).promise();
8578 * Get the validity of current value.
8580 * This method returns a promise that resolves if the value is valid and rejects if
8581 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
8583 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
8585 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
8588 function rejectOrResolve( valid
) {
8590 return $.Deferred().resolve().promise();
8592 return $.Deferred().reject().promise();
8596 if ( this.validate
instanceof Function
) {
8597 result
= this.validate( this.getValue() );
8598 if ( result
&& $.isFunction( result
.promise
) ) {
8599 return result
.promise().then( function ( valid
) {
8600 return rejectOrResolve( valid
);
8603 return rejectOrResolve( result
);
8606 return rejectOrResolve( this.getValue().match( this.validate
) );
8611 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
8613 * @param {string} labelPosition Label position, 'before' or 'after'
8616 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
8617 this.labelPosition
= labelPosition
;
8619 // If there is no label and we only change the position, #updatePosition is a no-op,
8620 // but it takes really a lot of work to do nothing.
8621 this.updatePosition();
8627 * Update the position of the inline label.
8629 * This method is called by #setLabelPosition, and can also be called on its own if
8630 * something causes the label to be mispositioned.
8634 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
8635 var after
= this.labelPosition
=== 'after';
8638 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
8639 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
8641 this.valCache
= null;
8642 this.scrollWidth
= null;
8644 this.positionLabel();
8650 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
8651 * already empty or when it's not editable.
8653 OO
.ui
.TextInputWidget
.prototype.updateSearchIndicator = function () {
8654 if ( this.type
=== 'search' ) {
8655 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
8656 this.setIndicator( null );
8658 this.setIndicator( 'clear' );
8664 * Position the label by setting the correct padding on the input.
8669 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
8670 var after
, rtl
, property
;
8673 // Clear old values if present
8675 'padding-right': '',
8680 this.$element
.append( this.$label
);
8682 this.$label
.detach();
8686 after
= this.labelPosition
=== 'after';
8687 rtl
= this.$element
.css( 'direction' ) === 'rtl';
8688 property
= after
=== rtl
? 'padding-left' : 'padding-right';
8690 this.$input
.css( property
, this.$label
.outerWidth( true ) + ( after
? this.scrollWidth
: 0 ) );
8698 OO
.ui
.TextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
8699 OO
.ui
.TextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
8700 if ( state
.scrollTop
!== undefined ) {
8701 this.$input
.scrollTop( state
.scrollTop
);
8706 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
8707 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
8708 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
8710 * - by typing a value in the text input field. If the value exactly matches the value of a menu
8711 * option, that option will appear to be selected.
8712 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
8715 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
8717 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
8720 * // Example: A ComboBoxInputWidget.
8721 * var comboBox = new OO.ui.ComboBoxInputWidget( {
8722 * label: 'ComboBoxInputWidget',
8723 * value: 'Option 1',
8726 * new OO.ui.MenuOptionWidget( {
8728 * label: 'Option One'
8730 * new OO.ui.MenuOptionWidget( {
8732 * label: 'Option Two'
8734 * new OO.ui.MenuOptionWidget( {
8736 * label: 'Option Three'
8738 * new OO.ui.MenuOptionWidget( {
8740 * label: 'Option Four'
8742 * new OO.ui.MenuOptionWidget( {
8744 * label: 'Option Five'
8749 * $( 'body' ).append( comboBox.$element );
8751 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
8754 * @extends OO.ui.TextInputWidget
8757 * @param {Object} [config] Configuration options
8758 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
8759 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
8760 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
8761 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
8762 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
8764 OO
.ui
.ComboBoxInputWidget
= function OoUiComboBoxInputWidget( config
) {
8765 // Configuration initialization
8766 config
= $.extend( {
8770 // For backwards-compatibility with ComboBoxWidget config
8771 $.extend( config
, config
.input
);
8773 // Parent constructor
8774 OO
.ui
.ComboBoxInputWidget
.parent
.call( this, config
);
8777 this.$overlay
= config
.$overlay
|| this.$element
;
8778 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
8782 $container
: this.$element
,
8783 disabled
: this.isDisabled()
8787 // For backwards-compatibility with ComboBoxWidget
8791 this.$indicator
.on( {
8792 click
: this.onIndicatorClick
.bind( this ),
8793 keypress
: this.onIndicatorKeyPress
.bind( this )
8795 this.connect( this, {
8796 change
: 'onInputChange',
8797 enter
: 'onInputEnter'
8799 this.menu
.connect( this, {
8800 choose
: 'onMenuChoose',
8801 add
: 'onMenuItemsChange',
8802 remove
: 'onMenuItemsChange'
8808 'aria-autocomplete': 'list'
8810 // Do not override options set via config.menu.items
8811 if ( config
.options
!== undefined ) {
8812 this.setOptions( config
.options
);
8814 // Extra class for backwards-compatibility with ComboBoxWidget
8815 this.$element
.addClass( 'oo-ui-comboBoxInputWidget oo-ui-comboBoxWidget' );
8816 this.$overlay
.append( this.menu
.$element
);
8817 this.onMenuItemsChange();
8822 OO
.inheritClass( OO
.ui
.ComboBoxInputWidget
, OO
.ui
.TextInputWidget
);
8827 * Get the combobox's menu.
8829 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
8831 OO
.ui
.ComboBoxInputWidget
.prototype.getMenu = function () {
8836 * Get the combobox's text input widget.
8838 * @return {OO.ui.TextInputWidget} Text input widget
8840 OO
.ui
.ComboBoxInputWidget
.prototype.getInput = function () {
8845 * Handle input change events.
8848 * @param {string} value New value
8850 OO
.ui
.ComboBoxInputWidget
.prototype.onInputChange = function ( value
) {
8851 var match
= this.menu
.getItemFromData( value
);
8853 this.menu
.selectItem( match
);
8854 if ( this.menu
.getHighlightedItem() ) {
8855 this.menu
.highlightItem( match
);
8858 if ( !this.isDisabled() ) {
8859 this.menu
.toggle( true );
8864 * Handle mouse click events.
8867 * @param {jQuery.Event} e Mouse click event
8869 OO
.ui
.ComboBoxInputWidget
.prototype.onIndicatorClick = function ( e
) {
8870 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
8872 this.$input
[ 0 ].focus();
8878 * Handle key press events.
8881 * @param {jQuery.Event} e Key press event
8883 OO
.ui
.ComboBoxInputWidget
.prototype.onIndicatorKeyPress = function ( e
) {
8884 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
8886 this.$input
[ 0 ].focus();
8892 * Handle input enter events.
8896 OO
.ui
.ComboBoxInputWidget
.prototype.onInputEnter = function () {
8897 if ( !this.isDisabled() ) {
8898 this.menu
.toggle( false );
8903 * Handle menu choose events.
8906 * @param {OO.ui.OptionWidget} item Chosen item
8908 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuChoose = function ( item
) {
8909 this.setValue( item
.getData() );
8913 * Handle menu item change events.
8917 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuItemsChange = function () {
8918 var match
= this.menu
.getItemFromData( this.getValue() );
8919 this.menu
.selectItem( match
);
8920 if ( this.menu
.getHighlightedItem() ) {
8921 this.menu
.highlightItem( match
);
8923 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu
.isEmpty() );
8929 OO
.ui
.ComboBoxInputWidget
.prototype.setDisabled = function ( disabled
) {
8931 OO
.ui
.ComboBoxInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
8934 this.menu
.setDisabled( this.isDisabled() );
8941 * Set the options available for this input.
8943 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
8946 OO
.ui
.ComboBoxInputWidget
.prototype.setOptions = function ( options
) {
8949 .addItems( options
.map( function ( opt
) {
8950 return new OO
.ui
.MenuOptionWidget( {
8952 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
8961 * @deprecated since 0.13.2; use OO.ui.ComboBoxInputWidget instead
8963 OO
.ui
.ComboBoxWidget
= OO
.ui
.ComboBoxInputWidget
;
8966 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
8967 * which is a widget that is specified by reference before any optional configuration settings.
8969 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
8971 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8972 * A left-alignment is used for forms with many fields.
8973 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8974 * A right-alignment is used for long but familiar forms which users tab through,
8975 * verifying the current field with a quick glance at the label.
8976 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8977 * that users fill out from top to bottom.
8978 * - **inline**: The label is placed after the field-widget and aligned to the left.
8979 * An inline-alignment is best used with checkboxes or radio buttons.
8981 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
8982 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
8984 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8987 * @extends OO.ui.Layout
8988 * @mixins OO.ui.mixin.LabelElement
8989 * @mixins OO.ui.mixin.TitledElement
8992 * @param {OO.ui.Widget} fieldWidget Field widget
8993 * @param {Object} [config] Configuration options
8994 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
8995 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
8996 * The array may contain strings or OO.ui.HtmlSnippet instances.
8997 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
8998 * The array may contain strings or OO.ui.HtmlSnippet instances.
8999 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
9000 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
9001 * For important messages, you are advised to use `notices`, as they are always shown.
9003 * @throws {Error} An error is thrown if no widget is specified
9005 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
9006 var hasInputWidget
, div
;
9008 // Allow passing positional parameters inside the config object
9009 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
9010 config
= fieldWidget
;
9011 fieldWidget
= config
.fieldWidget
;
9014 // Make sure we have required constructor arguments
9015 if ( fieldWidget
=== undefined ) {
9016 throw new Error( 'Widget not found' );
9019 hasInputWidget
= fieldWidget
.constructor.static.supportsSimpleLabel
;
9021 // Configuration initialization
9022 config
= $.extend( { align
: 'left' }, config
);
9024 // Parent constructor
9025 OO
.ui
.FieldLayout
.parent
.call( this, config
);
9027 // Mixin constructors
9028 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9029 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
9032 this.fieldWidget
= fieldWidget
;
9035 this.$field
= $( '<div>' );
9036 this.$messages
= $( '<ul>' );
9037 this.$body
= $( '<' + ( hasInputWidget
? 'label' : 'div' ) + '>' );
9039 if ( config
.help
) {
9040 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
9041 classes
: [ 'oo-ui-fieldLayout-help' ],
9047 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
9048 div
.html( config
.help
.toString() );
9050 div
.text( config
.help
);
9052 this.popupButtonWidget
.getPopup().$body
.append(
9053 div
.addClass( 'oo-ui-fieldLayout-help-content' )
9055 this.$help
= this.popupButtonWidget
.$element
;
9057 this.$help
= $( [] );
9061 if ( hasInputWidget
) {
9062 this.$label
.on( 'click', this.onLabelClick
.bind( this ) );
9064 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
9068 .addClass( 'oo-ui-fieldLayout' )
9069 .append( this.$help
, this.$body
);
9070 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
9071 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
9073 .addClass( 'oo-ui-fieldLayout-field' )
9074 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget
.isDisabled() )
9075 .append( this.fieldWidget
.$element
);
9077 this.setErrors( config
.errors
|| [] );
9078 this.setNotices( config
.notices
|| [] );
9079 this.setAlignment( config
.align
);
9084 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
9085 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
9086 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
9091 * Handle field disable events.
9094 * @param {boolean} value Field is disabled
9096 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
9097 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
9101 * Handle label mouse click events.
9104 * @param {jQuery.Event} e Mouse click event
9106 OO
.ui
.FieldLayout
.prototype.onLabelClick = function () {
9107 this.fieldWidget
.simulateLabelClick();
9112 * Get the widget contained by the field.
9114 * @return {OO.ui.Widget} Field widget
9116 OO
.ui
.FieldLayout
.prototype.getField = function () {
9117 return this.fieldWidget
;
9122 * @param {string} kind 'error' or 'notice'
9123 * @param {string|OO.ui.HtmlSnippet} text
9126 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
9127 var $listItem
, $icon
, message
;
9128 $listItem
= $( '<li>' );
9129 if ( kind
=== 'error' ) {
9130 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
9131 } else if ( kind
=== 'notice' ) {
9132 $icon
= new OO
.ui
.IconWidget( { icon
: 'info' } ).$element
;
9136 message
= new OO
.ui
.LabelWidget( { label
: text
} );
9138 .append( $icon
, message
.$element
)
9139 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
9144 * Set the field alignment mode.
9147 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
9150 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
9151 if ( value
!== this.align
) {
9152 // Default to 'left'
9153 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
9157 if ( value
=== 'inline' ) {
9158 this.$body
.append( this.$field
, this.$label
);
9160 this.$body
.append( this.$label
, this.$field
);
9162 // Set classes. The following classes can be used here:
9163 // * oo-ui-fieldLayout-align-left
9164 // * oo-ui-fieldLayout-align-right
9165 // * oo-ui-fieldLayout-align-top
9166 // * oo-ui-fieldLayout-align-inline
9168 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
9170 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
9178 * Set the list of error messages.
9180 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
9181 * The array may contain strings or OO.ui.HtmlSnippet instances.
9184 OO
.ui
.FieldLayout
.prototype.setErrors = function ( errors
) {
9185 this.errors
= errors
.slice();
9186 this.updateMessages();
9191 * Set the list of notice messages.
9193 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
9194 * The array may contain strings or OO.ui.HtmlSnippet instances.
9197 OO
.ui
.FieldLayout
.prototype.setNotices = function ( notices
) {
9198 this.notices
= notices
.slice();
9199 this.updateMessages();
9204 * Update the rendering of error and notice messages.
9208 OO
.ui
.FieldLayout
.prototype.updateMessages = function () {
9210 this.$messages
.empty();
9212 if ( this.errors
.length
|| this.notices
.length
) {
9213 this.$body
.after( this.$messages
);
9215 this.$messages
.remove();
9219 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
9220 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
9222 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
9223 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
9228 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
9229 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
9230 * is required and is specified before any optional configuration settings.
9232 * Labels can be aligned in one of four ways:
9234 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9235 * A left-alignment is used for forms with many fields.
9236 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9237 * A right-alignment is used for long but familiar forms which users tab through,
9238 * verifying the current field with a quick glance at the label.
9239 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9240 * that users fill out from top to bottom.
9241 * - **inline**: The label is placed after the field-widget and aligned to the left.
9242 * An inline-alignment is best used with checkboxes or radio buttons.
9244 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
9245 * text is specified.
9248 * // Example of an ActionFieldLayout
9249 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
9250 * new OO.ui.TextInputWidget( {
9251 * placeholder: 'Field widget'
9253 * new OO.ui.ButtonWidget( {
9257 * label: 'An ActionFieldLayout. This label is aligned top',
9259 * help: 'This is help text'
9263 * $( 'body' ).append( actionFieldLayout.$element );
9266 * @extends OO.ui.FieldLayout
9269 * @param {OO.ui.Widget} fieldWidget Field widget
9270 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
9272 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
9273 // Allow passing positional parameters inside the config object
9274 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
9275 config
= fieldWidget
;
9276 fieldWidget
= config
.fieldWidget
;
9277 buttonWidget
= config
.buttonWidget
;
9280 // Parent constructor
9281 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
9284 this.buttonWidget
= buttonWidget
;
9285 this.$button
= $( '<div>' );
9286 this.$input
= $( '<div>' );
9290 .addClass( 'oo-ui-actionFieldLayout' );
9292 .addClass( 'oo-ui-actionFieldLayout-button' )
9293 .append( this.buttonWidget
.$element
);
9295 .addClass( 'oo-ui-actionFieldLayout-input' )
9296 .append( this.fieldWidget
.$element
);
9298 .append( this.$input
, this.$button
);
9303 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
9306 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
9307 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
9308 * configured with a label as well. For more information and examples,
9309 * please see the [OOjs UI documentation on MediaWiki][1].
9312 * // Example of a fieldset layout
9313 * var input1 = new OO.ui.TextInputWidget( {
9314 * placeholder: 'A text input field'
9317 * var input2 = new OO.ui.TextInputWidget( {
9318 * placeholder: 'A text input field'
9321 * var fieldset = new OO.ui.FieldsetLayout( {
9322 * label: 'Example of a fieldset layout'
9325 * fieldset.addItems( [
9326 * new OO.ui.FieldLayout( input1, {
9327 * label: 'Field One'
9329 * new OO.ui.FieldLayout( input2, {
9330 * label: 'Field Two'
9333 * $( 'body' ).append( fieldset.$element );
9335 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9338 * @extends OO.ui.Layout
9339 * @mixins OO.ui.mixin.IconElement
9340 * @mixins OO.ui.mixin.LabelElement
9341 * @mixins OO.ui.mixin.GroupElement
9344 * @param {Object} [config] Configuration options
9345 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
9347 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
9348 // Configuration initialization
9349 config
= config
|| {};
9351 // Parent constructor
9352 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
9354 // Mixin constructors
9355 OO
.ui
.mixin
.IconElement
.call( this, config
);
9356 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9357 OO
.ui
.mixin
.GroupElement
.call( this, config
);
9359 if ( config
.help
) {
9360 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
9361 classes
: [ 'oo-ui-fieldsetLayout-help' ],
9366 this.popupButtonWidget
.getPopup().$body
.append(
9368 .text( config
.help
)
9369 .addClass( 'oo-ui-fieldsetLayout-help-content' )
9371 this.$help
= this.popupButtonWidget
.$element
;
9373 this.$help
= $( [] );
9378 .addClass( 'oo-ui-fieldsetLayout' )
9379 .prepend( this.$help
, this.$icon
, this.$label
, this.$group
);
9380 if ( Array
.isArray( config
.items
) ) {
9381 this.addItems( config
.items
);
9387 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
9388 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
9389 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
9390 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
9393 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
9394 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
9395 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
9396 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9398 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
9399 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
9400 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
9401 * some fancier controls. Some controls have both regular and InputWidget variants, for example
9402 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
9403 * often have simplified APIs to match the capabilities of HTML forms.
9404 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
9406 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
9407 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9410 * // Example of a form layout that wraps a fieldset layout
9411 * var input1 = new OO.ui.TextInputWidget( {
9412 * placeholder: 'Username'
9414 * var input2 = new OO.ui.TextInputWidget( {
9415 * placeholder: 'Password',
9418 * var submit = new OO.ui.ButtonInputWidget( {
9422 * var fieldset = new OO.ui.FieldsetLayout( {
9423 * label: 'A form layout'
9425 * fieldset.addItems( [
9426 * new OO.ui.FieldLayout( input1, {
9427 * label: 'Username',
9430 * new OO.ui.FieldLayout( input2, {
9431 * label: 'Password',
9434 * new OO.ui.FieldLayout( submit )
9436 * var form = new OO.ui.FormLayout( {
9437 * items: [ fieldset ],
9438 * action: '/api/formhandler',
9441 * $( 'body' ).append( form.$element );
9444 * @extends OO.ui.Layout
9445 * @mixins OO.ui.mixin.GroupElement
9448 * @param {Object} [config] Configuration options
9449 * @cfg {string} [method] HTML form `method` attribute
9450 * @cfg {string} [action] HTML form `action` attribute
9451 * @cfg {string} [enctype] HTML form `enctype` attribute
9452 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
9454 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
9457 // Configuration initialization
9458 config
= config
|| {};
9460 // Parent constructor
9461 OO
.ui
.FormLayout
.parent
.call( this, config
);
9463 // Mixin constructors
9464 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
9467 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
9469 // Make sure the action is safe
9470 action
= config
.action
;
9471 if ( action
!== undefined && !OO
.ui
.isSafeUrl( action
) ) {
9472 action
= './' + action
;
9477 .addClass( 'oo-ui-formLayout' )
9479 method
: config
.method
,
9481 enctype
: config
.enctype
9483 if ( Array
.isArray( config
.items
) ) {
9484 this.addItems( config
.items
);
9490 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
9491 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
9496 * A 'submit' event is emitted when the form is submitted.
9501 /* Static Properties */
9503 OO
.ui
.FormLayout
.static.tagName
= 'form';
9508 * Handle form submit events.
9511 * @param {jQuery.Event} e Submit event
9514 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
9515 if ( this.emit( 'submit' ) ) {
9521 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
9522 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
9525 * // Example of a panel layout
9526 * var panel = new OO.ui.PanelLayout( {
9530 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
9532 * $( 'body' ).append( panel.$element );
9535 * @extends OO.ui.Layout
9538 * @param {Object} [config] Configuration options
9539 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
9540 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
9541 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
9542 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
9544 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
9545 // Configuration initialization
9546 config
= $.extend( {
9553 // Parent constructor
9554 OO
.ui
.PanelLayout
.parent
.call( this, config
);
9557 this.$element
.addClass( 'oo-ui-panelLayout' );
9558 if ( config
.scrollable
) {
9559 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
9561 if ( config
.padded
) {
9562 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
9564 if ( config
.expanded
) {
9565 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
9567 if ( config
.framed
) {
9568 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
9574 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
9579 * Focus the panel layout
9581 * The default implementation just focuses the first focusable element in the panel
9583 OO
.ui
.PanelLayout
.prototype.focus = function () {
9584 OO
.ui
.findFocusable( this.$element
).focus();
9588 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
9589 * items), with small margins between them. Convenient when you need to put a number of block-level
9590 * widgets on a single line next to each other.
9592 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
9595 * // HorizontalLayout with a text input and a label
9596 * var layout = new OO.ui.HorizontalLayout( {
9598 * new OO.ui.LabelWidget( { label: 'Label' } ),
9599 * new OO.ui.TextInputWidget( { value: 'Text' } )
9602 * $( 'body' ).append( layout.$element );
9605 * @extends OO.ui.Layout
9606 * @mixins OO.ui.mixin.GroupElement
9609 * @param {Object} [config] Configuration options
9610 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
9612 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
9613 // Configuration initialization
9614 config
= config
|| {};
9616 // Parent constructor
9617 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
9619 // Mixin constructors
9620 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
9623 this.$element
.addClass( 'oo-ui-horizontalLayout' );
9624 if ( Array
.isArray( config
.items
) ) {
9625 this.addItems( config
.items
);
9631 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
9632 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);