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-08-16T21:13:48Z
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 * Get the transition duration in milliseconds for dialogs opening/closing
1640 * The dialog should be fully rendered this many milliseconds after the
1641 * ready process has executed.
1643 * @return {number} Transition duration in milliseconds
1645 OO
.ui
.Theme
.prototype.getDialogTransitionDuration = function () {
1650 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
1651 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
1652 * order in which users will navigate through the focusable elements via the "tab" key.
1655 * // TabIndexedElement is mixed into the ButtonWidget class
1656 * // to provide a tabIndex property.
1657 * var button1 = new OO.ui.ButtonWidget( {
1661 * var button2 = new OO.ui.ButtonWidget( {
1665 * var button3 = new OO.ui.ButtonWidget( {
1669 * var button4 = new OO.ui.ButtonWidget( {
1673 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
1679 * @param {Object} [config] Configuration options
1680 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
1681 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
1682 * functionality will be applied to it instead.
1683 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
1684 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
1685 * to remove the element from the tab-navigation flow.
1687 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
1688 // Configuration initialization
1689 config
= $.extend( { tabIndex
: 0 }, config
);
1692 this.$tabIndexed
= null;
1693 this.tabIndex
= null;
1696 this.connect( this, { disable
: 'onTabIndexedElementDisable' } );
1699 this.setTabIndex( config
.tabIndex
);
1700 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
1705 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
1710 * Set the element that should use the tabindex functionality.
1712 * This method is used to retarget a tabindex mixin so that its functionality applies
1713 * to the specified element. If an element is currently using the functionality, the mixin’s
1714 * effect on that element is removed before the new element is set up.
1716 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
1719 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
1720 var tabIndex
= this.tabIndex
;
1721 // Remove attributes from old $tabIndexed
1722 this.setTabIndex( null );
1723 // Force update of new $tabIndexed
1724 this.$tabIndexed
= $tabIndexed
;
1725 this.tabIndex
= tabIndex
;
1726 return this.updateTabIndex();
1730 * Set the value of the tabindex.
1732 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
1735 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
1736 tabIndex
= typeof tabIndex
=== 'number' ? tabIndex
: null;
1738 if ( this.tabIndex
!== tabIndex
) {
1739 this.tabIndex
= tabIndex
;
1740 this.updateTabIndex();
1747 * Update the `tabindex` attribute, in case of changes to tab index or
1753 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
1754 if ( this.$tabIndexed
) {
1755 if ( this.tabIndex
!== null ) {
1756 // Do not index over disabled elements
1757 this.$tabIndexed
.attr( {
1758 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
1759 // Support: ChromeVox and NVDA
1760 // These do not seem to inherit aria-disabled from parent elements
1761 'aria-disabled': this.isDisabled().toString()
1764 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
1771 * Handle disable events.
1774 * @param {boolean} disabled Element is disabled
1776 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
1777 this.updateTabIndex();
1781 * Get the value of the tabindex.
1783 * @return {number|null} Tabindex value
1785 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
1786 return this.tabIndex
;
1790 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
1791 * interface element that can be configured with access keys for accessibility.
1792 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
1794 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
1800 * @param {Object} [config] Configuration options
1801 * @cfg {jQuery} [$button] The button element created by the class.
1802 * If this configuration is omitted, the button element will use a generated `<a>`.
1803 * @cfg {boolean} [framed=true] Render the button with a frame
1805 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
1806 // Configuration initialization
1807 config
= config
|| {};
1810 this.$button
= null;
1812 this.active
= false;
1813 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
1814 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
1815 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
1816 this.onKeyUpHandler
= this.onKeyUp
.bind( this );
1817 this.onClickHandler
= this.onClick
.bind( this );
1818 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
1821 this.$element
.addClass( 'oo-ui-buttonElement' );
1822 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
1823 this.setButtonElement( config
.$button
|| $( '<a>' ) );
1828 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
1830 /* Static Properties */
1833 * Cancel mouse down events.
1835 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
1836 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
1837 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
1842 * @property {boolean}
1844 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
1849 * A 'click' event is emitted when the button element is clicked.
1857 * Set the button element.
1859 * This method is used to retarget a button mixin so that its functionality applies to
1860 * the specified button element instead of the one created by the class. If a button element
1861 * is already set, the method will remove the mixin’s effect on that element.
1863 * @param {jQuery} $button Element to use as button
1865 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
1866 if ( this.$button
) {
1868 .removeClass( 'oo-ui-buttonElement-button' )
1869 .removeAttr( 'role accesskey' )
1871 mousedown
: this.onMouseDownHandler
,
1872 keydown
: this.onKeyDownHandler
,
1873 click
: this.onClickHandler
,
1874 keypress
: this.onKeyPressHandler
1878 this.$button
= $button
1879 .addClass( 'oo-ui-buttonElement-button' )
1880 .attr( { role
: 'button' } )
1882 mousedown
: this.onMouseDownHandler
,
1883 keydown
: this.onKeyDownHandler
,
1884 click
: this.onClickHandler
,
1885 keypress
: this.onKeyPressHandler
1890 * Handles mouse down events.
1893 * @param {jQuery.Event} e Mouse down event
1895 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
1896 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
1899 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
1900 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
1901 // reliably remove the pressed class
1902 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
1903 // Prevent change of focus unless specifically configured otherwise
1904 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
1910 * Handles mouse up events.
1913 * @param {MouseEvent} e Mouse up event
1915 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp = function ( e
) {
1916 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
1919 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
1920 // Stop listening for mouseup, since we only needed this once
1921 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
1925 * Handles mouse click events.
1928 * @param {jQuery.Event} e Mouse click event
1931 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
1932 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
1933 if ( this.emit( 'click' ) ) {
1940 * Handles key down events.
1943 * @param {jQuery.Event} e Key down event
1945 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
1946 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
1949 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
1950 // Run the keyup handler no matter where the key is when the button is let go, so we can
1951 // reliably remove the pressed class
1952 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler
, true );
1956 * Handles key up events.
1959 * @param {KeyboardEvent} e Key up event
1961 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyUp = function ( e
) {
1962 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
1965 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
1966 // Stop listening for keyup, since we only needed this once
1967 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler
, true );
1971 * Handles key press events.
1974 * @param {jQuery.Event} e Key press event
1977 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
1978 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
1979 if ( this.emit( 'click' ) ) {
1986 * Check if button has a frame.
1988 * @return {boolean} Button is framed
1990 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
1995 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
1997 * @param {boolean} [framed] Make button framed, omit to toggle
2000 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
2001 framed
= framed
=== undefined ? !this.framed
: !!framed
;
2002 if ( framed
!== this.framed
) {
2003 this.framed
= framed
;
2005 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
2006 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
2007 this.updateThemeClasses();
2014 * Set the button's active state.
2016 * The active state can be set on:
2018 * - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected
2019 * - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on
2020 * - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page
2023 * @param {boolean} value Make button active
2026 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
2027 this.active
= !!value
;
2028 this.$element
.toggleClass( 'oo-ui-buttonElement-active', this.active
);
2029 this.updateThemeClasses();
2034 * Check if the button is active
2037 * @return {boolean} The button is active
2039 OO
.ui
.mixin
.ButtonElement
.prototype.isActive = function () {
2044 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
2045 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
2046 * items from the group is done through the interface the class provides.
2047 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2049 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
2055 * @param {Object} [config] Configuration options
2056 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
2057 * is omitted, the group element will use a generated `<div>`.
2059 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
2060 // Configuration initialization
2061 config
= config
|| {};
2066 this.aggregateItemEvents
= {};
2069 this.setGroupElement( config
.$group
|| $( '<div>' ) );
2077 * A change event is emitted when the set of selected items changes.
2079 * @param {OO.ui.Element[]} items Items currently in the group
2085 * Set the group element.
2087 * If an element is already set, items will be moved to the new element.
2089 * @param {jQuery} $group Element to use as group
2091 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
2094 this.$group
= $group
;
2095 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2096 this.$group
.append( this.items
[ i
].$element
);
2101 * Check if a group contains no items.
2103 * @return {boolean} Group is empty
2105 OO
.ui
.mixin
.GroupElement
.prototype.isEmpty = function () {
2106 return !this.items
.length
;
2110 * Get all items in the group.
2112 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
2113 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
2116 * @return {OO.ui.Element[]} An array of items.
2118 OO
.ui
.mixin
.GroupElement
.prototype.getItems = function () {
2119 return this.items
.slice( 0 );
2123 * Get an item by its data.
2125 * Only the first item with matching data will be returned. To return all matching items,
2126 * use the #getItemsFromData method.
2128 * @param {Object} data Item data to search for
2129 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2131 OO
.ui
.mixin
.GroupElement
.prototype.getItemFromData = function ( data
) {
2133 hash
= OO
.getHash( data
);
2135 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2136 item
= this.items
[ i
];
2137 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2146 * Get items by their data.
2148 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
2150 * @param {Object} data Item data to search for
2151 * @return {OO.ui.Element[]} Items with equivalent data
2153 OO
.ui
.mixin
.GroupElement
.prototype.getItemsFromData = function ( data
) {
2155 hash
= OO
.getHash( data
),
2158 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2159 item
= this.items
[ i
];
2160 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2169 * Aggregate the events emitted by the group.
2171 * When events are aggregated, the group will listen to all contained items for the event,
2172 * and then emit the event under a new name. The new event will contain an additional leading
2173 * parameter containing the item that emitted the original event. Other arguments emitted from
2174 * the original event are passed through.
2176 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
2177 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
2178 * A `null` value will remove aggregated events.
2180 * @throws {Error} An error is thrown if aggregation already exists.
2182 OO
.ui
.mixin
.GroupElement
.prototype.aggregate = function ( events
) {
2183 var i
, len
, item
, add
, remove
, itemEvent
, groupEvent
;
2185 for ( itemEvent
in events
) {
2186 groupEvent
= events
[ itemEvent
];
2188 // Remove existing aggregated event
2189 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
2190 // Don't allow duplicate aggregations
2192 throw new Error( 'Duplicate item event aggregation for ' + itemEvent
);
2194 // Remove event aggregation from existing items
2195 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2196 item
= this.items
[ i
];
2197 if ( item
.connect
&& item
.disconnect
) {
2199 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
2200 item
.disconnect( this, remove
);
2203 // Prevent future items from aggregating event
2204 delete this.aggregateItemEvents
[ itemEvent
];
2207 // Add new aggregate event
2209 // Make future items aggregate event
2210 this.aggregateItemEvents
[ itemEvent
] = groupEvent
;
2211 // Add event aggregation to existing items
2212 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2213 item
= this.items
[ i
];
2214 if ( item
.connect
&& item
.disconnect
) {
2216 add
[ itemEvent
] = [ 'emit', groupEvent
, item
];
2217 item
.connect( this, add
);
2225 * Add items to the group.
2227 * Items will be added to the end of the group array unless the optional `index` parameter specifies
2228 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
2230 * @param {OO.ui.Element[]} items An array of items to add to the group
2231 * @param {number} [index] Index of the insertion point
2234 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
2235 var i
, len
, item
, itemEvent
, events
, currentIndex
,
2238 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
2241 // Check if item exists then remove it first, effectively "moving" it
2242 currentIndex
= this.items
.indexOf( item
);
2243 if ( currentIndex
>= 0 ) {
2244 this.removeItems( [ item
] );
2245 // Adjust index to compensate for removal
2246 if ( currentIndex
< index
) {
2251 if ( item
.connect
&& item
.disconnect
&& !$.isEmptyObject( this.aggregateItemEvents
) ) {
2253 for ( itemEvent
in this.aggregateItemEvents
) {
2254 events
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
2256 item
.connect( this, events
);
2258 item
.setElementGroup( this );
2259 itemElements
.push( item
.$element
.get( 0 ) );
2262 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
2263 this.$group
.append( itemElements
);
2264 this.items
.push
.apply( this.items
, items
);
2265 } else if ( index
=== 0 ) {
2266 this.$group
.prepend( itemElements
);
2267 this.items
.unshift
.apply( this.items
, items
);
2269 this.items
[ index
].$element
.before( itemElements
);
2270 this.items
.splice
.apply( this.items
, [ index
, 0 ].concat( items
) );
2273 this.emit( 'change', this.getItems() );
2278 * Remove the specified items from a group.
2280 * Removed items are detached (not removed) from the DOM so that they may be reused.
2281 * To remove all items from a group, you may wish to use the #clearItems method instead.
2283 * @param {OO.ui.Element[]} items An array of items to remove
2286 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
2287 var i
, len
, item
, index
, events
, itemEvent
;
2289 // Remove specific items
2290 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
2292 index
= this.items
.indexOf( item
);
2293 if ( index
!== -1 ) {
2294 if ( item
.connect
&& item
.disconnect
&& !$.isEmptyObject( this.aggregateItemEvents
) ) {
2296 for ( itemEvent
in this.aggregateItemEvents
) {
2297 events
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
2299 item
.disconnect( this, events
);
2301 item
.setElementGroup( null );
2302 this.items
.splice( index
, 1 );
2303 item
.$element
.detach();
2307 this.emit( 'change', this.getItems() );
2312 * Clear all items from the group.
2314 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2315 * To remove only a subset of items from a group, use the #removeItems method.
2319 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
2320 var i
, len
, item
, remove
, itemEvent
;
2323 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2324 item
= this.items
[ i
];
2326 item
.connect
&& item
.disconnect
&&
2327 !$.isEmptyObject( this.aggregateItemEvents
)
2330 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
2331 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
2333 item
.disconnect( this, remove
);
2335 item
.setElementGroup( null );
2336 item
.$element
.detach();
2339 this.emit( 'change', this.getItems() );
2345 * IconElement is often mixed into other classes to generate an icon.
2346 * Icons are graphics, about the size of normal text. They are used to aid the user
2347 * in locating a control or to convey information in a space-efficient way. See the
2348 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
2349 * included in the library.
2351 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2357 * @param {Object} [config] Configuration options
2358 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2359 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2360 * the icon element be set to an existing icon instead of the one generated by this class, set a
2361 * value using a jQuery selection. For example:
2363 * // Use a <div> tag instead of a <span>
2365 * // Use an existing icon element instead of the one generated by the class
2366 * $icon: this.$element
2367 * // Use an icon element from a child widget
2368 * $icon: this.childwidget.$element
2369 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
2370 * symbolic names. A map is used for i18n purposes and contains a `default` icon
2371 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
2372 * by the user's language.
2374 * Example of an i18n map:
2376 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2377 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
2378 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2379 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
2380 * text. The icon title is displayed when users move the mouse over the icon.
2382 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
2383 // Configuration initialization
2384 config
= config
|| {};
2389 this.iconTitle
= null;
2392 this.setIcon( config
.icon
|| this.constructor.static.icon
);
2393 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
2394 this.setIconElement( config
.$icon
|| $( '<span>' ) );
2399 OO
.initClass( OO
.ui
.mixin
.IconElement
);
2401 /* Static Properties */
2404 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
2405 * for i18n purposes and contains a `default` icon name and additional names keyed by
2406 * language code. The `default` name is used when no icon is keyed by the user's language.
2408 * Example of an i18n map:
2410 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2412 * Note: the static property will be overridden if the #icon configuration is used.
2416 * @property {Object|string}
2418 OO
.ui
.mixin
.IconElement
.static.icon
= null;
2421 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2422 * function that returns title text, or `null` for no title.
2424 * The static property will be overridden if the #iconTitle configuration is used.
2428 * @property {string|Function|null}
2430 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
2435 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2436 * applies to the specified icon element instead of the one created by the class. If an icon
2437 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2438 * and mixin methods will no longer affect the element.
2440 * @param {jQuery} $icon Element to use as icon
2442 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
2445 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
2446 .removeAttr( 'title' );
2450 .addClass( 'oo-ui-iconElement-icon' )
2451 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
2452 if ( this.iconTitle
!== null ) {
2453 this.$icon
.attr( 'title', this.iconTitle
);
2456 this.updateThemeClasses();
2460 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
2461 * The icon parameter can also be set to a map of icon names. See the #icon config setting
2464 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
2465 * by language code, or `null` to remove the icon.
2468 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
2469 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
2470 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
2472 if ( this.icon
!== icon
) {
2474 if ( this.icon
!== null ) {
2475 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
2477 if ( icon
!== null ) {
2478 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
2484 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
2485 this.updateThemeClasses();
2491 * Set the icon title. Use `null` to remove the title.
2493 * @param {string|Function|null} iconTitle A text string used as the icon title,
2494 * a function that returns title text, or `null` for no title.
2497 OO
.ui
.mixin
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
2498 iconTitle
= typeof iconTitle
=== 'function' ||
2499 ( typeof iconTitle
=== 'string' && iconTitle
.length
) ?
2500 OO
.ui
.resolveMsg( iconTitle
) : null;
2502 if ( this.iconTitle
!== iconTitle
) {
2503 this.iconTitle
= iconTitle
;
2505 if ( this.iconTitle
!== null ) {
2506 this.$icon
.attr( 'title', iconTitle
);
2508 this.$icon
.removeAttr( 'title' );
2517 * Get the symbolic name of the icon.
2519 * @return {string} Icon name
2521 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
2526 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
2528 * @return {string} Icon title text
2530 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
2531 return this.iconTitle
;
2535 * IndicatorElement is often mixed into other classes to generate an indicator.
2536 * Indicators are small graphics that are generally used in two ways:
2538 * - To draw attention to the status of an item. For example, an indicator might be
2539 * used to show that an item in a list has errors that need to be resolved.
2540 * - To clarify the function of a control that acts in an exceptional way (a button
2541 * that opens a menu instead of performing an action directly, for example).
2543 * For a list of indicators included in the library, please see the
2544 * [OOjs UI documentation on MediaWiki] [1].
2546 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2552 * @param {Object} [config] Configuration options
2553 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
2554 * configuration is omitted, the indicator element will use a generated `<span>`.
2555 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2556 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
2558 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2559 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
2560 * or a function that returns title text. The indicator title is displayed when users move
2561 * the mouse over the indicator.
2563 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
2564 // Configuration initialization
2565 config
= config
|| {};
2568 this.$indicator
= null;
2569 this.indicator
= null;
2570 this.indicatorTitle
= null;
2573 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
2574 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
2575 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
2580 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
2582 /* Static Properties */
2585 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2586 * The static property will be overridden if the #indicator configuration is used.
2590 * @property {string|null}
2592 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
2595 * A text string used as the indicator title, a function that returns title text, or `null`
2596 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
2600 * @property {string|Function|null}
2602 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
2607 * Set the indicator element.
2609 * If an element is already set, it will be cleaned up before setting up the new element.
2611 * @param {jQuery} $indicator Element to use as indicator
2613 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
2614 if ( this.$indicator
) {
2616 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
2617 .removeAttr( 'title' );
2620 this.$indicator
= $indicator
2621 .addClass( 'oo-ui-indicatorElement-indicator' )
2622 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
2623 if ( this.indicatorTitle
!== null ) {
2624 this.$indicator
.attr( 'title', this.indicatorTitle
);
2627 this.updateThemeClasses();
2631 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
2633 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
2636 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
2637 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
2639 if ( this.indicator
!== indicator
) {
2640 if ( this.$indicator
) {
2641 if ( this.indicator
!== null ) {
2642 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
2644 if ( indicator
!== null ) {
2645 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
2648 this.indicator
= indicator
;
2651 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
2652 this.updateThemeClasses();
2658 * Set the indicator title.
2660 * The title is displayed when a user moves the mouse over the indicator.
2662 * @param {string|Function|null} indicatorTitle Indicator title text, a function that returns text, or
2663 * `null` for no indicator title
2666 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
2667 indicatorTitle
= typeof indicatorTitle
=== 'function' ||
2668 ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ?
2669 OO
.ui
.resolveMsg( indicatorTitle
) : null;
2671 if ( this.indicatorTitle
!== indicatorTitle
) {
2672 this.indicatorTitle
= indicatorTitle
;
2673 if ( this.$indicator
) {
2674 if ( this.indicatorTitle
!== null ) {
2675 this.$indicator
.attr( 'title', indicatorTitle
);
2677 this.$indicator
.removeAttr( 'title' );
2686 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2688 * @return {string} Symbolic name of indicator
2690 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
2691 return this.indicator
;
2695 * Get the indicator title.
2697 * The title is displayed when a user moves the mouse over the indicator.
2699 * @return {string} Indicator title text
2701 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
2702 return this.indicatorTitle
;
2706 * LabelElement is often mixed into other classes to generate a label, which
2707 * helps identify the function of an interface element.
2708 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
2710 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2716 * @param {Object} [config] Configuration options
2717 * @cfg {jQuery} [$label] The label element created by the class. If this
2718 * configuration is omitted, the label element will use a generated `<span>`.
2719 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
2720 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
2721 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
2722 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2724 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
2725 // Configuration initialization
2726 config
= config
|| {};
2733 this.setLabel( config
.label
|| this.constructor.static.label
);
2734 this.setLabelElement( config
.$label
|| $( '<span>' ) );
2739 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
2744 * @event labelChange
2745 * @param {string} value
2748 /* Static Properties */
2751 * The label text. The label can be specified as a plaintext string, a function that will
2752 * produce a string in the future, or `null` for no label. The static value will
2753 * be overridden if a label is specified with the #label config option.
2757 * @property {string|Function|null}
2759 OO
.ui
.mixin
.LabelElement
.static.label
= null;
2761 /* Static methods */
2764 * Highlight the first occurrence of the query in the given text
2766 * @param {string} text Text
2767 * @param {string} query Query to find
2768 * @return {jQuery} Text with the first match of the query
2769 * sub-string wrapped in highlighted span
2771 OO
.ui
.mixin
.LabelElement
.static.highlightQuery = function ( text
, query
) {
2772 var $result
= $( '<span>' ),
2773 offset
= text
.toLowerCase().indexOf( query
.toLowerCase() );
2775 if ( !query
.length
|| offset
=== -1 ) {
2776 return $result
.text( text
);
2779 document
.createTextNode( text
.slice( 0, offset
) ),
2781 .addClass( 'oo-ui-labelElement-label-highlight' )
2782 .text( text
.slice( offset
, offset
+ query
.length
) ),
2783 document
.createTextNode( text
.slice( offset
+ query
.length
) )
2785 return $result
.contents();
2791 * Set the label element.
2793 * If an element is already set, it will be cleaned up before setting up the new element.
2795 * @param {jQuery} $label Element to use as label
2797 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
2798 if ( this.$label
) {
2799 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
2802 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
2803 this.setLabelContent( this.label
);
2809 * An empty string will result in the label being hidden. A string containing only whitespace will
2810 * be converted to a single ` `.
2812 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
2813 * text; or null for no label
2816 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
2817 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
2818 label
= ( ( typeof label
=== 'string' || label
instanceof jQuery
) && label
.length
) || ( label
instanceof OO
.ui
.HtmlSnippet
&& label
.toString().length
) ? label
: null;
2820 if ( this.label
!== label
) {
2821 if ( this.$label
) {
2822 this.setLabelContent( label
);
2825 this.emit( 'labelChange' );
2828 this.$element
.toggleClass( 'oo-ui-labelElement', !!this.label
);
2834 * Set the label as plain text with a highlighted query
2836 * @param {string} text Text label to set
2837 * @param {string} query Substring of text to highlight
2840 OO
.ui
.mixin
.LabelElement
.prototype.setHighlightedQuery = function ( text
, query
) {
2841 return this.setLabel( this.constructor.static.highlightQuery( text
, query
) );
2847 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
2848 * text; or null for no label
2850 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
2858 * @deprecated since 0.16.0
2860 OO
.ui
.mixin
.LabelElement
.prototype.fitLabel = function () {
2865 * Set the content of the label.
2867 * Do not call this method until after the label element has been set by #setLabelElement.
2870 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
2871 * text; or null for no label
2873 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
2874 if ( typeof label
=== 'string' ) {
2875 if ( label
.match( /^\s*$/ ) ) {
2876 // Convert whitespace only string to a single non-breaking space
2877 this.$label
.html( ' ' );
2879 this.$label
.text( label
);
2881 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
2882 this.$label
.html( label
.toString() );
2883 } else if ( label
instanceof jQuery
) {
2884 this.$label
.empty().append( label
);
2886 this.$label
.empty();
2891 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
2892 * additional functionality to an element created by another class. The class provides
2893 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
2894 * which are used to customize the look and feel of a widget to better describe its
2895 * importance and functionality.
2897 * The library currently contains the following styling flags for general use:
2899 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
2900 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
2901 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
2903 * The flags affect the appearance of the buttons:
2906 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
2907 * var button1 = new OO.ui.ButtonWidget( {
2908 * label: 'Constructive',
2909 * flags: 'constructive'
2911 * var button2 = new OO.ui.ButtonWidget( {
2912 * label: 'Destructive',
2913 * flags: 'destructive'
2915 * var button3 = new OO.ui.ButtonWidget( {
2916 * label: 'Progressive',
2917 * flags: 'progressive'
2919 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
2921 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
2922 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
2924 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
2930 * @param {Object} [config] Configuration options
2931 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
2932 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
2933 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
2934 * @cfg {jQuery} [$flagged] The flagged element. By default,
2935 * the flagged functionality is applied to the element created by the class ($element).
2936 * If a different element is specified, the flagged functionality will be applied to it instead.
2938 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
2939 // Configuration initialization
2940 config
= config
|| {};
2944 this.$flagged
= null;
2947 this.setFlags( config
.flags
);
2948 this.setFlaggedElement( config
.$flagged
|| this.$element
);
2955 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
2956 * parameter contains the name of each modified flag and indicates whether it was
2959 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
2960 * that the flag was added, `false` that the flag was removed.
2966 * Set the flagged element.
2968 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
2969 * If an element is already set, the method will remove the mixin’s effect on that element.
2971 * @param {jQuery} $flagged Element that should be flagged
2973 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
2974 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
2975 return 'oo-ui-flaggedElement-' + flag
;
2978 if ( this.$flagged
) {
2979 this.$flagged
.removeClass( classNames
);
2982 this.$flagged
= $flagged
.addClass( classNames
);
2986 * Check if the specified flag is set.
2988 * @param {string} flag Name of flag
2989 * @return {boolean} The flag is set
2991 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
2992 // This may be called before the constructor, thus before this.flags is set
2993 return this.flags
&& ( flag
in this.flags
);
2997 * Get the names of all flags set.
2999 * @return {string[]} Flag names
3001 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
3002 // This may be called before the constructor, thus before this.flags is set
3003 return Object
.keys( this.flags
|| {} );
3012 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
3013 var flag
, className
,
3016 classPrefix
= 'oo-ui-flaggedElement-';
3018 for ( flag
in this.flags
) {
3019 className
= classPrefix
+ flag
;
3020 changes
[ flag
] = false;
3021 delete this.flags
[ flag
];
3022 remove
.push( className
);
3025 if ( this.$flagged
) {
3026 this.$flagged
.removeClass( remove
.join( ' ' ) );
3029 this.updateThemeClasses();
3030 this.emit( 'flag', changes
);
3036 * Add one or more flags.
3038 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
3039 * or an object keyed by flag name with a boolean value that indicates whether the flag should
3040 * be added (`true`) or removed (`false`).
3044 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
3045 var i
, len
, flag
, className
,
3049 classPrefix
= 'oo-ui-flaggedElement-';
3051 if ( typeof flags
=== 'string' ) {
3052 className
= classPrefix
+ flags
;
3054 if ( !this.flags
[ flags
] ) {
3055 this.flags
[ flags
] = true;
3056 add
.push( className
);
3058 } else if ( Array
.isArray( flags
) ) {
3059 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
3061 className
= classPrefix
+ flag
;
3063 if ( !this.flags
[ flag
] ) {
3064 changes
[ flag
] = true;
3065 this.flags
[ flag
] = true;
3066 add
.push( className
);
3069 } else if ( OO
.isPlainObject( flags
) ) {
3070 for ( flag
in flags
) {
3071 className
= classPrefix
+ flag
;
3072 if ( flags
[ flag
] ) {
3074 if ( !this.flags
[ flag
] ) {
3075 changes
[ flag
] = true;
3076 this.flags
[ flag
] = true;
3077 add
.push( className
);
3081 if ( this.flags
[ flag
] ) {
3082 changes
[ flag
] = false;
3083 delete this.flags
[ flag
];
3084 remove
.push( className
);
3090 if ( this.$flagged
) {
3092 .addClass( add
.join( ' ' ) )
3093 .removeClass( remove
.join( ' ' ) );
3096 this.updateThemeClasses();
3097 this.emit( 'flag', changes
);
3103 * TitledElement is mixed into other classes to provide a `title` attribute.
3104 * Titles are rendered by the browser and are made visible when the user moves
3105 * the mouse over the element. Titles are not visible on touch devices.
3108 * // TitledElement provides a 'title' attribute to the
3109 * // ButtonWidget class
3110 * var button = new OO.ui.ButtonWidget( {
3111 * label: 'Button with Title',
3112 * title: 'I am a button'
3114 * $( 'body' ).append( button.$element );
3120 * @param {Object} [config] Configuration options
3121 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
3122 * If this config is omitted, the title functionality is applied to $element, the
3123 * element created by the class.
3124 * @cfg {string|Function} [title] The title text or a function that returns text. If
3125 * this config is omitted, the value of the {@link #static-title static title} property is used.
3127 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
3128 // Configuration initialization
3129 config
= config
|| {};
3132 this.$titled
= null;
3136 this.setTitle( config
.title
!== undefined ? config
.title
: this.constructor.static.title
);
3137 this.setTitledElement( config
.$titled
|| this.$element
);
3142 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
3144 /* Static Properties */
3147 * The title text, a function that returns text, or `null` for no title. The value of the static property
3148 * is overridden if the #title config option is used.
3152 * @property {string|Function|null}
3154 OO
.ui
.mixin
.TitledElement
.static.title
= null;
3159 * Set the titled element.
3161 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
3162 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
3164 * @param {jQuery} $titled Element that should use the 'titled' functionality
3166 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
3167 if ( this.$titled
) {
3168 this.$titled
.removeAttr( 'title' );
3171 this.$titled
= $titled
;
3173 this.$titled
.attr( 'title', this.title
);
3180 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
3183 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
3184 title
= typeof title
=== 'function' ? OO
.ui
.resolveMsg( title
) : title
;
3185 title
= ( typeof title
=== 'string' && title
.length
) ? title
: null;
3187 if ( this.title
!== title
) {
3188 if ( this.$titled
) {
3189 if ( title
!== null ) {
3190 this.$titled
.attr( 'title', title
);
3192 this.$titled
.removeAttr( 'title' );
3204 * @return {string} Title string
3206 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
3211 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
3212 * Accesskeys allow an user to go to a specific element by using
3213 * a shortcut combination of a browser specific keys + the key
3217 * // AccessKeyedElement provides an 'accesskey' attribute to the
3218 * // ButtonWidget class
3219 * var button = new OO.ui.ButtonWidget( {
3220 * label: 'Button with Accesskey',
3223 * $( 'body' ).append( button.$element );
3229 * @param {Object} [config] Configuration options
3230 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3231 * If this config is omitted, the accesskey functionality is applied to $element, the
3232 * element created by the class.
3233 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3234 * this config is omitted, no accesskey will be added.
3236 OO
.ui
.mixin
.AccessKeyedElement
= function OoUiMixinAccessKeyedElement( config
) {
3237 // Configuration initialization
3238 config
= config
|| {};
3241 this.$accessKeyed
= null;
3242 this.accessKey
= null;
3245 this.setAccessKey( config
.accessKey
|| null );
3246 this.setAccessKeyedElement( config
.$accessKeyed
|| this.$element
);
3251 OO
.initClass( OO
.ui
.mixin
.AccessKeyedElement
);
3253 /* Static Properties */
3256 * The access key, a function that returns a key, or `null` for no accesskey.
3260 * @property {string|Function|null}
3262 OO
.ui
.mixin
.AccessKeyedElement
.static.accessKey
= null;
3267 * Set the accesskeyed element.
3269 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
3270 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
3272 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
3274 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKeyedElement = function ( $accessKeyed
) {
3275 if ( this.$accessKeyed
) {
3276 this.$accessKeyed
.removeAttr( 'accesskey' );
3279 this.$accessKeyed
= $accessKeyed
;
3280 if ( this.accessKey
) {
3281 this.$accessKeyed
.attr( 'accesskey', this.accessKey
);
3288 * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no accesskey
3291 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKey = function ( accessKey
) {
3292 accessKey
= typeof accessKey
=== 'string' ? OO
.ui
.resolveMsg( accessKey
) : null;
3294 if ( this.accessKey
!== accessKey
) {
3295 if ( this.$accessKeyed
) {
3296 if ( accessKey
!== null ) {
3297 this.$accessKeyed
.attr( 'accesskey', accessKey
);
3299 this.$accessKeyed
.removeAttr( 'accesskey' );
3302 this.accessKey
= accessKey
;
3311 * @return {string} accessKey string
3313 OO
.ui
.mixin
.AccessKeyedElement
.prototype.getAccessKey = function () {
3314 return this.accessKey
;
3318 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3319 * feels, and functionality can be customized via the class’s configuration options
3320 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
3323 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
3326 * // A button widget
3327 * var button = new OO.ui.ButtonWidget( {
3328 * label: 'Button with Icon',
3330 * iconTitle: 'Remove'
3332 * $( 'body' ).append( button.$element );
3334 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3337 * @extends OO.ui.Widget
3338 * @mixins OO.ui.mixin.ButtonElement
3339 * @mixins OO.ui.mixin.IconElement
3340 * @mixins OO.ui.mixin.IndicatorElement
3341 * @mixins OO.ui.mixin.LabelElement
3342 * @mixins OO.ui.mixin.TitledElement
3343 * @mixins OO.ui.mixin.FlaggedElement
3344 * @mixins OO.ui.mixin.TabIndexedElement
3345 * @mixins OO.ui.mixin.AccessKeyedElement
3348 * @param {Object} [config] Configuration options
3349 * @cfg {boolean} [active=false] Whether button should be shown as active
3350 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3351 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3352 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3354 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
3355 // Configuration initialization
3356 config
= config
|| {};
3358 // Parent constructor
3359 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
3361 // Mixin constructors
3362 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
3363 OO
.ui
.mixin
.IconElement
.call( this, config
);
3364 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
3365 OO
.ui
.mixin
.LabelElement
.call( this, config
);
3366 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
3367 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
3368 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
3369 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$button
} ) );
3374 this.noFollow
= false;
3377 this.connect( this, { disable
: 'onDisable' } );
3380 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
3382 .addClass( 'oo-ui-buttonWidget' )
3383 .append( this.$button
);
3384 this.setActive( config
.active
);
3385 this.setHref( config
.href
);
3386 this.setTarget( config
.target
);
3387 this.setNoFollow( config
.noFollow
);
3392 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
3393 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
3394 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
3395 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
3396 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
3397 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
3398 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
3399 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
3400 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
3407 OO
.ui
.ButtonWidget
.prototype.onMouseDown = function ( e
) {
3408 if ( !this.isDisabled() ) {
3409 // Remove the tab-index while the button is down to prevent the button from stealing focus
3410 this.$button
.removeAttr( 'tabindex' );
3413 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown
.call( this, e
);
3419 OO
.ui
.ButtonWidget
.prototype.onMouseUp = function ( e
) {
3420 if ( !this.isDisabled() ) {
3421 // Restore the tab-index after the button is up to restore the button's accessibility
3422 this.$button
.attr( 'tabindex', this.tabIndex
);
3425 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp
.call( this, e
);
3429 * Get hyperlink location.
3431 * @return {string} Hyperlink location
3433 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
3438 * Get hyperlink target.
3440 * @return {string} Hyperlink target
3442 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
3447 * Get search engine traversal hint.
3449 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3451 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
3452 return this.noFollow
;
3456 * Set hyperlink location.
3458 * @param {string|null} href Hyperlink location, null to remove
3460 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
3461 href
= typeof href
=== 'string' ? href
: null;
3462 if ( href
!== null && !OO
.ui
.isSafeUrl( href
) ) {
3466 if ( href
!== this.href
) {
3475 * Update the `href` attribute, in case of changes to href or
3481 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
3482 if ( this.href
!== null && !this.isDisabled() ) {
3483 this.$button
.attr( 'href', this.href
);
3485 this.$button
.removeAttr( 'href' );
3492 * Handle disable events.
3495 * @param {boolean} disabled Element is disabled
3497 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
3502 * Set hyperlink target.
3504 * @param {string|null} target Hyperlink target, null to remove
3506 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
3507 target
= typeof target
=== 'string' ? target
: null;
3509 if ( target
!== this.target
) {
3510 this.target
= target
;
3511 if ( target
!== null ) {
3512 this.$button
.attr( 'target', target
);
3514 this.$button
.removeAttr( 'target' );
3522 * Set search engine traversal hint.
3524 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3526 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
3527 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
3529 if ( noFollow
!== this.noFollow
) {
3530 this.noFollow
= noFollow
;
3532 this.$button
.attr( 'rel', 'nofollow' );
3534 this.$button
.removeAttr( 'rel' );
3541 // Override method visibility hints from ButtonElement
3550 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3551 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3552 * removed, and cleared from the group.
3555 * // Example: A ButtonGroupWidget with two buttons
3556 * var button1 = new OO.ui.PopupButtonWidget( {
3557 * label: 'Select a category',
3560 * $content: $( '<p>List of categories...</p>' ),
3565 * var button2 = new OO.ui.ButtonWidget( {
3568 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
3569 * items: [button1, button2]
3571 * $( 'body' ).append( buttonGroup.$element );
3574 * @extends OO.ui.Widget
3575 * @mixins OO.ui.mixin.GroupElement
3578 * @param {Object} [config] Configuration options
3579 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
3581 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
3582 // Configuration initialization
3583 config
= config
|| {};
3585 // Parent constructor
3586 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
3588 // Mixin constructors
3589 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
3592 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
3593 if ( Array
.isArray( config
.items
) ) {
3594 this.addItems( config
.items
);
3600 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
3601 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
3604 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
3605 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
3606 * for a list of icons included in the library.
3609 * // An icon widget with a label
3610 * var myIcon = new OO.ui.IconWidget( {
3614 * // Create a label.
3615 * var iconLabel = new OO.ui.LabelWidget( {
3618 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
3620 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
3623 * @extends OO.ui.Widget
3624 * @mixins OO.ui.mixin.IconElement
3625 * @mixins OO.ui.mixin.TitledElement
3626 * @mixins OO.ui.mixin.FlaggedElement
3629 * @param {Object} [config] Configuration options
3631 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
3632 // Configuration initialization
3633 config
= config
|| {};
3635 // Parent constructor
3636 OO
.ui
.IconWidget
.parent
.call( this, config
);
3638 // Mixin constructors
3639 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
3640 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
3641 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
3644 this.$element
.addClass( 'oo-ui-iconWidget' );
3649 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
3650 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
3651 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
3652 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
3654 /* Static Properties */
3656 OO
.ui
.IconWidget
.static.tagName
= 'span';
3659 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
3660 * attention to the status of an item or to clarify the function of a control. For a list of
3661 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
3664 * // Example of an indicator widget
3665 * var indicator1 = new OO.ui.IndicatorWidget( {
3666 * indicator: 'alert'
3669 * // Create a fieldset layout to add a label
3670 * var fieldset = new OO.ui.FieldsetLayout();
3671 * fieldset.addItems( [
3672 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
3674 * $( 'body' ).append( fieldset.$element );
3676 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3679 * @extends OO.ui.Widget
3680 * @mixins OO.ui.mixin.IndicatorElement
3681 * @mixins OO.ui.mixin.TitledElement
3684 * @param {Object} [config] Configuration options
3686 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
3687 // Configuration initialization
3688 config
= config
|| {};
3690 // Parent constructor
3691 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
3693 // Mixin constructors
3694 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
3695 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
3698 this.$element
.addClass( 'oo-ui-indicatorWidget' );
3703 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
3704 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
3705 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
3707 /* Static Properties */
3709 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
3712 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
3713 * be configured with a `label` option that is set to a string, a label node, or a function:
3715 * - String: a plaintext string
3716 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
3717 * label that includes a link or special styling, such as a gray color or additional graphical elements.
3718 * - Function: a function that will produce a string in the future. Functions are used
3719 * in cases where the value of the label is not currently defined.
3721 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
3722 * will come into focus when the label is clicked.
3725 * // Examples of LabelWidgets
3726 * var label1 = new OO.ui.LabelWidget( {
3727 * label: 'plaintext label'
3729 * var label2 = new OO.ui.LabelWidget( {
3730 * label: $( '<a href="default.html">jQuery label</a>' )
3732 * // Create a fieldset layout with fields for each example
3733 * var fieldset = new OO.ui.FieldsetLayout();
3734 * fieldset.addItems( [
3735 * new OO.ui.FieldLayout( label1 ),
3736 * new OO.ui.FieldLayout( label2 )
3738 * $( 'body' ).append( fieldset.$element );
3741 * @extends OO.ui.Widget
3742 * @mixins OO.ui.mixin.LabelElement
3743 * @mixins OO.ui.mixin.TitledElement
3746 * @param {Object} [config] Configuration options
3747 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
3748 * Clicking the label will focus the specified input field.
3750 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
3751 // Configuration initialization
3752 config
= config
|| {};
3754 // Parent constructor
3755 OO
.ui
.LabelWidget
.parent
.call( this, config
);
3757 // Mixin constructors
3758 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
3759 OO
.ui
.mixin
.TitledElement
.call( this, config
);
3762 this.input
= config
.input
;
3765 if ( this.input
instanceof OO
.ui
.InputWidget
) {
3766 this.$element
.on( 'click', this.onClick
.bind( this ) );
3770 this.$element
.addClass( 'oo-ui-labelWidget' );
3775 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
3776 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
3777 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
3779 /* Static Properties */
3781 OO
.ui
.LabelWidget
.static.tagName
= 'span';
3786 * Handles label mouse click events.
3789 * @param {jQuery.Event} e Mouse click event
3791 OO
.ui
.LabelWidget
.prototype.onClick = function () {
3792 this.input
.simulateLabelClick();
3797 * PendingElement is a mixin that is used to create elements that notify users that something is happening
3798 * and that they should wait before proceeding. The pending state is visually represented with a pending
3799 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
3800 * field of a {@link OO.ui.TextInputWidget text input widget}.
3802 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
3803 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
3804 * in process dialogs.
3807 * function MessageDialog( config ) {
3808 * MessageDialog.parent.call( this, config );
3810 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
3812 * MessageDialog.static.actions = [
3813 * { action: 'save', label: 'Done', flags: 'primary' },
3814 * { label: 'Cancel', flags: 'safe' }
3817 * MessageDialog.prototype.initialize = function () {
3818 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
3819 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
3820 * 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>' );
3821 * this.$body.append( this.content.$element );
3823 * MessageDialog.prototype.getBodyHeight = function () {
3826 * MessageDialog.prototype.getActionProcess = function ( action ) {
3827 * var dialog = this;
3828 * if ( action === 'save' ) {
3829 * dialog.getActions().get({actions: 'save'})[0].pushPending();
3830 * return new OO.ui.Process()
3832 * .next( function () {
3833 * dialog.getActions().get({actions: 'save'})[0].popPending();
3836 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
3839 * var windowManager = new OO.ui.WindowManager();
3840 * $( 'body' ).append( windowManager.$element );
3842 * var dialog = new MessageDialog();
3843 * windowManager.addWindows( [ dialog ] );
3844 * windowManager.openWindow( dialog );
3850 * @param {Object} [config] Configuration options
3851 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
3853 OO
.ui
.mixin
.PendingElement
= function OoUiMixinPendingElement( config
) {
3854 // Configuration initialization
3855 config
= config
|| {};
3859 this.$pending
= null;
3862 this.setPendingElement( config
.$pending
|| this.$element
);
3867 OO
.initClass( OO
.ui
.mixin
.PendingElement
);
3872 * Set the pending element (and clean up any existing one).
3874 * @param {jQuery} $pending The element to set to pending.
3876 OO
.ui
.mixin
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
3877 if ( this.$pending
) {
3878 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
3881 this.$pending
= $pending
;
3882 if ( this.pending
> 0 ) {
3883 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
3888 * Check if an element is pending.
3890 * @return {boolean} Element is pending
3892 OO
.ui
.mixin
.PendingElement
.prototype.isPending = function () {
3893 return !!this.pending
;
3897 * Increase the pending counter. The pending state will remain active until the counter is zero
3898 * (i.e., the number of calls to #pushPending and #popPending is the same).
3902 OO
.ui
.mixin
.PendingElement
.prototype.pushPending = function () {
3903 if ( this.pending
=== 0 ) {
3904 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
3905 this.updateThemeClasses();
3913 * Decrease the pending counter. The pending state will remain active until the counter is zero
3914 * (i.e., the number of calls to #pushPending and #popPending is the same).
3918 OO
.ui
.mixin
.PendingElement
.prototype.popPending = function () {
3919 if ( this.pending
=== 1 ) {
3920 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
3921 this.updateThemeClasses();
3923 this.pending
= Math
.max( 0, this.pending
- 1 );
3929 * Element that can be automatically clipped to visible boundaries.
3931 * Whenever the element's natural height changes, you have to call
3932 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
3933 * clipping correctly.
3935 * The dimensions of #$clippableContainer will be compared to the boundaries of the
3936 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
3937 * then #$clippable will be given a fixed reduced height and/or width and will be made
3938 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
3939 * but you can build a static footer by setting #$clippableContainer to an element that contains
3940 * #$clippable and the footer.
3946 * @param {Object} [config] Configuration options
3947 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
3948 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
3949 * omit to use #$clippable
3951 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
3952 // Configuration initialization
3953 config
= config
|| {};
3956 this.$clippable
= null;
3957 this.$clippableContainer
= null;
3958 this.clipping
= false;
3959 this.clippedHorizontally
= false;
3960 this.clippedVertically
= false;
3961 this.$clippableScrollableContainer
= null;
3962 this.$clippableScroller
= null;
3963 this.$clippableWindow
= null;
3964 this.idealWidth
= null;
3965 this.idealHeight
= null;
3966 this.onClippableScrollHandler
= this.clip
.bind( this );
3967 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
3970 if ( config
.$clippableContainer
) {
3971 this.setClippableContainer( config
.$clippableContainer
);
3973 this.setClippableElement( config
.$clippable
|| this.$element
);
3979 * Set clippable element.
3981 * If an element is already set, it will be cleaned up before setting up the new element.
3983 * @param {jQuery} $clippable Element to make clippable
3985 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
3986 if ( this.$clippable
) {
3987 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
3988 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
3989 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
3992 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
3997 * Set clippable container.
3999 * This is the container that will be measured when deciding whether to clip. When clipping,
4000 * #$clippable will be resized in order to keep the clippable container fully visible.
4002 * If the clippable container is unset, #$clippable will be used.
4004 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
4006 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableContainer = function ( $clippableContainer
) {
4007 this.$clippableContainer
= $clippableContainer
;
4008 if ( this.$clippable
) {
4016 * Do not turn clipping on until after the element is attached to the DOM and visible.
4018 * @param {boolean} [clipping] Enable clipping, omit to toggle
4021 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
4022 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
4024 if ( this.clipping
!== clipping
) {
4025 this.clipping
= clipping
;
4027 this.$clippableScrollableContainer
= $( this.getClosestScrollableElementContainer() );
4028 // If the clippable container is the root, we have to listen to scroll events and check
4029 // jQuery.scrollTop on the window because of browser inconsistencies
4030 this.$clippableScroller
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
4031 $( OO
.ui
.Element
.static.getWindow( this.$clippableScrollableContainer
) ) :
4032 this.$clippableScrollableContainer
;
4033 this.$clippableScroller
.on( 'scroll', this.onClippableScrollHandler
);
4034 this.$clippableWindow
= $( this.getElementWindow() )
4035 .on( 'resize', this.onClippableWindowResizeHandler
);
4036 // Initial clip after visible
4039 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
4040 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4042 this.$clippableScrollableContainer
= null;
4043 this.$clippableScroller
.off( 'scroll', this.onClippableScrollHandler
);
4044 this.$clippableScroller
= null;
4045 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
4046 this.$clippableWindow
= null;
4054 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4056 * @return {boolean} Element will be clipped to the visible area
4058 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
4059 return this.clipping
;
4063 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
4065 * @return {boolean} Part of the element is being clipped
4067 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
4068 return this.clippedHorizontally
|| this.clippedVertically
;
4072 * Check if the right of the element is being clipped by the nearest scrollable container.
4074 * @return {boolean} Part of the element is being clipped
4076 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
4077 return this.clippedHorizontally
;
4081 * Check if the bottom of the element is being clipped by the nearest scrollable container.
4083 * @return {boolean} Part of the element is being clipped
4085 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
4086 return this.clippedVertically
;
4090 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
4092 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
4093 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
4095 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
4096 this.idealWidth
= width
;
4097 this.idealHeight
= height
;
4099 if ( !this.clipping
) {
4100 // Update dimensions
4101 this.$clippable
.css( { width
: width
, height
: height
} );
4103 // While clipping, idealWidth and idealHeight are not considered
4107 * Clip element to visible boundaries and allow scrolling when needed. You should call this method
4108 * when the element's natural height changes.
4110 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
4111 * overlapped by, the visible area of the nearest scrollable container.
4113 * Because calling clip() when the natural height changes isn't always possible, we also set
4114 * max-height when the element isn't being clipped. This means that if the element tries to grow
4115 * beyond the edge, something reasonable will happen before clip() is called.
4119 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
4120 var $container
, extraHeight
, extraWidth
, ccOffset
,
4121 $scrollableContainer
, scOffset
, scHeight
, scWidth
,
4122 ccWidth
, scrollerIsWindow
, scrollTop
, scrollLeft
,
4123 desiredWidth
, desiredHeight
, allotedWidth
, allotedHeight
,
4124 naturalWidth
, naturalHeight
, clipWidth
, clipHeight
,
4125 buffer
= 7; // Chosen by fair dice roll
4127 if ( !this.clipping
) {
4128 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
4132 $container
= this.$clippableContainer
|| this.$clippable
;
4133 extraHeight
= $container
.outerHeight() - this.$clippable
.outerHeight();
4134 extraWidth
= $container
.outerWidth() - this.$clippable
.outerWidth();
4135 ccOffset
= $container
.offset();
4136 $scrollableContainer
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
4137 this.$clippableWindow
: this.$clippableScrollableContainer
;
4138 scOffset
= $scrollableContainer
.offset() || { top
: 0, left
: 0 };
4139 scHeight
= $scrollableContainer
.innerHeight() - buffer
;
4140 scWidth
= $scrollableContainer
.innerWidth() - buffer
;
4141 ccWidth
= $container
.outerWidth() + buffer
;
4142 scrollerIsWindow
= this.$clippableScroller
[ 0 ] === this.$clippableWindow
[ 0 ];
4143 scrollTop
= scrollerIsWindow
? this.$clippableScroller
.scrollTop() : 0;
4144 scrollLeft
= scrollerIsWindow
? this.$clippableScroller
.scrollLeft() : 0;
4145 desiredWidth
= ccOffset
.left
< 0 ?
4146 ccWidth
+ ccOffset
.left
:
4147 ( scOffset
.left
+ scrollLeft
+ scWidth
) - ccOffset
.left
;
4148 desiredHeight
= ( scOffset
.top
+ scrollTop
+ scHeight
) - ccOffset
.top
;
4149 // It should never be desirable to exceed the dimensions of the browser viewport... right?
4150 desiredWidth
= Math
.min( desiredWidth
, document
.documentElement
.clientWidth
);
4151 desiredHeight
= Math
.min( desiredHeight
, document
.documentElement
.clientHeight
);
4152 allotedWidth
= Math
.ceil( desiredWidth
- extraWidth
);
4153 allotedHeight
= Math
.ceil( desiredHeight
- extraHeight
);
4154 naturalWidth
= this.$clippable
.prop( 'scrollWidth' );
4155 naturalHeight
= this.$clippable
.prop( 'scrollHeight' );
4156 clipWidth
= allotedWidth
< naturalWidth
;
4157 clipHeight
= allotedHeight
< naturalHeight
;
4160 this.$clippable
.css( {
4161 overflowX
: 'scroll',
4162 width
: Math
.max( 0, allotedWidth
),
4166 this.$clippable
.css( {
4168 width
: this.idealWidth
? this.idealWidth
- extraWidth
: '',
4169 maxWidth
: Math
.max( 0, allotedWidth
)
4173 this.$clippable
.css( {
4174 overflowY
: 'scroll',
4175 height
: Math
.max( 0, allotedHeight
),
4179 this.$clippable
.css( {
4181 height
: this.idealHeight
? this.idealHeight
- extraHeight
: '',
4182 maxHeight
: Math
.max( 0, allotedHeight
)
4186 // If we stopped clipping in at least one of the dimensions
4187 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
4188 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4191 this.clippedHorizontally
= clipWidth
;
4192 this.clippedVertically
= clipHeight
;
4198 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
4199 * By default, each popup has an anchor that points toward its origin.
4200 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
4203 * // A popup widget.
4204 * var popup = new OO.ui.PopupWidget( {
4205 * $content: $( '<p>Hi there!</p>' ),
4210 * $( 'body' ).append( popup.$element );
4211 * // To display the popup, toggle the visibility to 'true'.
4212 * popup.toggle( true );
4214 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
4217 * @extends OO.ui.Widget
4218 * @mixins OO.ui.mixin.LabelElement
4219 * @mixins OO.ui.mixin.ClippableElement
4222 * @param {Object} [config] Configuration options
4223 * @cfg {number} [width=320] Width of popup in pixels
4224 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
4225 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
4226 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
4227 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
4228 * popup is leaning towards the right of the screen.
4229 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
4230 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
4231 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
4232 * sentence in the given language.
4233 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
4234 * See the [OOjs UI docs on MediaWiki][3] for an example.
4235 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
4236 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
4237 * @cfg {jQuery} [$content] Content to append to the popup's body
4238 * @cfg {jQuery} [$footer] Content to append to the popup's footer
4239 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
4240 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
4241 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
4243 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
4244 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
4246 * @cfg {boolean} [padded=false] Add padding to the popup's body
4248 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
4249 // Configuration initialization
4250 config
= config
|| {};
4252 // Parent constructor
4253 OO
.ui
.PopupWidget
.parent
.call( this, config
);
4255 // Properties (must be set before ClippableElement constructor call)
4256 this.$body
= $( '<div>' );
4257 this.$popup
= $( '<div>' );
4259 // Mixin constructors
4260 OO
.ui
.mixin
.LabelElement
.call( this, config
);
4261 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, {
4262 $clippable
: this.$body
,
4263 $clippableContainer
: this.$popup
4267 this.$anchor
= $( '<div>' );
4268 // If undefined, will be computed lazily in updateDimensions()
4269 this.$container
= config
.$container
;
4270 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
4271 this.autoClose
= !!config
.autoClose
;
4272 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
4273 this.transitionTimeout
= null;
4275 this.width
= config
.width
!== undefined ? config
.width
: 320;
4276 this.height
= config
.height
!== undefined ? config
.height
: null;
4277 this.setAlignment( config
.align
);
4278 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
4279 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
4282 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
4283 this.$body
.addClass( 'oo-ui-popupWidget-body' );
4284 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
4286 .addClass( 'oo-ui-popupWidget-popup' )
4287 .append( this.$body
);
4289 .addClass( 'oo-ui-popupWidget' )
4290 .append( this.$popup
, this.$anchor
);
4291 // Move content, which was added to #$element by OO.ui.Widget, to the body
4292 // FIXME This is gross, we should use '$body' or something for the config
4293 if ( config
.$content
instanceof jQuery
) {
4294 this.$body
.append( config
.$content
);
4297 if ( config
.padded
) {
4298 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
4301 if ( config
.head
) {
4302 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
4303 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
4304 this.$head
= $( '<div>' )
4305 .addClass( 'oo-ui-popupWidget-head' )
4306 .append( this.$label
, this.closeButton
.$element
);
4307 this.$popup
.prepend( this.$head
);
4310 if ( config
.$footer
) {
4311 this.$footer
= $( '<div>' )
4312 .addClass( 'oo-ui-popupWidget-footer' )
4313 .append( config
.$footer
);
4314 this.$popup
.append( this.$footer
);
4317 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
4318 // that reference properties not initialized at that time of parent class construction
4319 // TODO: Find a better way to handle post-constructor setup
4320 this.visible
= false;
4321 this.$element
.addClass( 'oo-ui-element-hidden' );
4326 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
4327 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
4328 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
4333 * Handles mouse down events.
4336 * @param {MouseEvent} e Mouse down event
4338 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
4341 !$.contains( this.$element
[ 0 ], e
.target
) &&
4342 ( !this.$autoCloseIgnore
|| !this.$autoCloseIgnore
.has( e
.target
).length
)
4344 this.toggle( false );
4349 * Bind mouse down listener.
4353 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
4354 // Capture clicks outside popup
4355 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler
, true );
4359 * Handles close button click events.
4363 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
4364 if ( this.isVisible() ) {
4365 this.toggle( false );
4370 * Unbind mouse down listener.
4374 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
4375 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler
, true );
4379 * Handles key down events.
4382 * @param {KeyboardEvent} e Key down event
4384 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
4386 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
4389 this.toggle( false );
4391 e
.stopPropagation();
4396 * Bind key down listener.
4400 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
4401 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
4405 * Unbind key down listener.
4409 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
4410 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
4414 * Show, hide, or toggle the visibility of the anchor.
4416 * @param {boolean} [show] Show anchor, omit to toggle
4418 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
4419 show
= show
=== undefined ? !this.anchored
: !!show
;
4421 if ( this.anchored
!== show
) {
4423 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
4425 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
4427 this.anchored
= show
;
4432 * Check if the anchor is visible.
4434 * @return {boolean} Anchor is visible
4436 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
4443 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
4445 show
= show
=== undefined ? !this.isVisible() : !!show
;
4447 change
= show
!== this.isVisible();
4450 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
4454 if ( this.autoClose
) {
4455 this.bindMouseDownListener();
4456 this.bindKeyDownListener();
4458 this.updateDimensions();
4459 this.toggleClipping( true );
4461 this.toggleClipping( false );
4462 if ( this.autoClose
) {
4463 this.unbindMouseDownListener();
4464 this.unbindKeyDownListener();
4473 * Set the size of the popup.
4475 * Changing the size may also change the popup's position depending on the alignment.
4477 * @param {number} width Width in pixels
4478 * @param {number} height Height in pixels
4479 * @param {boolean} [transition=false] Use a smooth transition
4482 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
4484 this.height
= height
!== undefined ? height
: null;
4485 if ( this.isVisible() ) {
4486 this.updateDimensions( transition
);
4491 * Update the size and position.
4493 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
4494 * be called automatically.
4496 * @param {boolean} [transition=false] Use a smooth transition
4499 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
4500 var popupOffset
, originOffset
, containerLeft
, containerWidth
, containerRight
,
4501 popupLeft
, popupRight
, overlapLeft
, overlapRight
, anchorWidth
,
4505 if ( !this.$container
) {
4506 // Lazy-initialize $container if not specified in constructor
4507 this.$container
= $( this.getClosestScrollableElementContainer() );
4510 // Set height and width before measuring things, since it might cause our measurements
4511 // to change (e.g. due to scrollbars appearing or disappearing)
4514 height
: this.height
!== null ? this.height
: 'auto'
4517 // If we are in RTL, we need to flip the alignment, unless it is center
4518 if ( align
=== 'forwards' || align
=== 'backwards' ) {
4519 if ( this.$container
.css( 'direction' ) === 'rtl' ) {
4520 align
= ( { forwards
: 'force-left', backwards
: 'force-right' } )[ this.align
];
4522 align
= ( { forwards
: 'force-right', backwards
: 'force-left' } )[ this.align
];
4527 // Compute initial popupOffset based on alignment
4528 popupOffset
= this.width
* ( { 'force-left': -1, center
: -0.5, 'force-right': 0 } )[ align
];
4530 // Figure out if this will cause the popup to go beyond the edge of the container
4531 originOffset
= this.$element
.offset().left
;
4532 containerLeft
= this.$container
.offset().left
;
4533 containerWidth
= this.$container
.innerWidth();
4534 containerRight
= containerLeft
+ containerWidth
;
4535 popupLeft
= popupOffset
- this.containerPadding
;
4536 popupRight
= popupOffset
+ this.containerPadding
+ this.width
+ this.containerPadding
;
4537 overlapLeft
= ( originOffset
+ popupLeft
) - containerLeft
;
4538 overlapRight
= containerRight
- ( originOffset
+ popupRight
);
4540 // Adjust offset to make the popup not go beyond the edge, if needed
4541 if ( overlapRight
< 0 ) {
4542 popupOffset
+= overlapRight
;
4543 } else if ( overlapLeft
< 0 ) {
4544 popupOffset
-= overlapLeft
;
4547 // Adjust offset to avoid anchor being rendered too close to the edge
4548 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
4549 // TODO: Find a measurement that works for CSS anchors and image anchors
4550 anchorWidth
= this.$anchor
[ 0 ].scrollWidth
* 2;
4551 if ( popupOffset
+ this.width
< anchorWidth
) {
4552 popupOffset
= anchorWidth
- this.width
;
4553 } else if ( -popupOffset
< anchorWidth
) {
4554 popupOffset
= -anchorWidth
;
4557 // Prevent transition from being interrupted
4558 clearTimeout( this.transitionTimeout
);
4560 // Enable transition
4561 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
4564 // Position body relative to anchor
4565 this.$popup
.css( 'margin-left', popupOffset
);
4568 // Prevent transitioning after transition is complete
4569 this.transitionTimeout
= setTimeout( function () {
4570 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
4573 // Prevent transitioning immediately
4574 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
4577 // Reevaluate clipping state since we've relocated and resized the popup
4584 * Set popup alignment
4586 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
4587 * `backwards` or `forwards`.
4589 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
4590 // Validate alignment and transform deprecated values
4591 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
4592 this.align
= { left
: 'force-right', right
: 'force-left' }[ align
] || align
;
4594 this.align
= 'center';
4599 * Get popup alignment
4601 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
4602 * `backwards` or `forwards`.
4604 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
4609 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
4610 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
4611 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
4612 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
4618 * @param {Object} [config] Configuration options
4619 * @cfg {Object} [popup] Configuration to pass to popup
4620 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
4622 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
4623 // Configuration initialization
4624 config
= config
|| {};
4627 this.popup
= new OO
.ui
.PopupWidget( $.extend(
4628 { autoClose
: true },
4630 { $autoCloseIgnore
: this.$element
}
4639 * @return {OO.ui.PopupWidget} Popup widget
4641 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
4646 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
4647 * which is used to display additional information or options.
4650 * // Example of a popup button.
4651 * var popupButton = new OO.ui.PopupButtonWidget( {
4652 * label: 'Popup button with options',
4655 * $content: $( '<p>Additional options here.</p>' ),
4657 * align: 'force-left'
4660 * // Append the button to the DOM.
4661 * $( 'body' ).append( popupButton.$element );
4664 * @extends OO.ui.ButtonWidget
4665 * @mixins OO.ui.mixin.PopupElement
4668 * @param {Object} [config] Configuration options
4670 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
4671 // Parent constructor
4672 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
4674 // Mixin constructors
4675 OO
.ui
.mixin
.PopupElement
.call( this, config
);
4678 this.connect( this, { click
: 'onAction' } );
4682 .addClass( 'oo-ui-popupButtonWidget' )
4683 .attr( 'aria-haspopup', 'true' )
4684 .append( this.popup
.$element
);
4689 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
4690 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
4695 * Handle the button action being triggered.
4699 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
4700 this.popup
.toggle();
4704 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
4706 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
4711 * @mixins OO.ui.mixin.GroupElement
4714 * @param {Object} [config] Configuration options
4716 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
4717 // Mixin constructors
4718 OO
.ui
.mixin
.GroupElement
.call( this, config
);
4723 OO
.mixinClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
4728 * Set the disabled state of the widget.
4730 * This will also update the disabled state of child widgets.
4732 * @param {boolean} disabled Disable widget
4735 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
4739 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
4740 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
4742 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
4744 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4745 this.items
[ i
].updateDisabled();
4753 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
4755 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
4756 * allows bidirectional communication.
4758 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
4766 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
4773 * Check if widget is disabled.
4775 * Checks parent if present, making disabled state inheritable.
4777 * @return {boolean} Widget is disabled
4779 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
4780 return this.disabled
||
4781 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
4785 * Set group element is in.
4787 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
4790 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
4792 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
4793 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
4795 // Initialize item disabled states
4796 this.updateDisabled();
4802 * OptionWidgets are special elements that can be selected and configured with data. The
4803 * data is often unique for each option, but it does not have to be. OptionWidgets are used
4804 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
4805 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
4807 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
4810 * @extends OO.ui.Widget
4811 * @mixins OO.ui.mixin.ItemWidget
4812 * @mixins OO.ui.mixin.LabelElement
4813 * @mixins OO.ui.mixin.FlaggedElement
4814 * @mixins OO.ui.mixin.AccessKeyedElement
4817 * @param {Object} [config] Configuration options
4819 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
4820 // Configuration initialization
4821 config
= config
|| {};
4823 // Parent constructor
4824 OO
.ui
.OptionWidget
.parent
.call( this, config
);
4826 // Mixin constructors
4827 OO
.ui
.mixin
.ItemWidget
.call( this );
4828 OO
.ui
.mixin
.LabelElement
.call( this, config
);
4829 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
4830 OO
.ui
.mixin
.AccessKeyedElement
.call( this, config
);
4833 this.selected
= false;
4834 this.highlighted
= false;
4835 this.pressed
= false;
4839 .data( 'oo-ui-optionWidget', this )
4840 // Allow programmatic focussing (and by accesskey), but not tabbing
4841 .attr( 'tabindex', '-1' )
4842 .attr( 'role', 'option' )
4843 .attr( 'aria-selected', 'false' )
4844 .addClass( 'oo-ui-optionWidget' )
4845 .append( this.$label
);
4850 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
4851 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
4852 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
4853 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
4854 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
4856 /* Static Properties */
4858 OO
.ui
.OptionWidget
.static.selectable
= true;
4860 OO
.ui
.OptionWidget
.static.highlightable
= true;
4862 OO
.ui
.OptionWidget
.static.pressable
= true;
4864 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
4869 * Check if the option can be selected.
4871 * @return {boolean} Item is selectable
4873 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
4874 return this.constructor.static.selectable
&& !this.isDisabled() && this.isVisible();
4878 * Check if the option can be highlighted. A highlight indicates that the option
4879 * may be selected when a user presses enter or clicks. Disabled items cannot
4882 * @return {boolean} Item is highlightable
4884 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
4885 return this.constructor.static.highlightable
&& !this.isDisabled() && this.isVisible();
4889 * Check if the option can be pressed. The pressed state occurs when a user mouses
4890 * down on an item, but has not yet let go of the mouse.
4892 * @return {boolean} Item is pressable
4894 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
4895 return this.constructor.static.pressable
&& !this.isDisabled() && this.isVisible();
4899 * Check if the option is selected.
4901 * @return {boolean} Item is selected
4903 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
4904 return this.selected
;
4908 * Check if the option is highlighted. A highlight indicates that the
4909 * item may be selected when a user presses enter or clicks.
4911 * @return {boolean} Item is highlighted
4913 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
4914 return this.highlighted
;
4918 * Check if the option is pressed. The pressed state occurs when a user mouses
4919 * down on an item, but has not yet let go of the mouse. The item may appear
4920 * selected, but it will not be selected until the user releases the mouse.
4922 * @return {boolean} Item is pressed
4924 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
4925 return this.pressed
;
4929 * Set the option’s selected state. In general, all modifications to the selection
4930 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
4931 * method instead of this method.
4933 * @param {boolean} [state=false] Select option
4936 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
4937 if ( this.constructor.static.selectable
) {
4938 this.selected
= !!state
;
4940 .toggleClass( 'oo-ui-optionWidget-selected', state
)
4941 .attr( 'aria-selected', state
.toString() );
4942 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
4943 this.scrollElementIntoView();
4945 this.updateThemeClasses();
4951 * Set the option’s highlighted state. In general, all programmatic
4952 * modifications to the highlight should be handled by the
4953 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
4954 * method instead of this method.
4956 * @param {boolean} [state=false] Highlight option
4959 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
4960 if ( this.constructor.static.highlightable
) {
4961 this.highlighted
= !!state
;
4962 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
4963 this.updateThemeClasses();
4969 * Set the option’s pressed state. In general, all
4970 * programmatic modifications to the pressed state should be handled by the
4971 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
4972 * method instead of this method.
4974 * @param {boolean} [state=false] Press option
4977 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
4978 if ( this.constructor.static.pressable
) {
4979 this.pressed
= !!state
;
4980 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
4981 this.updateThemeClasses();
4987 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
4988 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
4989 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
4992 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
4993 * information, please see the [OOjs UI documentation on MediaWiki][1].
4996 * // Example of a select widget with three options
4997 * var select = new OO.ui.SelectWidget( {
4999 * new OO.ui.OptionWidget( {
5001 * label: 'Option One',
5003 * new OO.ui.OptionWidget( {
5005 * label: 'Option Two',
5007 * new OO.ui.OptionWidget( {
5009 * label: 'Option Three',
5013 * $( 'body' ).append( select.$element );
5015 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5019 * @extends OO.ui.Widget
5020 * @mixins OO.ui.mixin.GroupWidget
5023 * @param {Object} [config] Configuration options
5024 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
5025 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
5026 * the [OOjs UI documentation on MediaWiki] [2] for examples.
5027 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5029 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
5030 // Configuration initialization
5031 config
= config
|| {};
5033 // Parent constructor
5034 OO
.ui
.SelectWidget
.parent
.call( this, config
);
5036 // Mixin constructors
5037 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
5040 this.pressed
= false;
5041 this.selecting
= null;
5042 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
5043 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
5044 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
5045 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
5046 this.keyPressBuffer
= '';
5047 this.keyPressBufferTimer
= null;
5048 this.blockMouseOverEvents
= 0;
5051 this.connect( this, {
5055 focusin
: this.onFocus
.bind( this ),
5056 mousedown
: this.onMouseDown
.bind( this ),
5057 mouseover
: this.onMouseOver
.bind( this ),
5058 mouseleave
: this.onMouseLeave
.bind( this )
5063 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
5064 .attr( 'role', 'listbox' );
5065 if ( Array
.isArray( config
.items
) ) {
5066 this.addItems( config
.items
);
5072 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
5073 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
5080 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
5082 * @param {OO.ui.OptionWidget|null} item Highlighted item
5088 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
5089 * pressed state of an option.
5091 * @param {OO.ui.OptionWidget|null} item Pressed item
5097 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
5099 * @param {OO.ui.OptionWidget|null} item Selected item
5104 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
5105 * @param {OO.ui.OptionWidget} item Chosen item
5111 * An `add` event is emitted when options are added to the select with the #addItems method.
5113 * @param {OO.ui.OptionWidget[]} items Added items
5114 * @param {number} index Index of insertion point
5120 * A `remove` event is emitted when options are removed from the select with the #clearItems
5121 * or #removeItems methods.
5123 * @param {OO.ui.OptionWidget[]} items Removed items
5129 * Handle focus events
5132 * @param {jQuery.Event} event
5134 OO
.ui
.SelectWidget
.prototype.onFocus = function ( event
) {
5136 if ( event
.target
=== this.$element
[ 0 ] ) {
5137 // This widget was focussed, e.g. by the user tabbing to it.
5138 // The styles for focus state depend on one of the items being selected.
5139 if ( !this.getSelectedItem() ) {
5140 item
= this.getFirstSelectableItem();
5143 // One of the options got focussed (and the event bubbled up here).
5144 // They can't be tabbed to, but they can be activated using accesskeys.
5145 item
= this.getTargetItem( event
);
5149 if ( item
.constructor.static.highlightable
) {
5150 this.highlightItem( item
);
5152 this.selectItem( item
);
5156 if ( event
.target
!== this.$element
[ 0 ] ) {
5157 this.$element
.focus();
5162 * Handle mouse down events.
5165 * @param {jQuery.Event} e Mouse down event
5167 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
5170 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
5171 this.togglePressed( true );
5172 item
= this.getTargetItem( e
);
5173 if ( item
&& item
.isSelectable() ) {
5174 this.pressItem( item
);
5175 this.selecting
= item
;
5176 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
5177 this.getElementDocument().addEventListener( 'mousemove', this.onMouseMoveHandler
, true );
5184 * Handle mouse up events.
5187 * @param {MouseEvent} e Mouse up event
5189 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
5192 this.togglePressed( false );
5193 if ( !this.selecting
) {
5194 item
= this.getTargetItem( e
);
5195 if ( item
&& item
.isSelectable() ) {
5196 this.selecting
= item
;
5199 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
&& this.selecting
) {
5200 this.pressItem( null );
5201 this.chooseItem( this.selecting
);
5202 this.selecting
= null;
5205 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
5206 this.getElementDocument().removeEventListener( 'mousemove', this.onMouseMoveHandler
, true );
5212 * Handle mouse move events.
5215 * @param {MouseEvent} e Mouse move event
5217 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
5220 if ( !this.isDisabled() && this.pressed
) {
5221 item
= this.getTargetItem( e
);
5222 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
5223 this.pressItem( item
);
5224 this.selecting
= item
;
5230 * Handle mouse over events.
5233 * @param {jQuery.Event} e Mouse over event
5235 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
5237 if ( this.blockMouseOverEvents
) {
5240 if ( !this.isDisabled() ) {
5241 item
= this.getTargetItem( e
);
5242 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
5248 * Handle mouse leave events.
5251 * @param {jQuery.Event} e Mouse over event
5253 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
5254 if ( !this.isDisabled() ) {
5255 this.highlightItem( null );
5261 * Handle key down events.
5264 * @param {KeyboardEvent} e Key down event
5266 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
5269 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
5271 if ( !this.isDisabled() && this.isVisible() ) {
5272 switch ( e
.keyCode
) {
5273 case OO
.ui
.Keys
.ENTER
:
5274 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
5275 // Was only highlighted, now let's select it. No-op if already selected.
5276 this.chooseItem( currentItem
);
5281 case OO
.ui
.Keys
.LEFT
:
5282 this.clearKeyPressBuffer();
5283 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
5286 case OO
.ui
.Keys
.DOWN
:
5287 case OO
.ui
.Keys
.RIGHT
:
5288 this.clearKeyPressBuffer();
5289 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
5292 case OO
.ui
.Keys
.ESCAPE
:
5293 case OO
.ui
.Keys
.TAB
:
5294 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
5295 currentItem
.setHighlighted( false );
5297 this.unbindKeyDownListener();
5298 this.unbindKeyPressListener();
5299 // Don't prevent tabbing away / defocusing
5305 if ( nextItem
.constructor.static.highlightable
) {
5306 this.highlightItem( nextItem
);
5308 this.chooseItem( nextItem
);
5310 this.scrollItemIntoView( nextItem
);
5315 e
.stopPropagation();
5321 * Bind key down listener.
5325 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
5326 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler
, true );
5330 * Unbind key down listener.
5334 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
5335 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler
, true );
5339 * Scroll item into view, preventing spurious mouse highlight actions from happening.
5341 * @param {OO.ui.OptionWidget} item Item to scroll into view
5343 OO
.ui
.SelectWidget
.prototype.scrollItemIntoView = function ( item
) {
5345 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling
5346 // and around 100-150 ms after it is finished.
5347 this.blockMouseOverEvents
++;
5348 item
.scrollElementIntoView().done( function () {
5349 setTimeout( function () {
5350 widget
.blockMouseOverEvents
--;
5356 * Clear the key-press buffer
5360 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
5361 if ( this.keyPressBufferTimer
) {
5362 clearTimeout( this.keyPressBufferTimer
);
5363 this.keyPressBufferTimer
= null;
5365 this.keyPressBuffer
= '';
5369 * Handle key press events.
5372 * @param {KeyboardEvent} e Key press event
5374 OO
.ui
.SelectWidget
.prototype.onKeyPress = function ( e
) {
5375 var c
, filter
, item
;
5377 if ( !e
.charCode
) {
5378 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
5379 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
5384 if ( String
.fromCodePoint
) {
5385 c
= String
.fromCodePoint( e
.charCode
);
5387 c
= String
.fromCharCode( e
.charCode
);
5390 if ( this.keyPressBufferTimer
) {
5391 clearTimeout( this.keyPressBufferTimer
);
5393 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
5395 item
= this.getHighlightedItem() || this.getSelectedItem();
5397 if ( this.keyPressBuffer
=== c
) {
5398 // Common (if weird) special case: typing "xxxx" will cycle through all
5399 // the items beginning with "x".
5401 item
= this.getRelativeSelectableItem( item
, 1 );
5404 this.keyPressBuffer
+= c
;
5407 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
5408 if ( !item
|| !filter( item
) ) {
5409 item
= this.getRelativeSelectableItem( item
, 1, filter
);
5412 if ( this.isVisible() && item
.constructor.static.highlightable
) {
5413 this.highlightItem( item
);
5415 this.chooseItem( item
);
5417 this.scrollItemIntoView( item
);
5421 e
.stopPropagation();
5425 * Get a matcher for the specific string
5428 * @param {string} s String to match against items
5429 * @param {boolean} [exact=false] Only accept exact matches
5430 * @return {Function} function ( OO.ui.OptionItem ) => boolean
5432 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
, exact
) {
5435 if ( s
.normalize
) {
5438 s
= exact
? s
.trim() : s
.replace( /^\s+/, '' );
5439 re
= '^\\s*' + s
.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
5443 re
= new RegExp( re
, 'i' );
5444 return function ( item
) {
5445 var l
= item
.getLabel();
5446 if ( typeof l
!== 'string' ) {
5447 l
= item
.$label
.text();
5449 if ( l
.normalize
) {
5452 return re
.test( l
);
5457 * Bind key press listener.
5461 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
5462 this.getElementWindow().addEventListener( 'keypress', this.onKeyPressHandler
, true );
5466 * Unbind key down listener.
5468 * If you override this, be sure to call this.clearKeyPressBuffer() from your
5473 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
5474 this.getElementWindow().removeEventListener( 'keypress', this.onKeyPressHandler
, true );
5475 this.clearKeyPressBuffer();
5479 * Visibility change handler
5482 * @param {boolean} visible
5484 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
5486 this.clearKeyPressBuffer();
5491 * Get the closest item to a jQuery.Event.
5494 * @param {jQuery.Event} e
5495 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
5497 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
5498 return $( e
.target
).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
5502 * Get selected item.
5504 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
5506 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
5509 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5510 if ( this.items
[ i
].isSelected() ) {
5511 return this.items
[ i
];
5518 * Get highlighted item.
5520 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
5522 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
5525 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5526 if ( this.items
[ i
].isHighlighted() ) {
5527 return this.items
[ i
];
5534 * Toggle pressed state.
5536 * Press is a state that occurs when a user mouses down on an item, but
5537 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
5538 * until the user releases the mouse.
5540 * @param {boolean} pressed An option is being pressed
5542 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
5543 if ( pressed
=== undefined ) {
5544 pressed
= !this.pressed
;
5546 if ( pressed
!== this.pressed
) {
5548 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
5549 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
5550 this.pressed
= pressed
;
5555 * Highlight an option. If the `item` param is omitted, no options will be highlighted
5556 * and any existing highlight will be removed. The highlight is mutually exclusive.
5558 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
5562 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
5563 var i
, len
, highlighted
,
5566 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5567 highlighted
= this.items
[ i
] === item
;
5568 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
5569 this.items
[ i
].setHighlighted( highlighted
);
5574 this.emit( 'highlight', item
);
5581 * Fetch an item by its label.
5583 * @param {string} label Label of the item to select.
5584 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
5585 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
5587 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
5589 len
= this.items
.length
,
5590 filter
= this.getItemMatcher( label
, true );
5592 for ( i
= 0; i
< len
; i
++ ) {
5593 item
= this.items
[ i
];
5594 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
5601 filter
= this.getItemMatcher( label
, false );
5602 for ( i
= 0; i
< len
; i
++ ) {
5603 item
= this.items
[ i
];
5604 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
5620 * Programmatically select an option by its label. If the item does not exist,
5621 * all options will be deselected.
5623 * @param {string} [label] Label of the item to select.
5624 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
5628 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
5629 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
5630 if ( label
=== undefined || !itemFromLabel
) {
5631 return this.selectItem();
5633 return this.selectItem( itemFromLabel
);
5637 * Programmatically select an option by its data. If the `data` parameter is omitted,
5638 * or if the item does not exist, all options will be deselected.
5640 * @param {Object|string} [data] Value of the item to select, omit to deselect all
5644 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
5645 var itemFromData
= this.getItemFromData( data
);
5646 if ( data
=== undefined || !itemFromData
) {
5647 return this.selectItem();
5649 return this.selectItem( itemFromData
);
5653 * Programmatically select an option by its reference. If the `item` parameter is omitted,
5654 * all options will be deselected.
5656 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
5660 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
5661 var i
, len
, selected
,
5664 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5665 selected
= this.items
[ i
] === item
;
5666 if ( this.items
[ i
].isSelected() !== selected
) {
5667 this.items
[ i
].setSelected( selected
);
5672 this.emit( 'select', item
);
5681 * Press is a state that occurs when a user mouses down on an item, but has not
5682 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
5683 * releases the mouse.
5685 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
5689 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
5690 var i
, len
, pressed
,
5693 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5694 pressed
= this.items
[ i
] === item
;
5695 if ( this.items
[ i
].isPressed() !== pressed
) {
5696 this.items
[ i
].setPressed( pressed
);
5701 this.emit( 'press', item
);
5710 * Note that ‘choose’ should never be modified programmatically. A user can choose
5711 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
5712 * use the #selectItem method.
5714 * This method is identical to #selectItem, but may vary in subclasses that take additional action
5715 * when users choose an item with the keyboard or mouse.
5717 * @param {OO.ui.OptionWidget} item Item to choose
5721 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
5723 this.selectItem( item
);
5724 this.emit( 'choose', item
);
5731 * Get an option by its position relative to the specified item (or to the start of the option array,
5732 * if item is `null`). The direction in which to search through the option array is specified with a
5733 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
5734 * `null` if there are no options in the array.
5736 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
5737 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
5738 * @param {Function} [filter] Only consider items for which this function returns
5739 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
5740 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
5742 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
, filter
) {
5743 var currentIndex
, nextIndex
, i
,
5744 increase
= direction
> 0 ? 1 : -1,
5745 len
= this.items
.length
;
5747 if ( item
instanceof OO
.ui
.OptionWidget
) {
5748 currentIndex
= this.items
.indexOf( item
);
5749 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
5751 // If no item is selected and moving forward, start at the beginning.
5752 // If moving backward, start at the end.
5753 nextIndex
= direction
> 0 ? 0 : len
- 1;
5756 for ( i
= 0; i
< len
; i
++ ) {
5757 item
= this.items
[ nextIndex
];
5759 item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() &&
5760 ( !filter
|| filter( item
) )
5764 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
5770 * Get the next selectable item or `null` if there are no selectable items.
5771 * Disabled options and menu-section markers and breaks are not selectable.
5773 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
5775 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
5776 return this.getRelativeSelectableItem( null, 1 );
5780 * Add an array of options to the select. Optionally, an index number can be used to
5781 * specify an insertion point.
5783 * @param {OO.ui.OptionWidget[]} items Items to add
5784 * @param {number} [index] Index to insert items after
5788 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
5790 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
5792 // Always provide an index, even if it was omitted
5793 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
5799 * Remove the specified array of options from the select. Options will be detached
5800 * from the DOM, not removed, so they can be reused later. To remove all options from
5801 * the select, you may wish to use the #clearItems method instead.
5803 * @param {OO.ui.OptionWidget[]} items Items to remove
5807 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
5810 // Deselect items being removed
5811 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
5813 if ( item
.isSelected() ) {
5814 this.selectItem( null );
5819 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
5821 this.emit( 'remove', items
);
5827 * Clear all options from the select. Options will be detached from the DOM, not removed,
5828 * so that they can be reused later. To remove a subset of options from the select, use
5829 * the #removeItems method.
5834 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
5835 var items
= this.items
.slice();
5838 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
5841 this.selectItem( null );
5843 this.emit( 'remove', items
);
5849 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
5850 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
5851 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
5852 * options. For more information about options and selects, please see the
5853 * [OOjs UI documentation on MediaWiki][1].
5856 * // Decorated options in a select widget
5857 * var select = new OO.ui.SelectWidget( {
5859 * new OO.ui.DecoratedOptionWidget( {
5861 * label: 'Option with icon',
5864 * new OO.ui.DecoratedOptionWidget( {
5866 * label: 'Option with indicator',
5871 * $( 'body' ).append( select.$element );
5873 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5876 * @extends OO.ui.OptionWidget
5877 * @mixins OO.ui.mixin.IconElement
5878 * @mixins OO.ui.mixin.IndicatorElement
5881 * @param {Object} [config] Configuration options
5883 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
5884 // Parent constructor
5885 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
5887 // Mixin constructors
5888 OO
.ui
.mixin
.IconElement
.call( this, config
);
5889 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
5893 .addClass( 'oo-ui-decoratedOptionWidget' )
5894 .prepend( this.$icon
)
5895 .append( this.$indicator
);
5900 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
5901 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
5902 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
5905 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
5906 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
5907 * the [OOjs UI documentation on MediaWiki] [1] for more information.
5909 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
5912 * @extends OO.ui.DecoratedOptionWidget
5915 * @param {Object} [config] Configuration options
5917 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
5918 // Configuration initialization
5919 config
= $.extend( { icon
: 'check' }, config
);
5921 // Parent constructor
5922 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
5926 .attr( 'role', 'menuitem' )
5927 .addClass( 'oo-ui-menuOptionWidget' );
5932 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
5934 /* Static Properties */
5936 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
5939 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
5940 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
5943 * var myDropdown = new OO.ui.DropdownWidget( {
5946 * new OO.ui.MenuSectionOptionWidget( {
5949 * new OO.ui.MenuOptionWidget( {
5951 * label: 'Welsh Corgi'
5953 * new OO.ui.MenuOptionWidget( {
5955 * label: 'Standard Poodle'
5957 * new OO.ui.MenuSectionOptionWidget( {
5960 * new OO.ui.MenuOptionWidget( {
5967 * $( 'body' ).append( myDropdown.$element );
5970 * @extends OO.ui.DecoratedOptionWidget
5973 * @param {Object} [config] Configuration options
5975 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
5976 // Parent constructor
5977 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
5980 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' );
5985 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
5987 /* Static Properties */
5989 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
5991 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
5994 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
5995 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
5996 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
5997 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
5998 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
5999 * and customized to be opened, closed, and displayed as needed.
6001 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
6002 * mouse outside the menu.
6004 * Menus also have support for keyboard interaction:
6006 * - Enter/Return key: choose and select a menu option
6007 * - Up-arrow key: highlight the previous menu option
6008 * - Down-arrow key: highlight the next menu option
6009 * - Esc key: hide the menu
6011 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
6012 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6015 * @extends OO.ui.SelectWidget
6016 * @mixins OO.ui.mixin.ClippableElement
6019 * @param {Object} [config] Configuration options
6020 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
6021 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
6022 * and {@link OO.ui.mixin.LookupElement LookupElement}
6023 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
6024 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiselectWidget CapsuleMultiselectWidget}
6025 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
6026 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
6027 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
6028 * that button, unless the button (or its parent widget) is passed in here.
6029 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
6030 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
6032 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
6033 // Configuration initialization
6034 config
= config
|| {};
6036 // Parent constructor
6037 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
6039 // Mixin constructors
6040 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
6043 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
6044 this.filterFromInput
= !!config
.filterFromInput
;
6045 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
6046 this.$widget
= config
.widget
? config
.widget
.$element
: null;
6047 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
6048 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
6052 .addClass( 'oo-ui-menuSelectWidget' )
6053 .attr( 'role', 'menu' );
6055 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
6056 // that reference properties not initialized at that time of parent class construction
6057 // TODO: Find a better way to handle post-constructor setup
6058 this.visible
= false;
6059 this.$element
.addClass( 'oo-ui-element-hidden' );
6064 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
6065 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
6070 * Handles document mouse down events.
6073 * @param {MouseEvent} e Mouse down event
6075 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
6077 !OO
.ui
.contains( this.$element
[ 0 ], e
.target
, true ) &&
6078 ( !this.$widget
|| !OO
.ui
.contains( this.$widget
[ 0 ], e
.target
, true ) )
6080 this.toggle( false );
6087 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
6088 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
6090 if ( !this.isDisabled() && this.isVisible() ) {
6091 switch ( e
.keyCode
) {
6092 case OO
.ui
.Keys
.LEFT
:
6093 case OO
.ui
.Keys
.RIGHT
:
6094 // Do nothing if a text field is associated, arrow keys will be handled natively
6095 if ( !this.$input
) {
6096 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
6099 case OO
.ui
.Keys
.ESCAPE
:
6100 case OO
.ui
.Keys
.TAB
:
6101 if ( currentItem
) {
6102 currentItem
.setHighlighted( false );
6104 this.toggle( false );
6105 // Don't prevent tabbing away, prevent defocusing
6106 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
6108 e
.stopPropagation();
6112 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
6119 * Update menu item visibility after input changes.
6123 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
6125 len
= this.items
.length
,
6126 showAll
= !this.isVisible(),
6127 filter
= showAll
? null : this.getItemMatcher( this.$input
.val() );
6129 for ( i
= 0; i
< len
; i
++ ) {
6130 item
= this.items
[ i
];
6131 if ( item
instanceof OO
.ui
.OptionWidget
) {
6132 item
.toggle( showAll
|| filter( item
) );
6136 // Reevaluate clipping
6143 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
6144 if ( this.$input
) {
6145 this.$input
.on( 'keydown', this.onKeyDownHandler
);
6147 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyDownListener
.call( this );
6154 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
6155 if ( this.$input
) {
6156 this.$input
.off( 'keydown', this.onKeyDownHandler
);
6158 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyDownListener
.call( this );
6165 OO
.ui
.MenuSelectWidget
.prototype.bindKeyPressListener = function () {
6166 if ( this.$input
) {
6167 if ( this.filterFromInput
) {
6168 this.$input
.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
6171 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyPressListener
.call( this );
6178 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyPressListener = function () {
6179 if ( this.$input
) {
6180 if ( this.filterFromInput
) {
6181 this.$input
.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
6182 this.updateItemVisibility();
6185 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyPressListener
.call( this );
6192 * When a user chooses an item, the menu is closed.
6194 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
6195 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
6197 * @param {OO.ui.OptionWidget} item Item to choose
6200 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
6201 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
6202 this.toggle( false );
6209 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
6211 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
6213 // Reevaluate clipping
6222 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
6224 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
6226 // Reevaluate clipping
6235 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
6237 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
6239 // Reevaluate clipping
6248 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
6251 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
6252 change
= visible
!== this.isVisible();
6255 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
6259 this.bindKeyDownListener();
6260 this.bindKeyPressListener();
6262 this.toggleClipping( true );
6264 if ( this.getSelectedItem() ) {
6265 this.getSelectedItem().scrollElementIntoView( { duration
: 0 } );
6269 if ( this.autoHide
) {
6270 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
6273 this.unbindKeyDownListener();
6274 this.unbindKeyPressListener();
6275 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
6276 this.toggleClipping( false );
6284 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
6285 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
6286 * users can interact with it.
6288 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
6289 * OO.ui.DropdownInputWidget instead.
6292 * // Example: A DropdownWidget with a menu that contains three options
6293 * var dropDown = new OO.ui.DropdownWidget( {
6294 * label: 'Dropdown menu: Select a menu option',
6297 * new OO.ui.MenuOptionWidget( {
6301 * new OO.ui.MenuOptionWidget( {
6305 * new OO.ui.MenuOptionWidget( {
6313 * $( 'body' ).append( dropDown.$element );
6315 * dropDown.getMenu().selectItemByData( 'b' );
6317 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
6319 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
6321 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
6324 * @extends OO.ui.Widget
6325 * @mixins OO.ui.mixin.IconElement
6326 * @mixins OO.ui.mixin.IndicatorElement
6327 * @mixins OO.ui.mixin.LabelElement
6328 * @mixins OO.ui.mixin.TitledElement
6329 * @mixins OO.ui.mixin.TabIndexedElement
6332 * @param {Object} [config] Configuration options
6333 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
6334 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
6335 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
6336 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
6338 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
6339 // Configuration initialization
6340 config
= $.extend( { indicator
: 'down' }, config
);
6342 // Parent constructor
6343 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
6345 // Properties (must be set before TabIndexedElement constructor call)
6346 this.$handle
= this.$( '<span>' );
6347 this.$overlay
= config
.$overlay
|| this.$element
;
6349 // Mixin constructors
6350 OO
.ui
.mixin
.IconElement
.call( this, config
);
6351 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
6352 OO
.ui
.mixin
.LabelElement
.call( this, config
);
6353 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
6354 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
6357 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend( {
6359 $container
: this.$element
6364 click
: this.onClick
.bind( this ),
6365 keydown
: this.onKeyDown
.bind( this ),
6366 // Hack? Handle type-to-search when menu is not expanded and not handling its own events
6367 keypress
: this.menu
.onKeyPressHandler
,
6368 blur
: this.menu
.clearKeyPressBuffer
.bind( this.menu
)
6370 this.menu
.connect( this, { select
: 'onMenuSelect' } );
6374 .addClass( 'oo-ui-dropdownWidget-handle' )
6375 .append( this.$icon
, this.$label
, this.$indicator
);
6377 .addClass( 'oo-ui-dropdownWidget' )
6378 .append( this.$handle
);
6379 this.$overlay
.append( this.menu
.$element
);
6384 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
6385 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
6386 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
6387 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
6388 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
6389 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
6396 * @return {OO.ui.MenuSelectWidget} Menu of widget
6398 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
6403 * Handles menu select events.
6406 * @param {OO.ui.MenuOptionWidget} item Selected menu item
6408 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
6412 this.setLabel( null );
6416 selectedLabel
= item
.getLabel();
6418 // If the label is a DOM element, clone it, because setLabel will append() it
6419 if ( selectedLabel
instanceof jQuery
) {
6420 selectedLabel
= selectedLabel
.clone();
6423 this.setLabel( selectedLabel
);
6427 * Handle mouse click events.
6430 * @param {jQuery.Event} e Mouse click event
6432 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
6433 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
6440 * Handle key down events.
6443 * @param {jQuery.Event} e Key down event
6445 OO
.ui
.DropdownWidget
.prototype.onKeyDown = function ( e
) {
6447 !this.isDisabled() &&
6449 e
.which
=== OO
.ui
.Keys
.ENTER
||
6451 !this.menu
.isVisible() &&
6453 e
.which
=== OO
.ui
.Keys
.SPACE
||
6454 e
.which
=== OO
.ui
.Keys
.UP
||
6455 e
.which
=== OO
.ui
.Keys
.DOWN
6466 * RadioOptionWidget is an option widget that looks like a radio button.
6467 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
6468 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6470 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
6473 * @extends OO.ui.OptionWidget
6476 * @param {Object} [config] Configuration options
6478 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
6479 // Configuration initialization
6480 config
= config
|| {};
6482 // Properties (must be done before parent constructor which calls #setDisabled)
6483 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
6485 // Parent constructor
6486 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
6489 // Remove implicit role, we're handling it ourselves
6490 this.radio
.$input
.attr( 'role', 'presentation' );
6492 .addClass( 'oo-ui-radioOptionWidget' )
6493 .attr( 'role', 'radio' )
6494 .attr( 'aria-checked', 'false' )
6495 .removeAttr( 'aria-selected' )
6496 .prepend( this.radio
.$element
);
6501 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
6503 /* Static Properties */
6505 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
6507 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
6509 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
6511 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
6518 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
6519 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
6521 this.radio
.setSelected( state
);
6523 .attr( 'aria-checked', state
.toString() )
6524 .removeAttr( 'aria-selected' );
6532 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
6533 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
6535 this.radio
.setDisabled( this.isDisabled() );
6541 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
6542 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
6543 * an interface for adding, removing and selecting options.
6544 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
6546 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
6547 * OO.ui.RadioSelectInputWidget instead.
6550 * // A RadioSelectWidget with RadioOptions.
6551 * var option1 = new OO.ui.RadioOptionWidget( {
6553 * label: 'Selected radio option'
6556 * var option2 = new OO.ui.RadioOptionWidget( {
6558 * label: 'Unselected radio option'
6561 * var radioSelect=new OO.ui.RadioSelectWidget( {
6562 * items: [ option1, option2 ]
6565 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
6566 * radioSelect.selectItem( option1 );
6568 * $( 'body' ).append( radioSelect.$element );
6570 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6574 * @extends OO.ui.SelectWidget
6575 * @mixins OO.ui.mixin.TabIndexedElement
6578 * @param {Object} [config] Configuration options
6580 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
6581 // Parent constructor
6582 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
6584 // Mixin constructors
6585 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
6589 focus
: this.bindKeyDownListener
.bind( this ),
6590 blur
: this.unbindKeyDownListener
.bind( this )
6595 .addClass( 'oo-ui-radioSelectWidget' )
6596 .attr( 'role', 'radiogroup' );
6601 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
6602 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
6605 * MultioptionWidgets are special elements that can be selected and configured with data. The
6606 * data is often unique for each option, but it does not have to be. MultioptionWidgets are used
6607 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
6608 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
6610 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Multioptions
6613 * @extends OO.ui.Widget
6614 * @mixins OO.ui.mixin.ItemWidget
6615 * @mixins OO.ui.mixin.LabelElement
6618 * @param {Object} [config] Configuration options
6619 * @cfg {boolean} [selected=false] Whether the option is initially selected
6621 OO
.ui
.MultioptionWidget
= function OoUiMultioptionWidget( config
) {
6622 // Configuration initialization
6623 config
= config
|| {};
6625 // Parent constructor
6626 OO
.ui
.MultioptionWidget
.parent
.call( this, config
);
6628 // Mixin constructors
6629 OO
.ui
.mixin
.ItemWidget
.call( this );
6630 OO
.ui
.mixin
.LabelElement
.call( this, config
);
6633 this.selected
= null;
6637 .addClass( 'oo-ui-multioptionWidget' )
6638 .append( this.$label
);
6639 this.setSelected( config
.selected
);
6644 OO
.inheritClass( OO
.ui
.MultioptionWidget
, OO
.ui
.Widget
);
6645 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.ItemWidget
);
6646 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.LabelElement
);
6653 * A change event is emitted when the selected state of the option changes.
6655 * @param {boolean} selected Whether the option is now selected
6661 * Check if the option is selected.
6663 * @return {boolean} Item is selected
6665 OO
.ui
.MultioptionWidget
.prototype.isSelected = function () {
6666 return this.selected
;
6670 * Set the option’s selected state. In general, all modifications to the selection
6671 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
6672 * method instead of this method.
6674 * @param {boolean} [state=false] Select option
6677 OO
.ui
.MultioptionWidget
.prototype.setSelected = function ( state
) {
6679 if ( this.selected
!== state
) {
6680 this.selected
= state
;
6681 this.emit( 'change', state
);
6682 this.$element
.toggleClass( 'oo-ui-multioptionWidget-selected', state
);
6688 * MultiselectWidget allows selecting multiple options from a list.
6690 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
6692 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
6696 * @extends OO.ui.Widget
6697 * @mixins OO.ui.mixin.GroupWidget
6700 * @param {Object} [config] Configuration options
6701 * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
6703 OO
.ui
.MultiselectWidget
= function OoUiMultiselectWidget( config
) {
6704 // Parent constructor
6705 OO
.ui
.MultiselectWidget
.parent
.call( this, config
);
6707 // Configuration initialization
6708 config
= config
|| {};
6710 // Mixin constructors
6711 OO
.ui
.mixin
.GroupWidget
.call( this, config
);
6714 this.aggregate( { change
: 'select' } );
6715 // This is mostly for compatibility with CapsuleMultiselectWidget... normally, 'change' is emitted
6716 // by GroupElement only when items are added/removed
6717 this.connect( this, { select
: [ 'emit', 'change' ] } );
6720 if ( config
.items
) {
6721 this.addItems( config
.items
);
6723 this.$group
.addClass( 'oo-ui-multiselectWidget-group' );
6724 this.$element
.addClass( 'oo-ui-multiselectWidget' )
6725 .append( this.$group
);
6730 OO
.inheritClass( OO
.ui
.MultiselectWidget
, OO
.ui
.Widget
);
6731 OO
.mixinClass( OO
.ui
.MultiselectWidget
, OO
.ui
.mixin
.GroupWidget
);
6738 * A change event is emitted when the set of items changes, or an item is selected or deselected.
6744 * A select event is emitted when an item is selected or deselected.
6750 * Get options that are selected.
6752 * @return {OO.ui.MultioptionWidget[]} Selected options
6754 OO
.ui
.MultiselectWidget
.prototype.getSelectedItems = function () {
6755 return this.items
.filter( function ( item
) {
6756 return item
.isSelected();
6761 * Get the data of options that are selected.
6763 * @return {Object[]|string[]} Values of selected options
6765 OO
.ui
.MultiselectWidget
.prototype.getSelectedItemsData = function () {
6766 return this.getSelectedItems().map( function ( item
) {
6772 * Select options by reference. Options not mentioned in the `items` array will be deselected.
6774 * @param {OO.ui.MultioptionWidget[]} items Items to select
6777 OO
.ui
.MultiselectWidget
.prototype.selectItems = function ( items
) {
6778 this.items
.forEach( function ( item
) {
6779 var selected
= items
.indexOf( item
) !== -1;
6780 item
.setSelected( selected
);
6786 * Select items by their data. Options not mentioned in the `datas` array will be deselected.
6788 * @param {Object[]|string[]} datas Values of items to select
6791 OO
.ui
.MultiselectWidget
.prototype.selectItemsByData = function ( datas
) {
6794 items
= datas
.map( function ( data
) {
6795 return widget
.getItemFromData( data
);
6797 this.selectItems( items
);
6802 * CheckboxMultioptionWidget is an option widget that looks like a checkbox.
6803 * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
6804 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6806 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
6809 * @extends OO.ui.MultioptionWidget
6812 * @param {Object} [config] Configuration options
6814 OO
.ui
.CheckboxMultioptionWidget
= function OoUiCheckboxMultioptionWidget( config
) {
6815 // Configuration initialization
6816 config
= config
|| {};
6818 // Properties (must be done before parent constructor which calls #setDisabled)
6819 this.checkbox
= new OO
.ui
.CheckboxInputWidget();
6821 // Parent constructor
6822 OO
.ui
.CheckboxMultioptionWidget
.parent
.call( this, config
);
6825 this.checkbox
.on( 'change', this.onCheckboxChange
.bind( this ) );
6826 this.$element
.on( 'keydown', this.onKeyDown
.bind( this ) );
6830 .addClass( 'oo-ui-checkboxMultioptionWidget' )
6831 .prepend( this.checkbox
.$element
);
6836 OO
.inheritClass( OO
.ui
.CheckboxMultioptionWidget
, OO
.ui
.MultioptionWidget
);
6838 /* Static Properties */
6840 OO
.ui
.CheckboxMultioptionWidget
.static.tagName
= 'label';
6845 * Handle checkbox selected state change.
6849 OO
.ui
.CheckboxMultioptionWidget
.prototype.onCheckboxChange = function () {
6850 this.setSelected( this.checkbox
.isSelected() );
6856 OO
.ui
.CheckboxMultioptionWidget
.prototype.setSelected = function ( state
) {
6857 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setSelected
.call( this, state
);
6858 this.checkbox
.setSelected( state
);
6865 OO
.ui
.CheckboxMultioptionWidget
.prototype.setDisabled = function ( disabled
) {
6866 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
6867 this.checkbox
.setDisabled( this.isDisabled() );
6874 OO
.ui
.CheckboxMultioptionWidget
.prototype.focus = function () {
6875 this.checkbox
.focus();
6879 * Handle key down events.
6882 * @param {jQuery.Event} e
6884 OO
.ui
.CheckboxMultioptionWidget
.prototype.onKeyDown = function ( e
) {
6886 element
= this.getElementGroup(),
6889 if ( e
.keyCode
=== OO
.ui
.Keys
.LEFT
|| e
.keyCode
=== OO
.ui
.Keys
.UP
) {
6890 nextItem
= element
.getRelativeFocusableItem( this, -1 );
6891 } else if ( e
.keyCode
=== OO
.ui
.Keys
.RIGHT
|| e
.keyCode
=== OO
.ui
.Keys
.DOWN
) {
6892 nextItem
= element
.getRelativeFocusableItem( this, 1 );
6902 * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
6903 * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
6904 * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
6905 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
6907 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
6908 * OO.ui.CheckboxMultiselectInputWidget instead.
6911 * // A CheckboxMultiselectWidget with CheckboxMultioptions.
6912 * var option1 = new OO.ui.CheckboxMultioptionWidget( {
6915 * label: 'Selected checkbox'
6918 * var option2 = new OO.ui.CheckboxMultioptionWidget( {
6920 * label: 'Unselected checkbox'
6923 * var multiselect=new OO.ui.CheckboxMultiselectWidget( {
6924 * items: [ option1, option2 ]
6927 * $( 'body' ).append( multiselect.$element );
6929 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6932 * @extends OO.ui.MultiselectWidget
6935 * @param {Object} [config] Configuration options
6937 OO
.ui
.CheckboxMultiselectWidget
= function OoUiCheckboxMultiselectWidget( config
) {
6938 // Parent constructor
6939 OO
.ui
.CheckboxMultiselectWidget
.parent
.call( this, config
);
6942 this.$lastClicked
= null;
6945 this.$group
.on( 'click', this.onClick
.bind( this ) );
6949 .addClass( 'oo-ui-checkboxMultiselectWidget' );
6954 OO
.inheritClass( OO
.ui
.CheckboxMultiselectWidget
, OO
.ui
.MultiselectWidget
);
6959 * Get an option by its position relative to the specified item (or to the start of the option array,
6960 * if item is `null`). The direction in which to search through the option array is specified with a
6961 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
6962 * `null` if there are no options in the array.
6964 * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
6965 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
6966 * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items in the select
6968 OO
.ui
.CheckboxMultiselectWidget
.prototype.getRelativeFocusableItem = function ( item
, direction
) {
6969 var currentIndex
, nextIndex
, i
,
6970 increase
= direction
> 0 ? 1 : -1,
6971 len
= this.items
.length
;
6974 currentIndex
= this.items
.indexOf( item
);
6975 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
6977 // If no item is selected and moving forward, start at the beginning.
6978 // If moving backward, start at the end.
6979 nextIndex
= direction
> 0 ? 0 : len
- 1;
6982 for ( i
= 0; i
< len
; i
++ ) {
6983 item
= this.items
[ nextIndex
];
6984 if ( item
&& !item
.isDisabled() ) {
6987 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
6993 * Handle click events on checkboxes.
6995 * @param {jQuery.Event} e
6997 OO
.ui
.CheckboxMultiselectWidget
.prototype.onClick = function ( e
) {
6998 var $options
, lastClickedIndex
, nowClickedIndex
, i
, direction
, wasSelected
, items
,
6999 $lastClicked
= this.$lastClicked
,
7000 $nowClicked
= $( e
.target
).closest( '.oo-ui-checkboxMultioptionWidget' )
7001 .not( '.oo-ui-widget-disabled' );
7003 // Allow selecting multiple options at once by Shift-clicking them
7004 if ( $lastClicked
&& $nowClicked
.length
&& e
.shiftKey
) {
7005 $options
= this.$group
.find( '.oo-ui-checkboxMultioptionWidget' );
7006 lastClickedIndex
= $options
.index( $lastClicked
);
7007 nowClickedIndex
= $options
.index( $nowClicked
);
7008 // If it's the same item, either the user is being silly, or it's a fake event generated by the
7009 // browser. In either case we don't need custom handling.
7010 if ( nowClickedIndex
!== lastClickedIndex
) {
7012 wasSelected
= items
[ nowClickedIndex
].isSelected();
7013 direction
= nowClickedIndex
> lastClickedIndex
? 1 : -1;
7015 // This depends on the DOM order of the items and the order of the .items array being the same.
7016 for ( i
= lastClickedIndex
; i
!== nowClickedIndex
; i
+= direction
) {
7017 if ( !items
[ i
].isDisabled() ) {
7018 items
[ i
].setSelected( !wasSelected
);
7021 // For the now-clicked element, use immediate timeout to allow the browser to do its own
7022 // handling first, then set our value. The order in which events happen is different for
7023 // clicks on the <input> and on the <label> and there are additional fake clicks fired for
7024 // non-click actions that change the checkboxes.
7026 setTimeout( function () {
7027 if ( !items
[ nowClickedIndex
].isDisabled() ) {
7028 items
[ nowClickedIndex
].setSelected( !wasSelected
);
7034 if ( $nowClicked
.length
) {
7035 this.$lastClicked
= $nowClicked
;
7040 * Element that will stick under a specified container, even when it is inserted elsewhere in the
7041 * document (for example, in a OO.ui.Window's $overlay).
7043 * The elements's position is automatically calculated and maintained when window is resized or the
7044 * page is scrolled. If you reposition the container manually, you have to call #position to make
7045 * sure the element is still placed correctly.
7047 * As positioning is only possible when both the element and the container are attached to the DOM
7048 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
7049 * the #toggle method to display a floating popup, for example.
7055 * @param {Object} [config] Configuration options
7056 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
7057 * @cfg {jQuery} [$floatableContainer] Node to position below
7059 OO
.ui
.mixin
.FloatableElement
= function OoUiMixinFloatableElement( config
) {
7060 // Configuration initialization
7061 config
= config
|| {};
7064 this.$floatable
= null;
7065 this.$floatableContainer
= null;
7066 this.$floatableWindow
= null;
7067 this.$floatableClosestScrollable
= null;
7068 this.onFloatableScrollHandler
= this.position
.bind( this );
7069 this.onFloatableWindowResizeHandler
= this.position
.bind( this );
7072 this.setFloatableContainer( config
.$floatableContainer
);
7073 this.setFloatableElement( config
.$floatable
|| this.$element
);
7079 * Set floatable element.
7081 * If an element is already set, it will be cleaned up before setting up the new element.
7083 * @param {jQuery} $floatable Element to make floatable
7085 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableElement = function ( $floatable
) {
7086 if ( this.$floatable
) {
7087 this.$floatable
.removeClass( 'oo-ui-floatableElement-floatable' );
7088 this.$floatable
.css( { left
: '', top
: '' } );
7091 this.$floatable
= $floatable
.addClass( 'oo-ui-floatableElement-floatable' );
7096 * Set floatable container.
7098 * The element will be always positioned under the specified container.
7100 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
7102 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableContainer = function ( $floatableContainer
) {
7103 this.$floatableContainer
= $floatableContainer
;
7104 if ( this.$floatable
) {
7110 * Toggle positioning.
7112 * Do not turn positioning on until after the element is attached to the DOM and visible.
7114 * @param {boolean} [positioning] Enable positioning, omit to toggle
7117 OO
.ui
.mixin
.FloatableElement
.prototype.togglePositioning = function ( positioning
) {
7118 var closestScrollableOfContainer
, closestScrollableOfFloatable
;
7120 positioning
= positioning
=== undefined ? !this.positioning
: !!positioning
;
7122 if ( this.positioning
!== positioning
) {
7123 this.positioning
= positioning
;
7125 closestScrollableOfContainer
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatableContainer
[ 0 ] );
7126 closestScrollableOfFloatable
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatable
[ 0 ] );
7127 this.needsCustomPosition
= closestScrollableOfContainer
!== closestScrollableOfFloatable
;
7128 // If the scrollable is the root, we have to listen to scroll events
7129 // on the window because of browser inconsistencies.
7130 if ( $( closestScrollableOfContainer
).is( 'html, body' ) ) {
7131 closestScrollableOfContainer
= OO
.ui
.Element
.static.getWindow( closestScrollableOfContainer
);
7134 if ( positioning
) {
7135 this.$floatableWindow
= $( this.getElementWindow() );
7136 this.$floatableWindow
.on( 'resize', this.onFloatableWindowResizeHandler
);
7138 this.$floatableClosestScrollable
= $( closestScrollableOfContainer
);
7139 this.$floatableClosestScrollable
.on( 'scroll', this.onFloatableScrollHandler
);
7141 // Initial position after visible
7144 if ( this.$floatableWindow
) {
7145 this.$floatableWindow
.off( 'resize', this.onFloatableWindowResizeHandler
);
7146 this.$floatableWindow
= null;
7149 if ( this.$floatableClosestScrollable
) {
7150 this.$floatableClosestScrollable
.off( 'scroll', this.onFloatableScrollHandler
);
7151 this.$floatableClosestScrollable
= null;
7154 this.$floatable
.css( { left
: '', top
: '' } );
7162 * Check whether the bottom edge of the given element is within the viewport of the given container.
7165 * @param {jQuery} $element
7166 * @param {jQuery} $container
7169 OO
.ui
.mixin
.FloatableElement
.prototype.isElementInViewport = function ( $element
, $container
) {
7170 var elemRect
, contRect
,
7171 topEdgeInBounds
= false,
7172 leftEdgeInBounds
= false,
7173 bottomEdgeInBounds
= false,
7174 rightEdgeInBounds
= false;
7176 elemRect
= $element
[ 0 ].getBoundingClientRect();
7177 if ( $container
[ 0 ] === window
) {
7181 right
: document
.documentElement
.clientWidth
,
7182 bottom
: document
.documentElement
.clientHeight
7185 contRect
= $container
[ 0 ].getBoundingClientRect();
7188 if ( elemRect
.top
>= contRect
.top
&& elemRect
.top
<= contRect
.bottom
) {
7189 topEdgeInBounds
= true;
7191 if ( elemRect
.left
>= contRect
.left
&& elemRect
.left
<= contRect
.right
) {
7192 leftEdgeInBounds
= true;
7194 if ( elemRect
.bottom
>= contRect
.top
&& elemRect
.bottom
<= contRect
.bottom
) {
7195 bottomEdgeInBounds
= true;
7197 if ( elemRect
.right
>= contRect
.left
&& elemRect
.right
<= contRect
.right
) {
7198 rightEdgeInBounds
= true;
7201 // We only care that any part of the bottom edge is visible
7202 return bottomEdgeInBounds
&& ( leftEdgeInBounds
|| rightEdgeInBounds
);
7206 * Position the floatable below its container.
7208 * This should only be done when both of them are attached to the DOM and visible.
7212 OO
.ui
.mixin
.FloatableElement
.prototype.position = function () {
7215 if ( !this.positioning
) {
7219 if ( !this.isElementInViewport( this.$floatableContainer
, this.$floatableClosestScrollable
) ) {
7220 this.$floatable
.addClass( 'oo-ui-floatableElement-hidden' );
7223 this.$floatable
.removeClass( 'oo-ui-floatableElement-hidden' );
7226 if ( !this.needsCustomPosition
) {
7230 pos
= OO
.ui
.Element
.static.getRelativePosition( this.$floatableContainer
, this.$floatable
.offsetParent() );
7232 // Position under container
7233 pos
.top
+= this.$floatableContainer
.height();
7234 this.$floatable
.css( pos
);
7236 // We updated the position, so re-evaluate the clipping state.
7237 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
7238 // will not notice the need to update itself.)
7239 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
7240 // it not listen to the right events in the right places?
7249 * FloatingMenuSelectWidget is a menu that will stick under a specified
7250 * container, even when it is inserted elsewhere in the document (for example,
7251 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
7252 * menu from being clipped too aggresively.
7254 * The menu's position is automatically calculated and maintained when the menu
7255 * is toggled or the window is resized.
7257 * See OO.ui.ComboBoxInputWidget for an example of a widget that uses this class.
7260 * @extends OO.ui.MenuSelectWidget
7261 * @mixins OO.ui.mixin.FloatableElement
7264 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
7265 * Deprecated, omit this parameter and specify `$container` instead.
7266 * @param {Object} [config] Configuration options
7267 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
7269 OO
.ui
.FloatingMenuSelectWidget
= function OoUiFloatingMenuSelectWidget( inputWidget
, config
) {
7270 // Allow 'inputWidget' parameter and config for backwards compatibility
7271 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
7272 config
= inputWidget
;
7273 inputWidget
= config
.inputWidget
;
7276 // Configuration initialization
7277 config
= config
|| {};
7279 // Parent constructor
7280 OO
.ui
.FloatingMenuSelectWidget
.parent
.call( this, config
);
7282 // Properties (must be set before mixin constructors)
7283 this.inputWidget
= inputWidget
; // For backwards compatibility
7284 this.$container
= config
.$container
|| this.inputWidget
.$element
;
7286 // Mixins constructors
7287 OO
.ui
.mixin
.FloatableElement
.call( this, $.extend( {}, config
, { $floatableContainer
: this.$container
} ) );
7290 this.$element
.addClass( 'oo-ui-floatingMenuSelectWidget' );
7291 // For backwards compatibility
7292 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
7297 OO
.inheritClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
7298 OO
.mixinClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.mixin
.FloatableElement
);
7300 // For backwards compatibility
7301 OO
.ui
.TextInputMenuSelectWidget
= OO
.ui
.FloatingMenuSelectWidget
;
7308 OO
.ui
.FloatingMenuSelectWidget
.prototype.toggle = function ( visible
) {
7310 visible
= visible
=== undefined ? !this.isVisible() : !!visible
;
7311 change
= visible
!== this.isVisible();
7313 if ( change
&& visible
) {
7314 // Make sure the width is set before the parent method runs.
7315 this.setIdealSize( this.$container
.width() );
7319 // This will call this.clip(), which is nonsensical since we're not positioned yet...
7320 OO
.ui
.FloatingMenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
7323 this.togglePositioning( this.isVisible() );
7330 * Progress bars visually display the status of an operation, such as a download,
7331 * and can be either determinate or indeterminate:
7333 * - **determinate** process bars show the percent of an operation that is complete.
7335 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
7336 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
7337 * not use percentages.
7339 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
7342 * // Examples of determinate and indeterminate progress bars.
7343 * var progressBar1 = new OO.ui.ProgressBarWidget( {
7346 * var progressBar2 = new OO.ui.ProgressBarWidget();
7348 * // Create a FieldsetLayout to layout progress bars
7349 * var fieldset = new OO.ui.FieldsetLayout;
7350 * fieldset.addItems( [
7351 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
7352 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
7354 * $( 'body' ).append( fieldset.$element );
7357 * @extends OO.ui.Widget
7360 * @param {Object} [config] Configuration options
7361 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
7362 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
7363 * By default, the progress bar is indeterminate.
7365 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
7366 // Configuration initialization
7367 config
= config
|| {};
7369 // Parent constructor
7370 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
7373 this.$bar
= $( '<div>' );
7374 this.progress
= null;
7377 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
7378 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
7381 role
: 'progressbar',
7383 'aria-valuemax': 100
7385 .addClass( 'oo-ui-progressBarWidget' )
7386 .append( this.$bar
);
7391 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
7393 /* Static Properties */
7395 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
7400 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
7402 * @return {number|boolean} Progress percent
7404 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
7405 return this.progress
;
7409 * Set the percent of the process completed or `false` for an indeterminate process.
7411 * @param {number|boolean} progress Progress percent or `false` for indeterminate
7413 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
7414 this.progress
= progress
;
7416 if ( progress
!== false ) {
7417 this.$bar
.css( 'width', this.progress
+ '%' );
7418 this.$element
.attr( 'aria-valuenow', this.progress
);
7420 this.$bar
.css( 'width', '' );
7421 this.$element
.removeAttr( 'aria-valuenow' );
7423 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress
=== false );
7427 * InputWidget is the base class for all input widgets, which
7428 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
7429 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
7430 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
7432 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7436 * @extends OO.ui.Widget
7437 * @mixins OO.ui.mixin.FlaggedElement
7438 * @mixins OO.ui.mixin.TabIndexedElement
7439 * @mixins OO.ui.mixin.TitledElement
7440 * @mixins OO.ui.mixin.AccessKeyedElement
7443 * @param {Object} [config] Configuration options
7444 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
7445 * @cfg {string} [value=''] The value of the input.
7446 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
7447 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
7448 * before it is accepted.
7450 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
7451 // Configuration initialization
7452 config
= config
|| {};
7454 // Parent constructor
7455 OO
.ui
.InputWidget
.parent
.call( this, config
);
7458 // See #reusePreInfuseDOM about config.$input
7459 this.$input
= config
.$input
|| this.getInputElement( config
);
7461 this.inputFilter
= config
.inputFilter
;
7463 // Mixin constructors
7464 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
7465 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
7466 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
7467 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$input
} ) );
7470 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
7474 .addClass( 'oo-ui-inputWidget-input' )
7475 .attr( 'name', config
.name
)
7476 .prop( 'disabled', this.isDisabled() );
7478 .addClass( 'oo-ui-inputWidget' )
7479 .append( this.$input
);
7480 this.setValue( config
.value
);
7482 this.setDir( config
.dir
);
7488 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
7489 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
7490 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
7491 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
7492 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
7494 /* Static Properties */
7496 OO
.ui
.InputWidget
.static.supportsSimpleLabel
= true;
7498 /* Static Methods */
7503 OO
.ui
.InputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
7504 config
= OO
.ui
.InputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
7505 // Reusing $input lets browsers preserve inputted values across page reloads (T114134)
7506 config
.$input
= $( node
).find( '.oo-ui-inputWidget-input' );
7513 OO
.ui
.InputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
7514 var state
= OO
.ui
.InputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
7515 if ( config
.$input
&& config
.$input
.length
) {
7516 state
.value
= config
.$input
.val();
7517 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
7518 state
.focus
= config
.$input
.is( ':focus' );
7528 * A change event is emitted when the value of the input changes.
7530 * @param {string} value
7536 * Get input element.
7538 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
7539 * different circumstances. The element must have a `value` property (like form elements).
7542 * @param {Object} config Configuration options
7543 * @return {jQuery} Input element
7545 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
7546 return $( '<input>' );
7550 * Handle potentially value-changing events.
7553 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
7555 OO
.ui
.InputWidget
.prototype.onEdit = function () {
7557 if ( !this.isDisabled() ) {
7558 // Allow the stack to clear so the value will be updated
7559 setTimeout( function () {
7560 widget
.setValue( widget
.$input
.val() );
7566 * Get the value of the input.
7568 * @return {string} Input value
7570 OO
.ui
.InputWidget
.prototype.getValue = function () {
7571 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
7572 // it, and we won't know unless they're kind enough to trigger a 'change' event.
7573 var value
= this.$input
.val();
7574 if ( this.value
!== value
) {
7575 this.setValue( value
);
7581 * Set the directionality of the input, either RTL (right-to-left) or LTR (left-to-right).
7583 * @deprecated since v0.13.1; use #setDir directly
7584 * @param {boolean} isRTL Directionality is right-to-left
7587 OO
.ui
.InputWidget
.prototype.setRTL = function ( isRTL
) {
7588 this.setDir( isRTL
? 'rtl' : 'ltr' );
7593 * Set the directionality of the input.
7595 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
7598 OO
.ui
.InputWidget
.prototype.setDir = function ( dir
) {
7599 this.$input
.prop( 'dir', dir
);
7604 * Set the value of the input.
7606 * @param {string} value New value
7610 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
7611 value
= this.cleanUpValue( value
);
7612 // Update the DOM if it has changed. Note that with cleanUpValue, it
7613 // is possible for the DOM value to change without this.value changing.
7614 if ( this.$input
.val() !== value
) {
7615 this.$input
.val( value
);
7617 if ( this.value
!== value
) {
7619 this.emit( 'change', this.value
);
7625 * Clean up incoming value.
7627 * Ensures value is a string, and converts undefined and null to empty string.
7630 * @param {string} value Original value
7631 * @return {string} Cleaned up value
7633 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
7634 if ( value
=== undefined || value
=== null ) {
7636 } else if ( this.inputFilter
) {
7637 return this.inputFilter( String( value
) );
7639 return String( value
);
7644 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
7645 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
7648 OO
.ui
.InputWidget
.prototype.simulateLabelClick = function () {
7649 if ( !this.isDisabled() ) {
7650 if ( this.$input
.is( ':checkbox, :radio' ) ) {
7651 this.$input
.click();
7653 if ( this.$input
.is( ':input' ) ) {
7654 this.$input
[ 0 ].focus();
7662 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
7663 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
7664 if ( this.$input
) {
7665 this.$input
.prop( 'disabled', this.isDisabled() );
7675 OO
.ui
.InputWidget
.prototype.focus = function () {
7676 this.$input
[ 0 ].focus();
7685 OO
.ui
.InputWidget
.prototype.blur = function () {
7686 this.$input
[ 0 ].blur();
7693 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
7694 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
7695 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
7696 this.setValue( state
.value
);
7698 if ( state
.focus
) {
7704 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
7705 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
7706 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
7707 * HTML `<button>` (the default) or an HTML `<input>` tags. See the
7708 * [OOjs UI documentation on MediaWiki] [1] for more information.
7711 * // A ButtonInputWidget rendered as an HTML button, the default.
7712 * var button = new OO.ui.ButtonInputWidget( {
7713 * label: 'Input button',
7717 * $( 'body' ).append( button.$element );
7719 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
7722 * @extends OO.ui.InputWidget
7723 * @mixins OO.ui.mixin.ButtonElement
7724 * @mixins OO.ui.mixin.IconElement
7725 * @mixins OO.ui.mixin.IndicatorElement
7726 * @mixins OO.ui.mixin.LabelElement
7727 * @mixins OO.ui.mixin.TitledElement
7730 * @param {Object} [config] Configuration options
7731 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
7732 * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
7733 * Widgets configured to be an `<input>` do not support {@link #icon icons} and {@link #indicator indicators},
7734 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
7735 * be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
7737 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
7738 // Configuration initialization
7739 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
7741 // See InputWidget#reusePreInfuseDOM about config.$input
7742 if ( config
.$input
) {
7743 config
.$input
.empty();
7746 // Properties (must be set before parent constructor, which calls #setValue)
7747 this.useInputTag
= config
.useInputTag
;
7749 // Parent constructor
7750 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
7752 // Mixin constructors
7753 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
7754 OO
.ui
.mixin
.IconElement
.call( this, config
);
7755 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
7756 OO
.ui
.mixin
.LabelElement
.call( this, config
);
7757 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
7760 if ( !config
.useInputTag
) {
7761 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
7763 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
7768 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
7769 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
7770 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
7771 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
7772 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
7773 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
7775 /* Static Properties */
7778 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
7779 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
7781 OO
.ui
.ButtonInputWidget
.static.supportsSimpleLabel
= false;
7789 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
7791 type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ? config
.type
: 'button';
7792 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
7798 * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
7800 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
7801 * text, or `null` for no label
7804 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
7805 if ( typeof label
=== 'function' ) {
7806 label
= OO
.ui
.resolveMsg( label
);
7809 if ( this.useInputTag
) {
7810 // Discard non-plaintext labels
7811 if ( typeof label
!== 'string' ) {
7815 this.$input
.val( label
);
7818 return OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
7822 * Set the value of the input.
7824 * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
7825 * they do not support {@link #value values}.
7827 * @param {string} value New value
7830 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
7831 if ( !this.useInputTag
) {
7832 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
7838 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
7839 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
7840 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
7841 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
7843 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
7846 * // An example of selected, unselected, and disabled checkbox inputs
7847 * var checkbox1=new OO.ui.CheckboxInputWidget( {
7851 * var checkbox2=new OO.ui.CheckboxInputWidget( {
7854 * var checkbox3=new OO.ui.CheckboxInputWidget( {
7858 * // Create a fieldset layout with fields for each checkbox.
7859 * var fieldset = new OO.ui.FieldsetLayout( {
7860 * label: 'Checkboxes'
7862 * fieldset.addItems( [
7863 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
7864 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
7865 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
7867 * $( 'body' ).append( fieldset.$element );
7869 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7872 * @extends OO.ui.InputWidget
7875 * @param {Object} [config] Configuration options
7876 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
7878 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
7879 // Configuration initialization
7880 config
= config
|| {};
7882 // Parent constructor
7883 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
7887 .addClass( 'oo-ui-checkboxInputWidget' )
7888 // Required for pretty styling in MediaWiki theme
7889 .append( $( '<span>' ) );
7890 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
7895 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
7897 /* Static Methods */
7902 OO
.ui
.CheckboxInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
7903 var state
= OO
.ui
.CheckboxInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
7904 state
.checked
= config
.$input
.prop( 'checked' );
7914 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
7915 return $( '<input>' ).attr( 'type', 'checkbox' );
7921 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
7923 if ( !this.isDisabled() ) {
7924 // Allow the stack to clear so the value will be updated
7925 setTimeout( function () {
7926 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
7932 * Set selection state of this checkbox.
7934 * @param {boolean} state `true` for selected
7937 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
7939 if ( this.selected
!== state
) {
7940 this.selected
= state
;
7941 this.$input
.prop( 'checked', this.selected
);
7942 this.emit( 'change', this.selected
);
7948 * Check if this checkbox is selected.
7950 * @return {boolean} Checkbox is selected
7952 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
7953 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
7954 // it, and we won't know unless they're kind enough to trigger a 'change' event.
7955 var selected
= this.$input
.prop( 'checked' );
7956 if ( this.selected
!== selected
) {
7957 this.setSelected( selected
);
7959 return this.selected
;
7965 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
7966 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
7967 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
7968 this.setSelected( state
.checked
);
7973 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
7974 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
7975 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
7976 * more information about input widgets.
7978 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
7979 * are no options. If no `value` configuration option is provided, the first option is selected.
7980 * If you need a state representing no value (no option being selected), use a DropdownWidget.
7982 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
7985 * // Example: A DropdownInputWidget with three options
7986 * var dropdownInput = new OO.ui.DropdownInputWidget( {
7988 * { data: 'a', label: 'First' },
7989 * { data: 'b', label: 'Second'},
7990 * { data: 'c', label: 'Third' }
7993 * $( 'body' ).append( dropdownInput.$element );
7995 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7998 * @extends OO.ui.InputWidget
7999 * @mixins OO.ui.mixin.TitledElement
8002 * @param {Object} [config] Configuration options
8003 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
8004 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
8006 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
8007 // Configuration initialization
8008 config
= config
|| {};
8010 // See InputWidget#reusePreInfuseDOM about config.$input
8011 if ( config
.$input
) {
8012 config
.$input
.addClass( 'oo-ui-element-hidden' );
8015 // Properties (must be done before parent constructor which calls #setDisabled)
8016 this.dropdownWidget
= new OO
.ui
.DropdownWidget( config
.dropdown
);
8018 // Parent constructor
8019 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
8021 // Mixin constructors
8022 OO
.ui
.mixin
.TitledElement
.call( this, config
);
8025 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
8028 this.setOptions( config
.options
|| [] );
8030 .addClass( 'oo-ui-dropdownInputWidget' )
8031 .append( this.dropdownWidget
.$element
);
8036 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
8037 OO
.mixinClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.mixin
.TitledElement
);
8045 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
8046 return $( '<input>' ).attr( 'type', 'hidden' );
8050 * Handles menu select events.
8053 * @param {OO.ui.MenuOptionWidget} item Selected menu item
8055 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
8056 this.setValue( item
.getData() );
8062 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
8063 value
= this.cleanUpValue( value
);
8064 this.dropdownWidget
.getMenu().selectItemByData( value
);
8065 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
8072 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
8073 this.dropdownWidget
.setDisabled( state
);
8074 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
8079 * Set the options available for this input.
8081 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
8084 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
8086 value
= this.getValue(),
8089 // Rebuild the dropdown menu
8090 this.dropdownWidget
.getMenu()
8092 .addItems( options
.map( function ( opt
) {
8093 var optValue
= widget
.cleanUpValue( opt
.data
);
8094 return new OO
.ui
.MenuOptionWidget( {
8096 label
: opt
.label
!== undefined ? opt
.label
: optValue
8100 // Restore the previous value, or reset to something sensible
8101 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
8102 // Previous value is still available, ensure consistency with the dropdown
8103 this.setValue( value
);
8105 // No longer valid, reset
8106 if ( options
.length
) {
8107 this.setValue( options
[ 0 ].data
);
8117 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
8118 this.dropdownWidget
.getMenu().toggle( true );
8125 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
8126 this.dropdownWidget
.getMenu().toggle( false );
8131 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
8132 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
8133 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
8134 * please see the [OOjs UI documentation on MediaWiki][1].
8136 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
8139 * // An example of selected, unselected, and disabled radio inputs
8140 * var radio1 = new OO.ui.RadioInputWidget( {
8144 * var radio2 = new OO.ui.RadioInputWidget( {
8147 * var radio3 = new OO.ui.RadioInputWidget( {
8151 * // Create a fieldset layout with fields for each radio button.
8152 * var fieldset = new OO.ui.FieldsetLayout( {
8153 * label: 'Radio inputs'
8155 * fieldset.addItems( [
8156 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
8157 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
8158 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
8160 * $( 'body' ).append( fieldset.$element );
8162 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8165 * @extends OO.ui.InputWidget
8168 * @param {Object} [config] Configuration options
8169 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
8171 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
8172 // Configuration initialization
8173 config
= config
|| {};
8175 // Parent constructor
8176 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
8180 .addClass( 'oo-ui-radioInputWidget' )
8181 // Required for pretty styling in MediaWiki theme
8182 .append( $( '<span>' ) );
8183 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
8188 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
8190 /* Static Methods */
8195 OO
.ui
.RadioInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8196 var state
= OO
.ui
.RadioInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8197 state
.checked
= config
.$input
.prop( 'checked' );
8207 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
8208 return $( '<input>' ).attr( 'type', 'radio' );
8214 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
8215 // RadioInputWidget doesn't track its state.
8219 * Set selection state of this radio button.
8221 * @param {boolean} state `true` for selected
8224 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
8225 // RadioInputWidget doesn't track its state.
8226 this.$input
.prop( 'checked', state
);
8231 * Check if this radio button is selected.
8233 * @return {boolean} Radio is selected
8235 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
8236 return this.$input
.prop( 'checked' );
8242 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
8243 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
8244 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
8245 this.setSelected( state
.checked
);
8250 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
8251 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
8252 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
8253 * more information about input widgets.
8255 * This and OO.ui.DropdownInputWidget support the same configuration options.
8258 * // Example: A RadioSelectInputWidget with three options
8259 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
8261 * { data: 'a', label: 'First' },
8262 * { data: 'b', label: 'Second'},
8263 * { data: 'c', label: 'Third' }
8266 * $( 'body' ).append( radioSelectInput.$element );
8268 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8271 * @extends OO.ui.InputWidget
8274 * @param {Object} [config] Configuration options
8275 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
8277 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
8278 // Configuration initialization
8279 config
= config
|| {};
8281 // Properties (must be done before parent constructor which calls #setDisabled)
8282 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
8284 // Parent constructor
8285 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
8288 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
8291 this.setOptions( config
.options
|| [] );
8293 .addClass( 'oo-ui-radioSelectInputWidget' )
8294 .append( this.radioSelectWidget
.$element
);
8299 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
8301 /* Static Properties */
8303 OO
.ui
.RadioSelectInputWidget
.static.supportsSimpleLabel
= false;
8305 /* Static Methods */
8310 OO
.ui
.RadioSelectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8311 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8312 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
8319 OO
.ui
.RadioSelectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
8320 config
= OO
.ui
.RadioSelectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
8321 // Cannot reuse the `<input type=radio>` set
8322 delete config
.$input
;
8332 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
8333 return $( '<input>' ).attr( 'type', 'hidden' );
8337 * Handles menu select events.
8340 * @param {OO.ui.RadioOptionWidget} item Selected menu item
8342 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
8343 this.setValue( item
.getData() );
8349 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
8350 value
= this.cleanUpValue( value
);
8351 this.radioSelectWidget
.selectItemByData( value
);
8352 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
8359 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
8360 this.radioSelectWidget
.setDisabled( state
);
8361 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
8366 * Set the options available for this input.
8368 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
8371 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
8373 value
= this.getValue(),
8376 // Rebuild the radioSelect menu
8377 this.radioSelectWidget
8379 .addItems( options
.map( function ( opt
) {
8380 var optValue
= widget
.cleanUpValue( opt
.data
);
8381 return new OO
.ui
.RadioOptionWidget( {
8383 label
: opt
.label
!== undefined ? opt
.label
: optValue
8387 // Restore the previous value, or reset to something sensible
8388 if ( this.radioSelectWidget
.getItemFromData( value
) ) {
8389 // Previous value is still available, ensure consistency with the radioSelect
8390 this.setValue( value
);
8392 // No longer valid, reset
8393 if ( options
.length
) {
8394 this.setValue( options
[ 0 ].data
);
8402 * CheckboxMultiselectInputWidget is a
8403 * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
8404 * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
8405 * HTML `<input type=checkbox>` tags. Please see the [OOjs UI documentation on MediaWiki][1] for
8406 * more information about input widgets.
8409 * // Example: A CheckboxMultiselectInputWidget with three options
8410 * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
8412 * { data: 'a', label: 'First' },
8413 * { data: 'b', label: 'Second'},
8414 * { data: 'c', label: 'Third' }
8417 * $( 'body' ).append( multiselectInput.$element );
8419 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8422 * @extends OO.ui.InputWidget
8425 * @param {Object} [config] Configuration options
8426 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
8428 OO
.ui
.CheckboxMultiselectInputWidget
= function OoUiCheckboxMultiselectInputWidget( config
) {
8429 // Configuration initialization
8430 config
= config
|| {};
8432 // Properties (must be done before parent constructor which calls #setDisabled)
8433 this.checkboxMultiselectWidget
= new OO
.ui
.CheckboxMultiselectWidget();
8435 // Parent constructor
8436 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.call( this, config
);
8439 this.inputName
= config
.name
;
8443 .addClass( 'oo-ui-checkboxMultiselectInputWidget' )
8444 .append( this.checkboxMultiselectWidget
.$element
);
8445 // We don't use this.$input, but rather the CheckboxInputWidgets inside each option
8446 this.$input
.detach();
8447 this.setOptions( config
.options
|| [] );
8448 // Have to repeat this from parent, as we need options to be set up for this to make sense
8449 this.setValue( config
.value
);
8454 OO
.inheritClass( OO
.ui
.CheckboxMultiselectInputWidget
, OO
.ui
.InputWidget
);
8456 /* Static Properties */
8458 OO
.ui
.CheckboxMultiselectInputWidget
.static.supportsSimpleLabel
= false;
8460 /* Static Methods */
8465 OO
.ui
.CheckboxMultiselectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8466 var state
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8467 state
.value
= $( node
).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
8468 .toArray().map( function ( el
) { return el
.value
; } );
8475 OO
.ui
.CheckboxMultiselectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
8476 config
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
8477 // Cannot reuse the `<input type=checkbox>` set
8478 delete config
.$input
;
8488 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getInputElement = function () {
8490 return $( '<div>' );
8496 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getValue = function () {
8497 var value
= this.$element
.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
8498 .toArray().map( function ( el
) { return el
.value
; } );
8499 if ( this.value
!== value
) {
8500 this.setValue( value
);
8508 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setValue = function ( value
) {
8509 value
= this.cleanUpValue( value
);
8510 this.checkboxMultiselectWidget
.selectItemsByData( value
);
8511 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setValue
.call( this, value
);
8516 * Clean up incoming value.
8518 * @param {string[]} value Original value
8519 * @return {string[]} Cleaned up value
8521 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.cleanUpValue = function ( value
) {
8524 if ( !Array
.isArray( value
) ) {
8527 for ( i
= 0; i
< value
.length
; i
++ ) {
8529 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( this, value
[ i
] );
8530 // Remove options that we don't have here
8531 if ( !this.checkboxMultiselectWidget
.getItemFromData( singleValue
) ) {
8534 cleanValue
.push( singleValue
);
8542 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setDisabled = function ( state
) {
8543 this.checkboxMultiselectWidget
.setDisabled( state
);
8544 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
8549 * Set the options available for this input.
8551 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
8554 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setOptions = function ( options
) {
8557 // Rebuild the checkboxMultiselectWidget menu
8558 this.checkboxMultiselectWidget
8560 .addItems( options
.map( function ( opt
) {
8563 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( widget
, opt
.data
);
8564 item
= new OO
.ui
.CheckboxMultioptionWidget( {
8566 label
: opt
.label
!== undefined ? opt
.label
: optValue
8568 // Set the 'name' and 'value' for form submission
8569 item
.checkbox
.$input
.attr( 'name', widget
.inputName
);
8570 item
.checkbox
.setValue( optValue
);
8574 // Re-set the value, checking the checkboxes as needed.
8575 // This will also get rid of any stale options that we just removed.
8576 this.setValue( this.getValue() );
8582 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
8583 * size of the field as well as its presentation. In addition, these widgets can be configured
8584 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
8585 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
8586 * which modifies incoming values rather than validating them.
8587 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
8589 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
8592 * // Example of a text input widget
8593 * var textInput = new OO.ui.TextInputWidget( {
8594 * value: 'Text input'
8596 * $( 'body' ).append( textInput.$element );
8598 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8601 * @extends OO.ui.InputWidget
8602 * @mixins OO.ui.mixin.IconElement
8603 * @mixins OO.ui.mixin.IndicatorElement
8604 * @mixins OO.ui.mixin.PendingElement
8605 * @mixins OO.ui.mixin.LabelElement
8608 * @param {Object} [config] Configuration options
8609 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
8610 * 'email', 'url', 'date' or 'number'. Ignored if `multiline` is true.
8612 * Some values of `type` result in additional behaviors:
8614 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
8615 * empties the text field
8616 * @cfg {string} [placeholder] Placeholder text
8617 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
8618 * instruct the browser to focus this widget.
8619 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
8620 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
8621 * @cfg {boolean} [multiline=false] Allow multiple lines of text
8622 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
8623 * specifies minimum number of rows to display.
8624 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
8625 * Use the #maxRows config to specify a maximum number of displayed rows.
8626 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
8627 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
8628 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
8629 * the value or placeholder text: `'before'` or `'after'`
8630 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
8631 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
8632 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
8633 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
8634 * (the value must contain only numbers); when RegExp, a regular expression that must match the
8635 * value for it to be considered valid; when Function, a function receiving the value as parameter
8636 * that must return true, or promise resolving to true, for it to be considered valid.
8638 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
8639 // Configuration initialization
8640 config
= $.extend( {
8642 labelPosition
: 'after'
8644 if ( config
.type
=== 'search' ) {
8645 if ( config
.icon
=== undefined ) {
8646 config
.icon
= 'search';
8648 // indicator: 'clear' is set dynamically later, depending on value
8650 if ( config
.required
) {
8651 if ( config
.indicator
=== undefined ) {
8652 config
.indicator
= 'required';
8656 // Parent constructor
8657 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
8659 // Mixin constructors
8660 OO
.ui
.mixin
.IconElement
.call( this, config
);
8661 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
8662 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
8663 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8666 this.type
= this.getSaneType( config
);
8667 this.readOnly
= false;
8668 this.multiline
= !!config
.multiline
;
8669 this.autosize
= !!config
.autosize
;
8670 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
8671 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
8672 this.validate
= null;
8673 this.styleHeight
= null;
8674 this.scrollWidth
= null;
8676 // Clone for resizing
8677 if ( this.autosize
) {
8678 this.$clone
= this.$input
8680 .insertAfter( this.$input
)
8681 .attr( 'aria-hidden', 'true' )
8682 .addClass( 'oo-ui-element-hidden' );
8685 this.setValidation( config
.validate
);
8686 this.setLabelPosition( config
.labelPosition
);
8690 keypress
: this.onKeyPress
.bind( this ),
8691 blur
: this.onBlur
.bind( this ),
8692 focus
: this.onFocus
.bind( this )
8695 focus
: this.onElementAttach
.bind( this )
8697 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
8698 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
8699 this.on( 'labelChange', this.updatePosition
.bind( this ) );
8700 this.connect( this, {
8702 disable
: 'onDisable'
8704 this.on( 'change', OO
.ui
.debounce( this.onDebouncedChange
.bind( this ), 250 ) );
8708 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
8709 .append( this.$icon
, this.$indicator
);
8710 this.setReadOnly( !!config
.readOnly
);
8711 this.updateSearchIndicator();
8712 if ( config
.placeholder
!== undefined ) {
8713 this.$input
.attr( 'placeholder', config
.placeholder
);
8715 if ( config
.maxLength
!== undefined ) {
8716 this.$input
.attr( 'maxlength', config
.maxLength
);
8718 if ( config
.autofocus
) {
8719 this.$input
.attr( 'autofocus', 'autofocus' );
8721 if ( config
.required
) {
8722 this.$input
.attr( 'required', 'required' );
8723 this.$input
.attr( 'aria-required', 'true' );
8725 if ( config
.autocomplete
=== false ) {
8726 this.$input
.attr( 'autocomplete', 'off' );
8727 // Turning off autocompletion also disables "form caching" when the user navigates to a
8728 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
8730 beforeunload: function () {
8731 this.$input
.removeAttr( 'autocomplete' );
8733 pageshow: function () {
8734 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
8735 // whole page... it shouldn't hurt, though.
8736 this.$input
.attr( 'autocomplete', 'off' );
8740 if ( this.multiline
&& config
.rows
) {
8741 this.$input
.attr( 'rows', config
.rows
);
8743 if ( this.label
|| config
.autosize
) {
8744 this.installParentChangeDetector();
8750 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
8751 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
8752 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
8753 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
8754 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
8756 /* Static Properties */
8758 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
8763 /* Static Methods */
8768 OO
.ui
.TextInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8769 var state
= OO
.ui
.TextInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8770 if ( config
.multiline
) {
8771 state
.scrollTop
= config
.$input
.scrollTop();
8779 * An `enter` event is emitted when the user presses 'enter' inside the text box.
8781 * Not emitted if the input is multiline.
8787 * A `resize` event is emitted when autosize is set and the widget resizes
8795 * Handle icon mouse down events.
8798 * @param {jQuery.Event} e Mouse down event
8800 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
8801 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
8802 this.$input
[ 0 ].focus();
8808 * Handle indicator mouse down events.
8811 * @param {jQuery.Event} e Mouse down event
8813 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
8814 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
8815 if ( this.type
=== 'search' ) {
8816 // Clear the text field
8817 this.setValue( '' );
8819 this.$input
[ 0 ].focus();
8825 * Handle key press events.
8828 * @param {jQuery.Event} e Key press event
8829 * @fires enter If enter key is pressed and input is not multiline
8831 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
8832 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
8833 this.emit( 'enter', e
);
8838 * Handle blur events.
8841 * @param {jQuery.Event} e Blur event
8843 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
8844 this.setValidityFlag();
8848 * Handle focus events.
8851 * @param {jQuery.Event} e Focus event
8853 OO
.ui
.TextInputWidget
.prototype.onFocus = function () {
8854 this.setValidityFlag( true );
8858 * Handle element attach events.
8861 * @param {jQuery.Event} e Element attach event
8863 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
8864 // Any previously calculated size is now probably invalid if we reattached elsewhere
8865 this.valCache
= null;
8867 this.positionLabel();
8871 * Handle change events.
8873 * @param {string} value
8876 OO
.ui
.TextInputWidget
.prototype.onChange = function () {
8877 this.updateSearchIndicator();
8882 * Handle debounced change events.
8884 * @param {string} value
8887 OO
.ui
.TextInputWidget
.prototype.onDebouncedChange = function () {
8888 this.setValidityFlag();
8892 * Handle disable events.
8894 * @param {boolean} disabled Element is disabled
8897 OO
.ui
.TextInputWidget
.prototype.onDisable = function () {
8898 this.updateSearchIndicator();
8902 * Check if the input is {@link #readOnly read-only}.
8906 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
8907 return this.readOnly
;
8911 * Set the {@link #readOnly read-only} state of the input.
8913 * @param {boolean} state Make input read-only
8916 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
8917 this.readOnly
= !!state
;
8918 this.$input
.prop( 'readOnly', this.readOnly
);
8919 this.updateSearchIndicator();
8924 * Support function for making #onElementAttach work across browsers.
8926 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
8927 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
8929 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
8930 * first time that the element gets attached to the documented.
8932 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
8933 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
8934 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
8937 if ( MutationObserver
) {
8938 // The new way. If only it wasn't so ugly.
8940 if ( this.$element
.closest( 'html' ).length
) {
8941 // Widget is attached already, do nothing. This breaks the functionality of this function when
8942 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
8943 // would require observation of the whole document, which would hurt performance of other,
8944 // more important code.
8948 // Find topmost node in the tree
8949 topmostNode
= this.$element
[ 0 ];
8950 while ( topmostNode
.parentNode
) {
8951 topmostNode
= topmostNode
.parentNode
;
8954 // We have no way to detect the $element being attached somewhere without observing the entire
8955 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
8956 // parent node of $element, and instead detect when $element is removed from it (and thus
8957 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
8958 // doesn't get attached, we end up back here and create the parent.
8960 mutationObserver
= new MutationObserver( function ( mutations
) {
8961 var i
, j
, removedNodes
;
8962 for ( i
= 0; i
< mutations
.length
; i
++ ) {
8963 removedNodes
= mutations
[ i
].removedNodes
;
8964 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
8965 if ( removedNodes
[ j
] === topmostNode
) {
8966 setTimeout( onRemove
, 0 );
8973 onRemove = function () {
8974 // If the node was attached somewhere else, report it
8975 if ( widget
.$element
.closest( 'html' ).length
) {
8976 widget
.onElementAttach();
8978 mutationObserver
.disconnect();
8979 widget
.installParentChangeDetector();
8982 // Create a fake parent and observe it
8983 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
8984 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
8986 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
8987 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
8988 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
8993 * Automatically adjust the size of the text input.
8995 * This only affects #multiline inputs that are {@link #autosize autosized}.
9000 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
9001 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
,
9002 idealHeight
, newHeight
, scrollWidth
, property
;
9004 if ( this.multiline
&& this.$input
.val() !== this.valCache
) {
9005 if ( this.autosize
) {
9007 .val( this.$input
.val() )
9008 .attr( 'rows', this.minRows
)
9009 // Set inline height property to 0 to measure scroll height
9010 .css( 'height', 0 );
9012 this.$clone
.removeClass( 'oo-ui-element-hidden' );
9014 this.valCache
= this.$input
.val();
9016 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
9018 // Remove inline height property to measure natural heights
9019 this.$clone
.css( 'height', '' );
9020 innerHeight
= this.$clone
.innerHeight();
9021 outerHeight
= this.$clone
.outerHeight();
9023 // Measure max rows height
9025 .attr( 'rows', this.maxRows
)
9026 .css( 'height', 'auto' )
9028 maxInnerHeight
= this.$clone
.innerHeight();
9030 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
9031 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
9032 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
9033 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
9035 this.$clone
.addClass( 'oo-ui-element-hidden' );
9037 // Only apply inline height when expansion beyond natural height is needed
9038 // Use the difference between the inner and outer height as a buffer
9039 newHeight
= idealHeight
> innerHeight
? idealHeight
+ ( outerHeight
- innerHeight
) : '';
9040 if ( newHeight
!== this.styleHeight
) {
9041 this.$input
.css( 'height', newHeight
);
9042 this.styleHeight
= newHeight
;
9043 this.emit( 'resize' );
9046 scrollWidth
= this.$input
[ 0 ].offsetWidth
- this.$input
[ 0 ].clientWidth
;
9047 if ( scrollWidth
!== this.scrollWidth
) {
9048 property
= this.$element
.css( 'direction' ) === 'rtl' ? 'left' : 'right';
9050 this.$label
.css( { right
: '', left
: '' } );
9051 this.$indicator
.css( { right
: '', left
: '' } );
9053 if ( scrollWidth
) {
9054 this.$indicator
.css( property
, scrollWidth
);
9055 if ( this.labelPosition
=== 'after' ) {
9056 this.$label
.css( property
, scrollWidth
);
9060 this.scrollWidth
= scrollWidth
;
9061 this.positionLabel();
9071 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
9072 if ( config
.multiline
) {
9073 return $( '<textarea>' );
9074 } else if ( this.getSaneType( config
) === 'number' ) {
9075 return $( '<input>' )
9076 .attr( 'step', 'any' )
9077 .attr( 'type', 'number' );
9079 return $( '<input>' ).attr( 'type', this.getSaneType( config
) );
9084 * Get sanitized value for 'type' for given config.
9086 * @param {Object} config Configuration options
9087 * @return {string|null}
9090 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
9091 var allowedTypes
= [
9100 return allowedTypes
.indexOf( config
.type
) !== -1 ? config
.type
: 'text';
9104 * Check if the input supports multiple lines.
9108 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
9109 return !!this.multiline
;
9113 * Check if the input automatically adjusts its size.
9117 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
9118 return !!this.autosize
;
9122 * Focus the input and select a specified range within the text.
9124 * @param {number} from Select from offset
9125 * @param {number} [to] Select to offset, defaults to from
9128 OO
.ui
.TextInputWidget
.prototype.selectRange = function ( from, to
) {
9129 var isBackwards
, start
, end
,
9130 input
= this.$input
[ 0 ];
9134 isBackwards
= to
< from;
9135 start
= isBackwards
? to
: from;
9136 end
= isBackwards
? from : to
;
9141 input
.setSelectionRange( start
, end
, isBackwards
? 'backward' : 'forward' );
9143 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
9144 // Rather than expensively check if the input is attached every time, just check
9145 // if it was the cause of an error being thrown. If not, rethrow the error.
9146 if ( this.getElementDocument().body
.contains( input
) ) {
9154 * Get an object describing the current selection range in a directional manner
9156 * @return {Object} Object containing 'from' and 'to' offsets
9158 OO
.ui
.TextInputWidget
.prototype.getRange = function () {
9159 var input
= this.$input
[ 0 ],
9160 start
= input
.selectionStart
,
9161 end
= input
.selectionEnd
,
9162 isBackwards
= input
.selectionDirection
=== 'backward';
9165 from: isBackwards
? end
: start
,
9166 to
: isBackwards
? start
: end
9171 * Get the length of the text input value.
9173 * This could differ from the length of #getValue if the
9174 * value gets filtered
9176 * @return {number} Input length
9178 OO
.ui
.TextInputWidget
.prototype.getInputLength = function () {
9179 return this.$input
[ 0 ].value
.length
;
9183 * Focus the input and select the entire text.
9187 OO
.ui
.TextInputWidget
.prototype.select = function () {
9188 return this.selectRange( 0, this.getInputLength() );
9192 * Focus the input and move the cursor to the start.
9196 OO
.ui
.TextInputWidget
.prototype.moveCursorToStart = function () {
9197 return this.selectRange( 0 );
9201 * Focus the input and move the cursor to the end.
9205 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
9206 return this.selectRange( this.getInputLength() );
9210 * Insert new content into the input.
9212 * @param {string} content Content to be inserted
9215 OO
.ui
.TextInputWidget
.prototype.insertContent = function ( content
) {
9217 range
= this.getRange(),
9218 value
= this.getValue();
9220 start
= Math
.min( range
.from, range
.to
);
9221 end
= Math
.max( range
.from, range
.to
);
9223 this.setValue( value
.slice( 0, start
) + content
+ value
.slice( end
) );
9224 this.selectRange( start
+ content
.length
);
9229 * Insert new content either side of a selection.
9231 * @param {string} pre Content to be inserted before the selection
9232 * @param {string} post Content to be inserted after the selection
9235 OO
.ui
.TextInputWidget
.prototype.encapsulateContent = function ( pre
, post
) {
9237 range
= this.getRange(),
9238 offset
= pre
.length
;
9240 start
= Math
.min( range
.from, range
.to
);
9241 end
= Math
.max( range
.from, range
.to
);
9243 this.selectRange( start
).insertContent( pre
);
9244 this.selectRange( offset
+ end
).insertContent( post
);
9246 this.selectRange( offset
+ start
, offset
+ end
);
9251 * Set the validation pattern.
9253 * The validation pattern is either a regular expression, a function, or the symbolic name of a
9254 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
9255 * value must contain only numbers).
9257 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
9258 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
9260 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
9261 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
9262 this.validate
= validate
;
9264 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
9269 * Sets the 'invalid' flag appropriately.
9271 * @param {boolean} [isValid] Optionally override validation result
9273 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
9275 setFlag = function ( valid
) {
9277 widget
.$input
.attr( 'aria-invalid', 'true' );
9279 widget
.$input
.removeAttr( 'aria-invalid' );
9281 widget
.setFlags( { invalid
: !valid
} );
9284 if ( isValid
!== undefined ) {
9287 this.getValidity().then( function () {
9296 * Check if a value is valid.
9298 * This method returns a promise that resolves with a boolean `true` if the current value is
9299 * considered valid according to the supplied {@link #validate validation pattern}.
9301 * @deprecated since v0.12.3
9302 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
9304 OO
.ui
.TextInputWidget
.prototype.isValid = function () {
9307 if ( this.validate
instanceof Function
) {
9308 result
= this.validate( this.getValue() );
9309 if ( result
&& $.isFunction( result
.promise
) ) {
9310 return result
.promise();
9312 return $.Deferred().resolve( !!result
).promise();
9315 return $.Deferred().resolve( !!this.getValue().match( this.validate
) ).promise();
9320 * Get the validity of current value.
9322 * This method returns a promise that resolves if the value is valid and rejects if
9323 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
9325 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
9327 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
9330 function rejectOrResolve( valid
) {
9332 return $.Deferred().resolve().promise();
9334 return $.Deferred().reject().promise();
9338 if ( this.validate
instanceof Function
) {
9339 result
= this.validate( this.getValue() );
9340 if ( result
&& $.isFunction( result
.promise
) ) {
9341 return result
.promise().then( function ( valid
) {
9342 return rejectOrResolve( valid
);
9345 return rejectOrResolve( result
);
9348 return rejectOrResolve( this.getValue().match( this.validate
) );
9353 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
9355 * @param {string} labelPosition Label position, 'before' or 'after'
9358 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
9359 this.labelPosition
= labelPosition
;
9361 // If there is no label and we only change the position, #updatePosition is a no-op,
9362 // but it takes really a lot of work to do nothing.
9363 this.updatePosition();
9369 * Update the position of the inline label.
9371 * This method is called by #setLabelPosition, and can also be called on its own if
9372 * something causes the label to be mispositioned.
9376 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
9377 var after
= this.labelPosition
=== 'after';
9380 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
9381 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
9383 this.valCache
= null;
9384 this.scrollWidth
= null;
9386 this.positionLabel();
9392 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
9393 * already empty or when it's not editable.
9395 OO
.ui
.TextInputWidget
.prototype.updateSearchIndicator = function () {
9396 if ( this.type
=== 'search' ) {
9397 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
9398 this.setIndicator( null );
9400 this.setIndicator( 'clear' );
9406 * Position the label by setting the correct padding on the input.
9411 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
9412 var after
, rtl
, property
;
9415 // Clear old values if present
9417 'padding-right': '',
9422 this.$element
.append( this.$label
);
9424 this.$label
.detach();
9428 after
= this.labelPosition
=== 'after';
9429 rtl
= this.$element
.css( 'direction' ) === 'rtl';
9430 property
= after
=== rtl
? 'padding-left' : 'padding-right';
9432 this.$input
.css( property
, this.$label
.outerWidth( true ) + ( after
? this.scrollWidth
: 0 ) );
9440 OO
.ui
.TextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
9441 OO
.ui
.TextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
9442 if ( state
.scrollTop
!== undefined ) {
9443 this.$input
.scrollTop( state
.scrollTop
);
9448 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
9449 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
9450 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
9452 * - by typing a value in the text input field. If the value exactly matches the value of a menu
9453 * option, that option will appear to be selected.
9454 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
9457 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
9459 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
9462 * // Example: A ComboBoxInputWidget.
9463 * var comboBox = new OO.ui.ComboBoxInputWidget( {
9464 * label: 'ComboBoxInputWidget',
9465 * value: 'Option 1',
9468 * new OO.ui.MenuOptionWidget( {
9470 * label: 'Option One'
9472 * new OO.ui.MenuOptionWidget( {
9474 * label: 'Option Two'
9476 * new OO.ui.MenuOptionWidget( {
9478 * label: 'Option Three'
9480 * new OO.ui.MenuOptionWidget( {
9482 * label: 'Option Four'
9484 * new OO.ui.MenuOptionWidget( {
9486 * label: 'Option Five'
9491 * $( 'body' ).append( comboBox.$element );
9493 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
9496 * @extends OO.ui.TextInputWidget
9499 * @param {Object} [config] Configuration options
9500 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9501 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
9502 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
9503 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
9504 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
9506 OO
.ui
.ComboBoxInputWidget
= function OoUiComboBoxInputWidget( config
) {
9507 // Configuration initialization
9508 config
= $.extend( {
9512 // For backwards-compatibility with ComboBoxWidget config
9513 $.extend( config
, config
.input
);
9515 // Parent constructor
9516 OO
.ui
.ComboBoxInputWidget
.parent
.call( this, config
);
9519 this.$overlay
= config
.$overlay
|| this.$element
;
9520 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
9524 $container
: this.$element
,
9525 disabled
: this.isDisabled()
9529 // For backwards-compatibility with ComboBoxWidget
9533 this.$indicator
.on( {
9534 click
: this.onIndicatorClick
.bind( this ),
9535 keypress
: this.onIndicatorKeyPress
.bind( this )
9537 this.connect( this, {
9538 change
: 'onInputChange',
9539 enter
: 'onInputEnter'
9541 this.menu
.connect( this, {
9542 choose
: 'onMenuChoose',
9543 add
: 'onMenuItemsChange',
9544 remove
: 'onMenuItemsChange'
9550 'aria-autocomplete': 'list'
9552 // Do not override options set via config.menu.items
9553 if ( config
.options
!== undefined ) {
9554 this.setOptions( config
.options
);
9556 // Extra class for backwards-compatibility with ComboBoxWidget
9557 this.$element
.addClass( 'oo-ui-comboBoxInputWidget oo-ui-comboBoxWidget' );
9558 this.$overlay
.append( this.menu
.$element
);
9559 this.onMenuItemsChange();
9564 OO
.inheritClass( OO
.ui
.ComboBoxInputWidget
, OO
.ui
.TextInputWidget
);
9569 * Get the combobox's menu.
9571 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
9573 OO
.ui
.ComboBoxInputWidget
.prototype.getMenu = function () {
9578 * Get the combobox's text input widget.
9580 * @return {OO.ui.TextInputWidget} Text input widget
9582 OO
.ui
.ComboBoxInputWidget
.prototype.getInput = function () {
9587 * Handle input change events.
9590 * @param {string} value New value
9592 OO
.ui
.ComboBoxInputWidget
.prototype.onInputChange = function ( value
) {
9593 var match
= this.menu
.getItemFromData( value
);
9595 this.menu
.selectItem( match
);
9596 if ( this.menu
.getHighlightedItem() ) {
9597 this.menu
.highlightItem( match
);
9600 if ( !this.isDisabled() ) {
9601 this.menu
.toggle( true );
9606 * Handle mouse click events.
9609 * @param {jQuery.Event} e Mouse click event
9611 OO
.ui
.ComboBoxInputWidget
.prototype.onIndicatorClick = function ( e
) {
9612 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
9614 this.$input
[ 0 ].focus();
9620 * Handle key press events.
9623 * @param {jQuery.Event} e Key press event
9625 OO
.ui
.ComboBoxInputWidget
.prototype.onIndicatorKeyPress = function ( e
) {
9626 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
9628 this.$input
[ 0 ].focus();
9634 * Handle input enter events.
9638 OO
.ui
.ComboBoxInputWidget
.prototype.onInputEnter = function () {
9639 if ( !this.isDisabled() ) {
9640 this.menu
.toggle( false );
9645 * Handle menu choose events.
9648 * @param {OO.ui.OptionWidget} item Chosen item
9650 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuChoose = function ( item
) {
9651 this.setValue( item
.getData() );
9655 * Handle menu item change events.
9659 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuItemsChange = function () {
9660 var match
= this.menu
.getItemFromData( this.getValue() );
9661 this.menu
.selectItem( match
);
9662 if ( this.menu
.getHighlightedItem() ) {
9663 this.menu
.highlightItem( match
);
9665 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu
.isEmpty() );
9671 OO
.ui
.ComboBoxInputWidget
.prototype.setDisabled = function ( disabled
) {
9673 OO
.ui
.ComboBoxInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
9676 this.menu
.setDisabled( this.isDisabled() );
9683 * Set the options available for this input.
9685 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9688 OO
.ui
.ComboBoxInputWidget
.prototype.setOptions = function ( options
) {
9691 .addItems( options
.map( function ( opt
) {
9692 return new OO
.ui
.MenuOptionWidget( {
9694 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
9703 * @deprecated since 0.13.2; use OO.ui.ComboBoxInputWidget instead
9705 OO
.ui
.ComboBoxWidget
= OO
.ui
.ComboBoxInputWidget
;
9708 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
9709 * which is a widget that is specified by reference before any optional configuration settings.
9711 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
9713 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9714 * A left-alignment is used for forms with many fields.
9715 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9716 * A right-alignment is used for long but familiar forms which users tab through,
9717 * verifying the current field with a quick glance at the label.
9718 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9719 * that users fill out from top to bottom.
9720 * - **inline**: The label is placed after the field-widget and aligned to the left.
9721 * An inline-alignment is best used with checkboxes or radio buttons.
9723 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
9724 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
9726 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9729 * @extends OO.ui.Layout
9730 * @mixins OO.ui.mixin.LabelElement
9731 * @mixins OO.ui.mixin.TitledElement
9734 * @param {OO.ui.Widget} fieldWidget Field widget
9735 * @param {Object} [config] Configuration options
9736 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
9737 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
9738 * The array may contain strings or OO.ui.HtmlSnippet instances.
9739 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
9740 * The array may contain strings or OO.ui.HtmlSnippet instances.
9741 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
9742 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
9743 * For important messages, you are advised to use `notices`, as they are always shown.
9745 * @throws {Error} An error is thrown if no widget is specified
9747 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
9748 var hasInputWidget
, div
;
9750 // Allow passing positional parameters inside the config object
9751 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
9752 config
= fieldWidget
;
9753 fieldWidget
= config
.fieldWidget
;
9756 // Make sure we have required constructor arguments
9757 if ( fieldWidget
=== undefined ) {
9758 throw new Error( 'Widget not found' );
9761 hasInputWidget
= fieldWidget
.constructor.static.supportsSimpleLabel
;
9763 // Configuration initialization
9764 config
= $.extend( { align
: 'left' }, config
);
9766 // Parent constructor
9767 OO
.ui
.FieldLayout
.parent
.call( this, config
);
9769 // Mixin constructors
9770 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9771 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
9774 this.fieldWidget
= fieldWidget
;
9777 this.$field
= $( '<div>' );
9778 this.$messages
= $( '<ul>' );
9779 this.$body
= $( '<' + ( hasInputWidget
? 'label' : 'div' ) + '>' );
9781 if ( config
.help
) {
9782 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
9783 classes
: [ 'oo-ui-fieldLayout-help' ],
9789 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
9790 div
.html( config
.help
.toString() );
9792 div
.text( config
.help
);
9794 this.popupButtonWidget
.getPopup().$body
.append(
9795 div
.addClass( 'oo-ui-fieldLayout-help-content' )
9797 this.$help
= this.popupButtonWidget
.$element
;
9799 this.$help
= $( [] );
9803 if ( hasInputWidget
) {
9804 this.$label
.on( 'click', this.onLabelClick
.bind( this ) );
9806 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
9810 .addClass( 'oo-ui-fieldLayout' )
9811 .append( this.$help
, this.$body
);
9812 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
9813 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
9815 .addClass( 'oo-ui-fieldLayout-field' )
9816 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget
.isDisabled() )
9817 .append( this.fieldWidget
.$element
);
9819 this.setErrors( config
.errors
|| [] );
9820 this.setNotices( config
.notices
|| [] );
9821 this.setAlignment( config
.align
);
9826 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
9827 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
9828 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
9833 * Handle field disable events.
9836 * @param {boolean} value Field is disabled
9838 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
9839 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
9843 * Handle label mouse click events.
9846 * @param {jQuery.Event} e Mouse click event
9848 OO
.ui
.FieldLayout
.prototype.onLabelClick = function () {
9849 this.fieldWidget
.simulateLabelClick();
9854 * Get the widget contained by the field.
9856 * @return {OO.ui.Widget} Field widget
9858 OO
.ui
.FieldLayout
.prototype.getField = function () {
9859 return this.fieldWidget
;
9864 * @param {string} kind 'error' or 'notice'
9865 * @param {string|OO.ui.HtmlSnippet} text
9868 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
9869 var $listItem
, $icon
, message
;
9870 $listItem
= $( '<li>' );
9871 if ( kind
=== 'error' ) {
9872 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
9873 } else if ( kind
=== 'notice' ) {
9874 $icon
= new OO
.ui
.IconWidget( { icon
: 'info' } ).$element
;
9878 message
= new OO
.ui
.LabelWidget( { label
: text
} );
9880 .append( $icon
, message
.$element
)
9881 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
9886 * Set the field alignment mode.
9889 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
9892 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
9893 if ( value
!== this.align
) {
9894 // Default to 'left'
9895 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
9899 if ( value
=== 'inline' ) {
9900 this.$body
.append( this.$field
, this.$label
);
9902 this.$body
.append( this.$label
, this.$field
);
9904 // Set classes. The following classes can be used here:
9905 // * oo-ui-fieldLayout-align-left
9906 // * oo-ui-fieldLayout-align-right
9907 // * oo-ui-fieldLayout-align-top
9908 // * oo-ui-fieldLayout-align-inline
9910 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
9912 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
9920 * Set the list of error messages.
9922 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
9923 * The array may contain strings or OO.ui.HtmlSnippet instances.
9926 OO
.ui
.FieldLayout
.prototype.setErrors = function ( errors
) {
9927 this.errors
= errors
.slice();
9928 this.updateMessages();
9933 * Set the list of notice messages.
9935 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
9936 * The array may contain strings or OO.ui.HtmlSnippet instances.
9939 OO
.ui
.FieldLayout
.prototype.setNotices = function ( notices
) {
9940 this.notices
= notices
.slice();
9941 this.updateMessages();
9946 * Update the rendering of error and notice messages.
9950 OO
.ui
.FieldLayout
.prototype.updateMessages = function () {
9952 this.$messages
.empty();
9954 if ( this.errors
.length
|| this.notices
.length
) {
9955 this.$body
.after( this.$messages
);
9957 this.$messages
.remove();
9961 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
9962 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
9964 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
9965 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
9970 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
9971 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
9972 * is required and is specified before any optional configuration settings.
9974 * Labels can be aligned in one of four ways:
9976 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9977 * A left-alignment is used for forms with many fields.
9978 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9979 * A right-alignment is used for long but familiar forms which users tab through,
9980 * verifying the current field with a quick glance at the label.
9981 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9982 * that users fill out from top to bottom.
9983 * - **inline**: The label is placed after the field-widget and aligned to the left.
9984 * An inline-alignment is best used with checkboxes or radio buttons.
9986 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
9987 * text is specified.
9990 * // Example of an ActionFieldLayout
9991 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
9992 * new OO.ui.TextInputWidget( {
9993 * placeholder: 'Field widget'
9995 * new OO.ui.ButtonWidget( {
9999 * label: 'An ActionFieldLayout. This label is aligned top',
10001 * help: 'This is help text'
10005 * $( 'body' ).append( actionFieldLayout.$element );
10008 * @extends OO.ui.FieldLayout
10011 * @param {OO.ui.Widget} fieldWidget Field widget
10012 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
10014 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
10015 // Allow passing positional parameters inside the config object
10016 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
10017 config
= fieldWidget
;
10018 fieldWidget
= config
.fieldWidget
;
10019 buttonWidget
= config
.buttonWidget
;
10022 // Parent constructor
10023 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
10026 this.buttonWidget
= buttonWidget
;
10027 this.$button
= $( '<div>' );
10028 this.$input
= $( '<div>' );
10032 .addClass( 'oo-ui-actionFieldLayout' );
10034 .addClass( 'oo-ui-actionFieldLayout-button' )
10035 .append( this.buttonWidget
.$element
);
10037 .addClass( 'oo-ui-actionFieldLayout-input' )
10038 .append( this.fieldWidget
.$element
);
10040 .append( this.$input
, this.$button
);
10045 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
10048 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
10049 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
10050 * configured with a label as well. For more information and examples,
10051 * please see the [OOjs UI documentation on MediaWiki][1].
10054 * // Example of a fieldset layout
10055 * var input1 = new OO.ui.TextInputWidget( {
10056 * placeholder: 'A text input field'
10059 * var input2 = new OO.ui.TextInputWidget( {
10060 * placeholder: 'A text input field'
10063 * var fieldset = new OO.ui.FieldsetLayout( {
10064 * label: 'Example of a fieldset layout'
10067 * fieldset.addItems( [
10068 * new OO.ui.FieldLayout( input1, {
10069 * label: 'Field One'
10071 * new OO.ui.FieldLayout( input2, {
10072 * label: 'Field Two'
10075 * $( 'body' ).append( fieldset.$element );
10077 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
10080 * @extends OO.ui.Layout
10081 * @mixins OO.ui.mixin.IconElement
10082 * @mixins OO.ui.mixin.LabelElement
10083 * @mixins OO.ui.mixin.GroupElement
10086 * @param {Object} [config] Configuration options
10087 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
10089 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
10090 // Configuration initialization
10091 config
= config
|| {};
10093 // Parent constructor
10094 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
10096 // Mixin constructors
10097 OO
.ui
.mixin
.IconElement
.call( this, config
);
10098 OO
.ui
.mixin
.LabelElement
.call( this, config
);
10099 OO
.ui
.mixin
.GroupElement
.call( this, config
);
10101 if ( config
.help
) {
10102 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
10103 classes
: [ 'oo-ui-fieldsetLayout-help' ],
10108 this.popupButtonWidget
.getPopup().$body
.append(
10110 .text( config
.help
)
10111 .addClass( 'oo-ui-fieldsetLayout-help-content' )
10113 this.$help
= this.popupButtonWidget
.$element
;
10115 this.$help
= $( [] );
10120 .addClass( 'oo-ui-fieldsetLayout' )
10121 .prepend( this.$help
, this.$icon
, this.$label
, this.$group
);
10122 if ( Array
.isArray( config
.items
) ) {
10123 this.addItems( config
.items
);
10129 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
10130 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
10131 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
10132 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
10135 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
10136 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
10137 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
10138 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
10140 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
10141 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
10142 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
10143 * some fancier controls. Some controls have both regular and InputWidget variants, for example
10144 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
10145 * often have simplified APIs to match the capabilities of HTML forms.
10146 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
10148 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
10149 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
10152 * // Example of a form layout that wraps a fieldset layout
10153 * var input1 = new OO.ui.TextInputWidget( {
10154 * placeholder: 'Username'
10156 * var input2 = new OO.ui.TextInputWidget( {
10157 * placeholder: 'Password',
10160 * var submit = new OO.ui.ButtonInputWidget( {
10164 * var fieldset = new OO.ui.FieldsetLayout( {
10165 * label: 'A form layout'
10167 * fieldset.addItems( [
10168 * new OO.ui.FieldLayout( input1, {
10169 * label: 'Username',
10172 * new OO.ui.FieldLayout( input2, {
10173 * label: 'Password',
10176 * new OO.ui.FieldLayout( submit )
10178 * var form = new OO.ui.FormLayout( {
10179 * items: [ fieldset ],
10180 * action: '/api/formhandler',
10183 * $( 'body' ).append( form.$element );
10186 * @extends OO.ui.Layout
10187 * @mixins OO.ui.mixin.GroupElement
10190 * @param {Object} [config] Configuration options
10191 * @cfg {string} [method] HTML form `method` attribute
10192 * @cfg {string} [action] HTML form `action` attribute
10193 * @cfg {string} [enctype] HTML form `enctype` attribute
10194 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
10196 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
10199 // Configuration initialization
10200 config
= config
|| {};
10202 // Parent constructor
10203 OO
.ui
.FormLayout
.parent
.call( this, config
);
10205 // Mixin constructors
10206 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
10209 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
10211 // Make sure the action is safe
10212 action
= config
.action
;
10213 if ( action
!== undefined && !OO
.ui
.isSafeUrl( action
) ) {
10214 action
= './' + action
;
10219 .addClass( 'oo-ui-formLayout' )
10221 method
: config
.method
,
10223 enctype
: config
.enctype
10225 if ( Array
.isArray( config
.items
) ) {
10226 this.addItems( config
.items
);
10232 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
10233 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
10238 * A 'submit' event is emitted when the form is submitted.
10243 /* Static Properties */
10245 OO
.ui
.FormLayout
.static.tagName
= 'form';
10250 * Handle form submit events.
10253 * @param {jQuery.Event} e Submit event
10256 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
10257 if ( this.emit( 'submit' ) ) {
10263 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
10264 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
10267 * // Example of a panel layout
10268 * var panel = new OO.ui.PanelLayout( {
10272 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
10274 * $( 'body' ).append( panel.$element );
10277 * @extends OO.ui.Layout
10280 * @param {Object} [config] Configuration options
10281 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
10282 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10283 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10284 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10286 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
10287 // Configuration initialization
10288 config
= $.extend( {
10295 // Parent constructor
10296 OO
.ui
.PanelLayout
.parent
.call( this, config
);
10299 this.$element
.addClass( 'oo-ui-panelLayout' );
10300 if ( config
.scrollable
) {
10301 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
10303 if ( config
.padded
) {
10304 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
10306 if ( config
.expanded
) {
10307 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
10309 if ( config
.framed
) {
10310 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
10316 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
10321 * Focus the panel layout
10323 * The default implementation just focuses the first focusable element in the panel
10325 OO
.ui
.PanelLayout
.prototype.focus = function () {
10326 OO
.ui
.findFocusable( this.$element
).focus();
10330 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
10331 * items), with small margins between them. Convenient when you need to put a number of block-level
10332 * widgets on a single line next to each other.
10334 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
10337 * // HorizontalLayout with a text input and a label
10338 * var layout = new OO.ui.HorizontalLayout( {
10340 * new OO.ui.LabelWidget( { label: 'Label' } ),
10341 * new OO.ui.TextInputWidget( { value: 'Text' } )
10344 * $( 'body' ).append( layout.$element );
10347 * @extends OO.ui.Layout
10348 * @mixins OO.ui.mixin.GroupElement
10351 * @param {Object} [config] Configuration options
10352 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
10354 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
10355 // Configuration initialization
10356 config
= config
|| {};
10358 // Parent constructor
10359 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
10361 // Mixin constructors
10362 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
10365 this.$element
.addClass( 'oo-ui-horizontalLayout' );
10366 if ( Array
.isArray( config
.items
) ) {
10367 this.addItems( config
.items
);
10373 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
10374 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);