Merge "Fix Selenium tests"
[mediawiki.git] / resources / lib / oojs-ui / oojs-ui-core.js
blob5dc78aba5637109f9e3b8c239168d3d66e02876e
1 /*!
2 * OOjs UI v0.18.4-fix (d4045dee45)
3 * https://www.mediawiki.org/wiki/OOjs_UI
5 * Copyright 2011–2017 OOjs UI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: 2017-01-19T20:22:26Z
11 ( function ( OO ) {
13 'use strict';
15 /**
16 * Namespace for all classes, static methods and static properties.
18 * @class
19 * @singleton
21 OO.ui = {};
23 OO.ui.bind = $.proxy;
25 /**
26 * @property {Object}
28 OO.ui.Keys = {
29 UNDEFINED: 0,
30 BACKSPACE: 8,
31 DELETE: 46,
32 LEFT: 37,
33 RIGHT: 39,
34 UP: 38,
35 DOWN: 40,
36 ENTER: 13,
37 END: 35,
38 HOME: 36,
39 TAB: 9,
40 PAGEUP: 33,
41 PAGEDOWN: 34,
42 ESCAPE: 27,
43 SHIFT: 16,
44 SPACE: 32
47 /**
48 * Constants for MouseEvent.which
50 * @property {Object}
52 OO.ui.MouseButtons = {
53 LEFT: 1,
54 MIDDLE: 2,
55 RIGHT: 3
58 /**
59 * @property {number}
60 * @private
62 OO.ui.elementId = 0;
64 /**
65 * Generate a unique ID for element
67 * @return {string} ID
69 OO.ui.generateElementId = function () {
70 OO.ui.elementId++;
71 return 'oojsui-' + OO.ui.elementId;
74 /**
75 * Check if an element is focusable.
76 * Inspired from :focusable in jQueryUI v1.11.4 - 2015-04-14
78 * @param {jQuery} $element Element to test
79 * @return {boolean}
81 OO.ui.isFocusableElement = function ( $element ) {
82 var nodeName,
83 element = $element[ 0 ];
85 // Anything disabled is not focusable
86 if ( element.disabled ) {
87 return false;
90 // Check if the element is visible
91 if ( !(
92 // This is quicker than calling $element.is( ':visible' )
93 $.expr.filters.visible( element ) &&
94 // Check that all parents are visible
95 !$element.parents().addBack().filter( function () {
96 return $.css( this, 'visibility' ) === 'hidden';
97 } ).length
98 ) ) {
99 return false;
102 // Check if the element is ContentEditable, which is the string 'true'
103 if ( element.contentEditable === 'true' ) {
104 return true;
107 // Anything with a non-negative numeric tabIndex is focusable.
108 // Use .prop to avoid browser bugs
109 if ( $element.prop( 'tabIndex' ) >= 0 ) {
110 return true;
113 // Some element types are naturally focusable
114 // (indexOf is much faster than regex in Chrome and about the
115 // same in FF: https://jsperf.com/regex-vs-indexof-array2)
116 nodeName = element.nodeName.toLowerCase();
117 if ( [ 'input', 'select', 'textarea', 'button', 'object' ].indexOf( nodeName ) !== -1 ) {
118 return true;
121 // Links and areas are focusable if they have an href
122 if ( ( nodeName === 'a' || nodeName === 'area' ) && $element.attr( 'href' ) !== undefined ) {
123 return true;
126 return false;
130 * Find a focusable child
132 * @param {jQuery} $container Container to search in
133 * @param {boolean} [backwards] Search backwards
134 * @return {jQuery} Focusable child, an empty jQuery object if none found
136 OO.ui.findFocusable = function ( $container, backwards ) {
137 var $focusable = $( [] ),
138 // $focusableCandidates is a superset of things that
139 // could get matched by isFocusableElement
140 $focusableCandidates = $container
141 .find( 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]' );
143 if ( backwards ) {
144 $focusableCandidates = Array.prototype.reverse.call( $focusableCandidates );
147 $focusableCandidates.each( function () {
148 var $this = $( this );
149 if ( OO.ui.isFocusableElement( $this ) ) {
150 $focusable = $this;
151 return false;
153 } );
154 return $focusable;
158 * Get the user's language and any fallback languages.
160 * These language codes are used to localize user interface elements in the user's language.
162 * In environments that provide a localization system, this function should be overridden to
163 * return the user's language(s). The default implementation returns English (en) only.
165 * @return {string[]} Language codes, in descending order of priority
167 OO.ui.getUserLanguages = function () {
168 return [ 'en' ];
172 * Get a value in an object keyed by language code.
174 * @param {Object.<string,Mixed>} obj Object keyed by language code
175 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
176 * @param {string} [fallback] Fallback code, used if no matching language can be found
177 * @return {Mixed} Local value
179 OO.ui.getLocalValue = function ( obj, lang, fallback ) {
180 var i, len, langs;
182 // Requested language
183 if ( obj[ lang ] ) {
184 return obj[ lang ];
186 // Known user language
187 langs = OO.ui.getUserLanguages();
188 for ( i = 0, len = langs.length; i < len; i++ ) {
189 lang = langs[ i ];
190 if ( obj[ lang ] ) {
191 return obj[ lang ];
194 // Fallback language
195 if ( obj[ fallback ] ) {
196 return obj[ fallback ];
198 // First existing language
199 for ( lang in obj ) {
200 return obj[ lang ];
203 return undefined;
207 * Check if a node is contained within another node
209 * Similar to jQuery#contains except a list of containers can be supplied
210 * and a boolean argument allows you to include the container in the match list
212 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
213 * @param {HTMLElement} contained Node to find
214 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
215 * @return {boolean} The node is in the list of target nodes
217 OO.ui.contains = function ( containers, contained, matchContainers ) {
218 var i;
219 if ( !Array.isArray( containers ) ) {
220 containers = [ containers ];
222 for ( i = containers.length - 1; i >= 0; i-- ) {
223 if ( ( matchContainers && contained === containers[ i ] ) || $.contains( containers[ i ], contained ) ) {
224 return true;
227 return false;
231 * Return a function, that, as long as it continues to be invoked, will not
232 * be triggered. The function will be called after it stops being called for
233 * N milliseconds. If `immediate` is passed, trigger the function on the
234 * leading edge, instead of the trailing.
236 * Ported from: http://underscorejs.org/underscore.js
238 * @param {Function} func
239 * @param {number} wait
240 * @param {boolean} immediate
241 * @return {Function}
243 OO.ui.debounce = function ( func, wait, immediate ) {
244 var timeout;
245 return function () {
246 var context = this,
247 args = arguments,
248 later = function () {
249 timeout = null;
250 if ( !immediate ) {
251 func.apply( context, args );
254 if ( immediate && !timeout ) {
255 func.apply( context, args );
257 if ( !timeout || wait ) {
258 clearTimeout( timeout );
259 timeout = setTimeout( later, wait );
265 * Puts a console warning with provided message.
267 * @param {string} message
269 OO.ui.warnDeprecation = function ( message ) {
270 if ( OO.getProp( window, 'console', 'warn' ) !== undefined ) {
271 // eslint-disable-next-line no-console
272 console.warn( message );
277 * Returns a function, that, when invoked, will only be triggered at most once
278 * during a given window of time. If called again during that window, it will
279 * wait until the window ends and then trigger itself again.
281 * As it's not knowable to the caller whether the function will actually run
282 * when the wrapper is called, return values from the function are entirely
283 * discarded.
285 * @param {Function} func
286 * @param {number} wait
287 * @return {Function}
289 OO.ui.throttle = function ( func, wait ) {
290 var context, args, timeout,
291 previous = 0,
292 run = function () {
293 timeout = null;
294 previous = OO.ui.now();
295 func.apply( context, args );
297 return function () {
298 // Check how long it's been since the last time the function was
299 // called, and whether it's more or less than the requested throttle
300 // period. If it's less, run the function immediately. If it's more,
301 // set a timeout for the remaining time -- but don't replace an
302 // existing timeout, since that'd indefinitely prolong the wait.
303 var remaining = wait - ( OO.ui.now() - previous );
304 context = this;
305 args = arguments;
306 if ( remaining <= 0 ) {
307 // Note: unless wait was ridiculously large, this means we'll
308 // automatically run the first time the function was called in a
309 // given period. (If you provide a wait period larger than the
310 // current Unix timestamp, you *deserve* unexpected behavior.)
311 clearTimeout( timeout );
312 run();
313 } else if ( !timeout ) {
314 timeout = setTimeout( run, remaining );
320 * A (possibly faster) way to get the current timestamp as an integer
322 * @return {number} Current timestamp
324 OO.ui.now = Date.now || function () {
325 return new Date().getTime();
329 * Reconstitute a JavaScript object corresponding to a widget created by
330 * the PHP implementation.
332 * This is an alias for `OO.ui.Element.static.infuse()`.
334 * @param {string|HTMLElement|jQuery} idOrNode
335 * A DOM id (if a string) or node for the widget to infuse.
336 * @return {OO.ui.Element}
337 * The `OO.ui.Element` corresponding to this (infusable) document node.
339 OO.ui.infuse = function ( idOrNode ) {
340 return OO.ui.Element.static.infuse( idOrNode );
343 ( function () {
345 * Message store for the default implementation of OO.ui.msg
347 * Environments that provide a localization system should not use this, but should override
348 * OO.ui.msg altogether.
350 * @private
352 var messages = {
353 // Tool tip for a button that moves items in a list down one place
354 'ooui-outline-control-move-down': 'Move item down',
355 // Tool tip for a button that moves items in a list up one place
356 'ooui-outline-control-move-up': 'Move item up',
357 // Tool tip for a button that removes items from a list
358 'ooui-outline-control-remove': 'Remove item',
359 // Label for the toolbar group that contains a list of all other available tools
360 'ooui-toolbar-more': 'More',
361 // Label for the fake tool that expands the full list of tools in a toolbar group
362 'ooui-toolgroup-expand': 'More',
363 // Label for the fake tool that collapses the full list of tools in a toolbar group
364 'ooui-toolgroup-collapse': 'Fewer',
365 // Default label for the accept button of a confirmation dialog
366 'ooui-dialog-message-accept': 'OK',
367 // Default label for the reject button of a confirmation dialog
368 'ooui-dialog-message-reject': 'Cancel',
369 // Title for process dialog error description
370 'ooui-dialog-process-error': 'Something went wrong',
371 // Label for process dialog dismiss error button, visible when describing errors
372 'ooui-dialog-process-dismiss': 'Dismiss',
373 // Label for process dialog retry action button, visible when describing only recoverable errors
374 'ooui-dialog-process-retry': 'Try again',
375 // Label for process dialog retry action button, visible when describing only warnings
376 'ooui-dialog-process-continue': 'Continue',
377 // Label for the file selection widget's select file button
378 'ooui-selectfile-button-select': 'Select a file',
379 // Label for the file selection widget if file selection is not supported
380 'ooui-selectfile-not-supported': 'File selection is not supported',
381 // Label for the file selection widget when no file is currently selected
382 'ooui-selectfile-placeholder': 'No file is selected',
383 // Label for the file selection widget's drop target
384 'ooui-selectfile-dragdrop-placeholder': 'Drop file here'
388 * Get a localized message.
390 * After the message key, message parameters may optionally be passed. In the default implementation,
391 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
392 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
393 * they support unnamed, ordered message parameters.
395 * In environments that provide a localization system, this function should be overridden to
396 * return the message translated in the user's language. The default implementation always returns
397 * English messages. An example of doing this with [jQuery.i18n](https://github.com/wikimedia/jquery.i18n)
398 * follows.
400 * @example
401 * var i, iLen, button,
402 * messagePath = 'oojs-ui/dist/i18n/',
403 * languages = [ $.i18n().locale, 'ur', 'en' ],
404 * languageMap = {};
406 * for ( i = 0, iLen = languages.length; i < iLen; i++ ) {
407 * languageMap[ languages[ i ] ] = messagePath + languages[ i ].toLowerCase() + '.json';
410 * $.i18n().load( languageMap ).done( function() {
411 * // Replace the built-in `msg` only once we've loaded the internationalization.
412 * // OOjs UI uses `OO.ui.deferMsg` for all initially-loaded messages. So long as
413 * // you put off creating any widgets until this promise is complete, no English
414 * // will be displayed.
415 * OO.ui.msg = $.i18n;
417 * // A button displaying "OK" in the default locale
418 * button = new OO.ui.ButtonWidget( {
419 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
420 * icon: 'check'
421 * } );
422 * $( 'body' ).append( button.$element );
424 * // A button displaying "OK" in Urdu
425 * $.i18n().locale = 'ur';
426 * button = new OO.ui.ButtonWidget( {
427 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
428 * icon: 'check'
429 * } );
430 * $( 'body' ).append( button.$element );
431 * } );
433 * @param {string} key Message key
434 * @param {...Mixed} [params] Message parameters
435 * @return {string} Translated message with parameters substituted
437 OO.ui.msg = function ( key ) {
438 var message = messages[ key ],
439 params = Array.prototype.slice.call( arguments, 1 );
440 if ( typeof message === 'string' ) {
441 // Perform $1 substitution
442 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
443 var i = parseInt( n, 10 );
444 return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n;
445 } );
446 } else {
447 // Return placeholder if message not found
448 message = '[' + key + ']';
450 return message;
452 }() );
455 * Package a message and arguments for deferred resolution.
457 * Use this when you are statically specifying a message and the message may not yet be present.
459 * @param {string} key Message key
460 * @param {...Mixed} [params] Message parameters
461 * @return {Function} Function that returns the resolved message when executed
463 OO.ui.deferMsg = function () {
464 var args = arguments;
465 return function () {
466 return OO.ui.msg.apply( OO.ui, args );
471 * Resolve a message.
473 * If the message is a function it will be executed, otherwise it will pass through directly.
475 * @param {Function|string} msg Deferred message, or message text
476 * @return {string} Resolved message
478 OO.ui.resolveMsg = function ( msg ) {
479 if ( $.isFunction( msg ) ) {
480 return msg();
482 return msg;
486 * @param {string} url
487 * @return {boolean}
489 OO.ui.isSafeUrl = function ( url ) {
490 // Keep this function in sync with php/Tag.php
491 var i, protocolWhitelist;
493 function stringStartsWith( haystack, needle ) {
494 return haystack.substr( 0, needle.length ) === needle;
497 protocolWhitelist = [
498 'bitcoin', 'ftp', 'ftps', 'geo', 'git', 'gopher', 'http', 'https', 'irc', 'ircs',
499 'magnet', 'mailto', 'mms', 'news', 'nntp', 'redis', 'sftp', 'sip', 'sips', 'sms', 'ssh',
500 'svn', 'tel', 'telnet', 'urn', 'worldwind', 'xmpp'
503 if ( url === '' ) {
504 return true;
507 for ( i = 0; i < protocolWhitelist.length; i++ ) {
508 if ( stringStartsWith( url, protocolWhitelist[ i ] + ':' ) ) {
509 return true;
513 // This matches '//' too
514 if ( stringStartsWith( url, '/' ) || stringStartsWith( url, './' ) ) {
515 return true;
517 if ( stringStartsWith( url, '?' ) || stringStartsWith( url, '#' ) ) {
518 return true;
521 return false;
525 * Check if the user has a 'mobile' device.
527 * For our purposes this means the user is primarily using an
528 * on-screen keyboard, touch input instead of a mouse and may
529 * have a physically small display.
531 * It is left up to implementors to decide how to compute this
532 * so the default implementation always returns false.
534 * @return {boolean} Use is on a mobile device
536 OO.ui.isMobile = function () {
537 return false;
541 * Mixin namespace.
545 * Namespace for OOjs UI mixins.
547 * Mixins are named according to the type of object they are intended to
548 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
549 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
550 * is intended to be mixed in to an instance of OO.ui.Widget.
552 * @class
553 * @singleton
555 OO.ui.mixin = {};
558 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
559 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
560 * connected to them and can't be interacted with.
562 * @abstract
563 * @class
565 * @constructor
566 * @param {Object} [config] Configuration options
567 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
568 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
569 * for an example.
570 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
571 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
572 * @cfg {string} [text] Text to insert
573 * @cfg {Array} [content] An array of content elements to append (after #text).
574 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
575 * Instances of OO.ui.Element will have their $element appended.
576 * @cfg {jQuery} [$content] Content elements to append (after #text).
577 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
578 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
579 * Data can also be specified with the #setData method.
581 OO.ui.Element = function OoUiElement( config ) {
582 // Configuration initialization
583 config = config || {};
585 // Properties
586 this.$ = $;
587 this.visible = true;
588 this.data = config.data;
589 this.$element = config.$element ||
590 $( document.createElement( this.getTagName() ) );
591 this.elementGroup = null;
593 // Initialization
594 if ( Array.isArray( config.classes ) ) {
595 this.$element.addClass( config.classes.join( ' ' ) );
597 if ( config.id ) {
598 this.$element.attr( 'id', config.id );
600 if ( config.text ) {
601 this.$element.text( config.text );
603 if ( config.content ) {
604 // The `content` property treats plain strings as text; use an
605 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
606 // appropriate $element appended.
607 this.$element.append( config.content.map( function ( v ) {
608 if ( typeof v === 'string' ) {
609 // Escape string so it is properly represented in HTML.
610 return document.createTextNode( v );
611 } else if ( v instanceof OO.ui.HtmlSnippet ) {
612 // Bypass escaping.
613 return v.toString();
614 } else if ( v instanceof OO.ui.Element ) {
615 return v.$element;
617 return v;
618 } ) );
620 if ( config.$content ) {
621 // The `$content` property treats plain strings as HTML.
622 this.$element.append( config.$content );
626 /* Setup */
628 OO.initClass( OO.ui.Element );
630 /* Static Properties */
633 * The name of the HTML tag used by the element.
635 * The static value may be ignored if the #getTagName method is overridden.
637 * @static
638 * @inheritable
639 * @property {string}
641 OO.ui.Element.static.tagName = 'div';
643 /* Static Methods */
646 * Reconstitute a JavaScript object corresponding to a widget created
647 * by the PHP implementation.
649 * @param {string|HTMLElement|jQuery} idOrNode
650 * A DOM id (if a string) or node for the widget to infuse.
651 * @return {OO.ui.Element}
652 * The `OO.ui.Element` corresponding to this (infusable) document node.
653 * For `Tag` objects emitted on the HTML side (used occasionally for content)
654 * the value returned is a newly-created Element wrapping around the existing
655 * DOM node.
657 OO.ui.Element.static.infuse = function ( idOrNode ) {
658 var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, false );
659 // Verify that the type matches up.
660 // FIXME: uncomment after T89721 is fixed (see T90929)
662 if ( !( obj instanceof this['class'] ) ) {
663 throw new Error( 'Infusion type mismatch!' );
666 return obj;
670 * Implementation helper for `infuse`; skips the type check and has an
671 * extra property so that only the top-level invocation touches the DOM.
673 * @private
674 * @param {string|HTMLElement|jQuery} idOrNode
675 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
676 * when the top-level widget of this infusion is inserted into DOM,
677 * replacing the original node; or false for top-level invocation.
678 * @return {OO.ui.Element}
680 OO.ui.Element.static.unsafeInfuse = function ( idOrNode, domPromise ) {
681 // look for a cached result of a previous infusion.
682 var id, $elem, data, cls, parts, parent, obj, top, state, infusedChildren;
683 if ( typeof idOrNode === 'string' ) {
684 id = idOrNode;
685 $elem = $( document.getElementById( id ) );
686 } else {
687 $elem = $( idOrNode );
688 id = $elem.attr( 'id' );
690 if ( !$elem.length ) {
691 throw new Error( 'Widget not found: ' + id );
693 if ( $elem[ 0 ].oouiInfused ) {
694 $elem = $elem[ 0 ].oouiInfused;
696 data = $elem.data( 'ooui-infused' );
697 if ( data ) {
698 // cached!
699 if ( data === true ) {
700 throw new Error( 'Circular dependency! ' + id );
702 if ( domPromise ) {
703 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
704 state = data.constructor.static.gatherPreInfuseState( $elem, data );
705 // restore dynamic state after the new element is re-inserted into DOM under infused parent
706 domPromise.done( data.restorePreInfuseState.bind( data, state ) );
707 infusedChildren = $elem.data( 'ooui-infused-children' );
708 if ( infusedChildren && infusedChildren.length ) {
709 infusedChildren.forEach( function ( data ) {
710 var state = data.constructor.static.gatherPreInfuseState( $elem, data );
711 domPromise.done( data.restorePreInfuseState.bind( data, state ) );
712 } );
715 return data;
717 data = $elem.attr( 'data-ooui' );
718 if ( !data ) {
719 throw new Error( 'No infusion data found: ' + id );
721 try {
722 data = $.parseJSON( data );
723 } catch ( _ ) {
724 data = null;
726 if ( !( data && data._ ) ) {
727 throw new Error( 'No valid infusion data found: ' + id );
729 if ( data._ === 'Tag' ) {
730 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
731 return new OO.ui.Element( { $element: $elem } );
733 parts = data._.split( '.' );
734 cls = OO.getProp.apply( OO, [ window ].concat( parts ) );
735 if ( cls === undefined ) {
736 // The PHP output might be old and not including the "OO.ui" prefix
737 // TODO: Remove this back-compat after next major release
738 cls = OO.getProp.apply( OO, [ OO.ui ].concat( parts ) );
739 if ( cls === undefined ) {
740 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
744 // Verify that we're creating an OO.ui.Element instance
745 parent = cls.parent;
747 while ( parent !== undefined ) {
748 if ( parent === OO.ui.Element ) {
749 // Safe
750 break;
753 parent = parent.parent;
756 if ( parent !== OO.ui.Element ) {
757 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
760 if ( domPromise === false ) {
761 top = $.Deferred();
762 domPromise = top.promise();
764 $elem.data( 'ooui-infused', true ); // prevent loops
765 data.id = id; // implicit
766 infusedChildren = [];
767 data = OO.copy( data, null, function deserialize( value ) {
768 var infused;
769 if ( OO.isPlainObject( value ) ) {
770 if ( value.tag ) {
771 infused = OO.ui.Element.static.unsafeInfuse( value.tag, domPromise );
772 infusedChildren.push( infused );
773 // Flatten the structure
774 infusedChildren.push.apply( infusedChildren, infused.$element.data( 'ooui-infused-children' ) || [] );
775 infused.$element.removeData( 'ooui-infused-children' );
776 return infused;
778 if ( value.html !== undefined ) {
779 return new OO.ui.HtmlSnippet( value.html );
782 } );
783 // allow widgets to reuse parts of the DOM
784 data = cls.static.reusePreInfuseDOM( $elem[ 0 ], data );
785 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
786 state = cls.static.gatherPreInfuseState( $elem[ 0 ], data );
787 // rebuild widget
788 // eslint-disable-next-line new-cap
789 obj = new cls( data );
790 // now replace old DOM with this new DOM.
791 if ( top ) {
792 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
793 // so only mutate the DOM if we need to.
794 if ( $elem[ 0 ] !== obj.$element[ 0 ] ) {
795 $elem.replaceWith( obj.$element );
796 // This element is now gone from the DOM, but if anyone is holding a reference to it,
797 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
798 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
799 $elem[ 0 ].oouiInfused = obj.$element;
801 top.resolve();
803 obj.$element.data( 'ooui-infused', obj );
804 obj.$element.data( 'ooui-infused-children', infusedChildren );
805 // set the 'data-ooui' attribute so we can identify infused widgets
806 obj.$element.attr( 'data-ooui', '' );
807 // restore dynamic state after the new element is inserted into DOM
808 domPromise.done( obj.restorePreInfuseState.bind( obj, state ) );
809 return obj;
813 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
815 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
816 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
817 * constructor, which will be given the enhanced config.
819 * @protected
820 * @param {HTMLElement} node
821 * @param {Object} config
822 * @return {Object}
824 OO.ui.Element.static.reusePreInfuseDOM = function ( node, config ) {
825 return config;
829 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of an HTML DOM node
830 * (and its children) that represent an Element of the same class and the given configuration,
831 * generated by the PHP implementation.
833 * This method is called just before `node` is detached from the DOM. The return value of this
834 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
835 * is inserted into DOM to replace `node`.
837 * @protected
838 * @param {HTMLElement} node
839 * @param {Object} config
840 * @return {Object}
842 OO.ui.Element.static.gatherPreInfuseState = function () {
843 return {};
847 * Get a jQuery function within a specific document.
849 * @static
850 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
851 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
852 * not in an iframe
853 * @return {Function} Bound jQuery function
855 OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
856 function wrapper( selector ) {
857 return $( selector, wrapper.context );
860 wrapper.context = this.getDocument( context );
862 if ( $iframe ) {
863 wrapper.$iframe = $iframe;
866 return wrapper;
870 * Get the document of an element.
872 * @static
873 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
874 * @return {HTMLDocument|null} Document object
876 OO.ui.Element.static.getDocument = function ( obj ) {
877 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
878 return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
879 // Empty jQuery selections might have a context
880 obj.context ||
881 // HTMLElement
882 obj.ownerDocument ||
883 // Window
884 obj.document ||
885 // HTMLDocument
886 ( obj.nodeType === 9 && obj ) ||
887 null;
891 * Get the window of an element or document.
893 * @static
894 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
895 * @return {Window} Window object
897 OO.ui.Element.static.getWindow = function ( obj ) {
898 var doc = this.getDocument( obj );
899 return doc.defaultView;
903 * Get the direction of an element or document.
905 * @static
906 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
907 * @return {string} Text direction, either 'ltr' or 'rtl'
909 OO.ui.Element.static.getDir = function ( obj ) {
910 var isDoc, isWin;
912 if ( obj instanceof jQuery ) {
913 obj = obj[ 0 ];
915 isDoc = obj.nodeType === 9;
916 isWin = obj.document !== undefined;
917 if ( isDoc || isWin ) {
918 if ( isWin ) {
919 obj = obj.document;
921 obj = obj.body;
923 return $( obj ).css( 'direction' );
927 * Get the offset between two frames.
929 * TODO: Make this function not use recursion.
931 * @static
932 * @param {Window} from Window of the child frame
933 * @param {Window} [to=window] Window of the parent frame
934 * @param {Object} [offset] Offset to start with, used internally
935 * @return {Object} Offset object, containing left and top properties
937 OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
938 var i, len, frames, frame, rect;
940 if ( !to ) {
941 to = window;
943 if ( !offset ) {
944 offset = { top: 0, left: 0 };
946 if ( from.parent === from ) {
947 return offset;
950 // Get iframe element
951 frames = from.parent.document.getElementsByTagName( 'iframe' );
952 for ( i = 0, len = frames.length; i < len; i++ ) {
953 if ( frames[ i ].contentWindow === from ) {
954 frame = frames[ i ];
955 break;
959 // Recursively accumulate offset values
960 if ( frame ) {
961 rect = frame.getBoundingClientRect();
962 offset.left += rect.left;
963 offset.top += rect.top;
964 if ( from !== to ) {
965 this.getFrameOffset( from.parent, offset );
968 return offset;
972 * Get the offset between two elements.
974 * The two elements may be in a different frame, but in that case the frame $element is in must
975 * be contained in the frame $anchor is in.
977 * @static
978 * @param {jQuery} $element Element whose position to get
979 * @param {jQuery} $anchor Element to get $element's position relative to
980 * @return {Object} Translated position coordinates, containing top and left properties
982 OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
983 var iframe, iframePos,
984 pos = $element.offset(),
985 anchorPos = $anchor.offset(),
986 elementDocument = this.getDocument( $element ),
987 anchorDocument = this.getDocument( $anchor );
989 // If $element isn't in the same document as $anchor, traverse up
990 while ( elementDocument !== anchorDocument ) {
991 iframe = elementDocument.defaultView.frameElement;
992 if ( !iframe ) {
993 throw new Error( '$element frame is not contained in $anchor frame' );
995 iframePos = $( iframe ).offset();
996 pos.left += iframePos.left;
997 pos.top += iframePos.top;
998 elementDocument = iframe.ownerDocument;
1000 pos.left -= anchorPos.left;
1001 pos.top -= anchorPos.top;
1002 return pos;
1006 * Get element border sizes.
1008 * @static
1009 * @param {HTMLElement} el Element to measure
1010 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1012 OO.ui.Element.static.getBorders = function ( el ) {
1013 var doc = el.ownerDocument,
1014 win = doc.defaultView,
1015 style = win.getComputedStyle( el, null ),
1016 $el = $( el ),
1017 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
1018 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
1019 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
1020 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
1022 return {
1023 top: top,
1024 left: left,
1025 bottom: bottom,
1026 right: right
1031 * Get dimensions of an element or window.
1033 * @static
1034 * @param {HTMLElement|Window} el Element to measure
1035 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1037 OO.ui.Element.static.getDimensions = function ( el ) {
1038 var $el, $win,
1039 doc = el.ownerDocument || el.document,
1040 win = doc.defaultView;
1042 if ( win === el || el === doc.documentElement ) {
1043 $win = $( win );
1044 return {
1045 borders: { top: 0, left: 0, bottom: 0, right: 0 },
1046 scroll: {
1047 top: $win.scrollTop(),
1048 left: $win.scrollLeft()
1050 scrollbar: { right: 0, bottom: 0 },
1051 rect: {
1052 top: 0,
1053 left: 0,
1054 bottom: $win.innerHeight(),
1055 right: $win.innerWidth()
1058 } else {
1059 $el = $( el );
1060 return {
1061 borders: this.getBorders( el ),
1062 scroll: {
1063 top: $el.scrollTop(),
1064 left: $el.scrollLeft()
1066 scrollbar: {
1067 right: $el.innerWidth() - el.clientWidth,
1068 bottom: $el.innerHeight() - el.clientHeight
1070 rect: el.getBoundingClientRect()
1076 * Get scrollable object parent
1078 * documentElement can't be used to get or set the scrollTop
1079 * property on Blink. Changing and testing its value lets us
1080 * use 'body' or 'documentElement' based on what is working.
1082 * https://code.google.com/p/chromium/issues/detail?id=303131
1084 * @static
1085 * @param {HTMLElement} el Element to find scrollable parent for
1086 * @return {HTMLElement} Scrollable parent
1088 OO.ui.Element.static.getRootScrollableElement = function ( el ) {
1089 var scrollTop, body;
1091 if ( OO.ui.scrollableElement === undefined ) {
1092 body = el.ownerDocument.body;
1093 scrollTop = body.scrollTop;
1094 body.scrollTop = 1;
1096 if ( body.scrollTop === 1 ) {
1097 body.scrollTop = scrollTop;
1098 OO.ui.scrollableElement = 'body';
1099 } else {
1100 OO.ui.scrollableElement = 'documentElement';
1104 return el.ownerDocument[ OO.ui.scrollableElement ];
1108 * Get closest scrollable container.
1110 * Traverses up until either a scrollable element or the root is reached, in which case the window
1111 * will be returned.
1113 * @static
1114 * @param {HTMLElement} el Element to find scrollable container for
1115 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1116 * @return {HTMLElement} Closest scrollable container
1118 OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
1119 var i, val,
1120 // props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
1121 props = [ 'overflow-x', 'overflow-y' ],
1122 $parent = $( el ).parent();
1124 if ( dimension === 'x' || dimension === 'y' ) {
1125 props = [ 'overflow-' + dimension ];
1128 while ( $parent.length ) {
1129 if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
1130 return $parent[ 0 ];
1132 i = props.length;
1133 while ( i-- ) {
1134 val = $parent.css( props[ i ] );
1135 if ( val === 'auto' || val === 'scroll' ) {
1136 return $parent[ 0 ];
1139 $parent = $parent.parent();
1141 return this.getDocument( el ).body;
1145 * Scroll element into view.
1147 * @static
1148 * @param {HTMLElement} el Element to scroll into view
1149 * @param {Object} [config] Configuration options
1150 * @param {string} [config.duration='fast'] jQuery animation duration value
1151 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1152 * to scroll in both directions
1153 * @param {Function} [config.complete] Function to call when scrolling completes.
1154 * Deprecated since 0.15.4, use the return promise instead.
1155 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1157 OO.ui.Element.static.scrollIntoView = function ( el, config ) {
1158 var position, animations, callback, container, $container, elementDimensions, containerDimensions, $window,
1159 deferred = $.Deferred();
1161 // Configuration initialization
1162 config = config || {};
1164 animations = {};
1165 callback = typeof config.complete === 'function' && config.complete;
1166 if ( callback ) {
1167 OO.ui.warnDeprecation( 'Element#scrollIntoView: The `complete` callback config option is deprecated. Use the return promise instead.' );
1169 container = this.getClosestScrollableContainer( el, config.direction );
1170 $container = $( container );
1171 elementDimensions = this.getDimensions( el );
1172 containerDimensions = this.getDimensions( container );
1173 $window = $( this.getWindow( el ) );
1175 // Compute the element's position relative to the container
1176 if ( $container.is( 'html, body' ) ) {
1177 // If the scrollable container is the root, this is easy
1178 position = {
1179 top: elementDimensions.rect.top,
1180 bottom: $window.innerHeight() - elementDimensions.rect.bottom,
1181 left: elementDimensions.rect.left,
1182 right: $window.innerWidth() - elementDimensions.rect.right
1184 } else {
1185 // Otherwise, we have to subtract el's coordinates from container's coordinates
1186 position = {
1187 top: elementDimensions.rect.top - ( containerDimensions.rect.top + containerDimensions.borders.top ),
1188 bottom: containerDimensions.rect.bottom - containerDimensions.borders.bottom - containerDimensions.scrollbar.bottom - elementDimensions.rect.bottom,
1189 left: elementDimensions.rect.left - ( containerDimensions.rect.left + containerDimensions.borders.left ),
1190 right: containerDimensions.rect.right - containerDimensions.borders.right - containerDimensions.scrollbar.right - elementDimensions.rect.right
1194 if ( !config.direction || config.direction === 'y' ) {
1195 if ( position.top < 0 ) {
1196 animations.scrollTop = containerDimensions.scroll.top + position.top;
1197 } else if ( position.top > 0 && position.bottom < 0 ) {
1198 animations.scrollTop = containerDimensions.scroll.top + Math.min( position.top, -position.bottom );
1201 if ( !config.direction || config.direction === 'x' ) {
1202 if ( position.left < 0 ) {
1203 animations.scrollLeft = containerDimensions.scroll.left + position.left;
1204 } else if ( position.left > 0 && position.right < 0 ) {
1205 animations.scrollLeft = containerDimensions.scroll.left + Math.min( position.left, -position.right );
1208 if ( !$.isEmptyObject( animations ) ) {
1209 $container.stop( true ).animate( animations, config.duration === undefined ? 'fast' : config.duration );
1210 $container.queue( function ( next ) {
1211 if ( callback ) {
1212 callback();
1214 deferred.resolve();
1215 next();
1216 } );
1217 } else {
1218 if ( callback ) {
1219 callback();
1221 deferred.resolve();
1223 return deferred.promise();
1227 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1228 * and reserve space for them, because it probably doesn't.
1230 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1231 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1232 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1233 * and then reattach (or show) them back.
1235 * @static
1236 * @param {HTMLElement} el Element to reconsider the scrollbars on
1238 OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
1239 var i, len, scrollLeft, scrollTop, nodes = [];
1240 // Save scroll position
1241 scrollLeft = el.scrollLeft;
1242 scrollTop = el.scrollTop;
1243 // Detach all children
1244 while ( el.firstChild ) {
1245 nodes.push( el.firstChild );
1246 el.removeChild( el.firstChild );
1248 // Force reflow
1249 void el.offsetHeight;
1250 // Reattach all children
1251 for ( i = 0, len = nodes.length; i < len; i++ ) {
1252 el.appendChild( nodes[ i ] );
1254 // Restore scroll position (no-op if scrollbars disappeared)
1255 el.scrollLeft = scrollLeft;
1256 el.scrollTop = scrollTop;
1259 /* Methods */
1262 * Toggle visibility of an element.
1264 * @param {boolean} [show] Make element visible, omit to toggle visibility
1265 * @fires visible
1266 * @chainable
1268 OO.ui.Element.prototype.toggle = function ( show ) {
1269 show = show === undefined ? !this.visible : !!show;
1271 if ( show !== this.isVisible() ) {
1272 this.visible = show;
1273 this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
1274 this.emit( 'toggle', show );
1277 return this;
1281 * Check if element is visible.
1283 * @return {boolean} element is visible
1285 OO.ui.Element.prototype.isVisible = function () {
1286 return this.visible;
1290 * Get element data.
1292 * @return {Mixed} Element data
1294 OO.ui.Element.prototype.getData = function () {
1295 return this.data;
1299 * Set element data.
1301 * @param {Mixed} data Element data
1302 * @chainable
1304 OO.ui.Element.prototype.setData = function ( data ) {
1305 this.data = data;
1306 return this;
1310 * Check if element supports one or more methods.
1312 * @param {string|string[]} methods Method or list of methods to check
1313 * @return {boolean} All methods are supported
1315 OO.ui.Element.prototype.supports = function ( methods ) {
1316 var i, len,
1317 support = 0;
1319 methods = Array.isArray( methods ) ? methods : [ methods ];
1320 for ( i = 0, len = methods.length; i < len; i++ ) {
1321 if ( $.isFunction( this[ methods[ i ] ] ) ) {
1322 support++;
1326 return methods.length === support;
1330 * Update the theme-provided classes.
1332 * @localdoc This is called in element mixins and widget classes any time state changes.
1333 * Updating is debounced, minimizing overhead of changing multiple attributes and
1334 * guaranteeing that theme updates do not occur within an element's constructor
1336 OO.ui.Element.prototype.updateThemeClasses = function () {
1337 OO.ui.theme.queueUpdateElementClasses( this );
1341 * Get the HTML tag name.
1343 * Override this method to base the result on instance information.
1345 * @return {string} HTML tag name
1347 OO.ui.Element.prototype.getTagName = function () {
1348 return this.constructor.static.tagName;
1352 * Check if the element is attached to the DOM
1354 * @return {boolean} The element is attached to the DOM
1356 OO.ui.Element.prototype.isElementAttached = function () {
1357 return $.contains( this.getElementDocument(), this.$element[ 0 ] );
1361 * Get the DOM document.
1363 * @return {HTMLDocument} Document object
1365 OO.ui.Element.prototype.getElementDocument = function () {
1366 // Don't cache this in other ways either because subclasses could can change this.$element
1367 return OO.ui.Element.static.getDocument( this.$element );
1371 * Get the DOM window.
1373 * @return {Window} Window object
1375 OO.ui.Element.prototype.getElementWindow = function () {
1376 return OO.ui.Element.static.getWindow( this.$element );
1380 * Get closest scrollable container.
1382 * @return {HTMLElement} Closest scrollable container
1384 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1385 return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
1389 * Get group element is in.
1391 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1393 OO.ui.Element.prototype.getElementGroup = function () {
1394 return this.elementGroup;
1398 * Set group element is in.
1400 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1401 * @chainable
1403 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1404 this.elementGroup = group;
1405 return this;
1409 * Scroll element into view.
1411 * @param {Object} [config] Configuration options
1412 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1414 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
1415 if (
1416 !this.isElementAttached() ||
1417 !this.isVisible() ||
1418 ( this.getElementGroup() && !this.getElementGroup().isVisible() )
1420 return $.Deferred().resolve();
1422 return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
1426 * Restore the pre-infusion dynamic state for this widget.
1428 * This method is called after #$element has been inserted into DOM. The parameter is the return
1429 * value of #gatherPreInfuseState.
1431 * @protected
1432 * @param {Object} state
1434 OO.ui.Element.prototype.restorePreInfuseState = function () {
1438 * Wraps an HTML snippet for use with configuration values which default
1439 * to strings. This bypasses the default html-escaping done to string
1440 * values.
1442 * @class
1444 * @constructor
1445 * @param {string} [content] HTML content
1447 OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
1448 // Properties
1449 this.content = content;
1452 /* Setup */
1454 OO.initClass( OO.ui.HtmlSnippet );
1456 /* Methods */
1459 * Render into HTML.
1461 * @return {string} Unchanged HTML snippet.
1463 OO.ui.HtmlSnippet.prototype.toString = function () {
1464 return this.content;
1468 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1469 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1470 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1471 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1472 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1474 * @abstract
1475 * @class
1476 * @extends OO.ui.Element
1477 * @mixins OO.EventEmitter
1479 * @constructor
1480 * @param {Object} [config] Configuration options
1482 OO.ui.Layout = function OoUiLayout( config ) {
1483 // Configuration initialization
1484 config = config || {};
1486 // Parent constructor
1487 OO.ui.Layout.parent.call( this, config );
1489 // Mixin constructors
1490 OO.EventEmitter.call( this );
1492 // Initialization
1493 this.$element.addClass( 'oo-ui-layout' );
1496 /* Setup */
1498 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1499 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1502 * Widgets are compositions of one or more OOjs UI elements that users can both view
1503 * and interact with. All widgets can be configured and modified via a standard API,
1504 * and their state can change dynamically according to a model.
1506 * @abstract
1507 * @class
1508 * @extends OO.ui.Element
1509 * @mixins OO.EventEmitter
1511 * @constructor
1512 * @param {Object} [config] Configuration options
1513 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1514 * appearance reflects this state.
1516 OO.ui.Widget = function OoUiWidget( config ) {
1517 // Initialize config
1518 config = $.extend( { disabled: false }, config );
1520 // Parent constructor
1521 OO.ui.Widget.parent.call( this, config );
1523 // Mixin constructors
1524 OO.EventEmitter.call( this );
1526 // Properties
1527 this.disabled = null;
1528 this.wasDisabled = null;
1530 // Initialization
1531 this.$element.addClass( 'oo-ui-widget' );
1532 this.setDisabled( !!config.disabled );
1535 /* Setup */
1537 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
1538 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
1540 /* Static Properties */
1543 * Whether this widget will behave reasonably when wrapped in an HTML `<label>`. If this is true,
1544 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
1545 * handling.
1547 * @static
1548 * @inheritable
1549 * @property {boolean}
1551 OO.ui.Widget.static.supportsSimpleLabel = false;
1553 /* Events */
1556 * @event disable
1558 * A 'disable' event is emitted when the disabled state of the widget changes
1559 * (i.e. on disable **and** enable).
1561 * @param {boolean} disabled Widget is disabled
1565 * @event toggle
1567 * A 'toggle' event is emitted when the visibility of the widget changes.
1569 * @param {boolean} visible Widget is visible
1572 /* Methods */
1575 * Check if the widget is disabled.
1577 * @return {boolean} Widget is disabled
1579 OO.ui.Widget.prototype.isDisabled = function () {
1580 return this.disabled;
1584 * Set the 'disabled' state of the widget.
1586 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1588 * @param {boolean} disabled Disable widget
1589 * @chainable
1591 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
1592 var isDisabled;
1594 this.disabled = !!disabled;
1595 isDisabled = this.isDisabled();
1596 if ( isDisabled !== this.wasDisabled ) {
1597 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
1598 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
1599 this.$element.attr( 'aria-disabled', isDisabled.toString() );
1600 this.emit( 'disable', isDisabled );
1601 this.updateThemeClasses();
1603 this.wasDisabled = isDisabled;
1605 return this;
1609 * Update the disabled state, in case of changes in parent widget.
1611 * @chainable
1613 OO.ui.Widget.prototype.updateDisabled = function () {
1614 this.setDisabled( this.disabled );
1615 return this;
1619 * Theme logic.
1621 * @abstract
1622 * @class
1624 * @constructor
1626 OO.ui.Theme = function OoUiTheme() {
1627 this.elementClassesQueue = [];
1628 this.debouncedUpdateQueuedElementClasses = OO.ui.debounce( this.updateQueuedElementClasses );
1631 /* Setup */
1633 OO.initClass( OO.ui.Theme );
1635 /* Methods */
1638 * Get a list of classes to be applied to a widget.
1640 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
1641 * otherwise state transitions will not work properly.
1643 * @param {OO.ui.Element} element Element for which to get classes
1644 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1646 OO.ui.Theme.prototype.getElementClasses = function () {
1647 return { on: [], off: [] };
1651 * Update CSS classes provided by the theme.
1653 * For elements with theme logic hooks, this should be called any time there's a state change.
1655 * @param {OO.ui.Element} element Element for which to update classes
1657 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
1658 var $elements = $( [] ),
1659 classes = this.getElementClasses( element );
1661 if ( element.$icon ) {
1662 $elements = $elements.add( element.$icon );
1664 if ( element.$indicator ) {
1665 $elements = $elements.add( element.$indicator );
1668 $elements
1669 .removeClass( classes.off.join( ' ' ) )
1670 .addClass( classes.on.join( ' ' ) );
1674 * @private
1676 OO.ui.Theme.prototype.updateQueuedElementClasses = function () {
1677 var i;
1678 for ( i = 0; i < this.elementClassesQueue.length; i++ ) {
1679 this.updateElementClasses( this.elementClassesQueue[ i ] );
1681 // Clear the queue
1682 this.elementClassesQueue = [];
1686 * Queue #updateElementClasses to be called for this element.
1688 * @localdoc QUnit tests override this method to directly call #queueUpdateElementClasses,
1689 * to make them synchronous.
1691 * @param {OO.ui.Element} element Element for which to update classes
1693 OO.ui.Theme.prototype.queueUpdateElementClasses = function ( element ) {
1694 // Keep items in the queue unique. Use lastIndexOf to start checking from the end because that's
1695 // the most common case (this method is often called repeatedly for the same element).
1696 if ( this.elementClassesQueue.lastIndexOf( element ) !== -1 ) {
1697 return;
1699 this.elementClassesQueue.push( element );
1700 this.debouncedUpdateQueuedElementClasses();
1704 * Get the transition duration in milliseconds for dialogs opening/closing
1706 * The dialog should be fully rendered this many milliseconds after the
1707 * ready process has executed.
1709 * @return {number} Transition duration in milliseconds
1711 OO.ui.Theme.prototype.getDialogTransitionDuration = function () {
1712 return 0;
1716 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
1717 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
1718 * order in which users will navigate through the focusable elements via the "tab" key.
1720 * @example
1721 * // TabIndexedElement is mixed into the ButtonWidget class
1722 * // to provide a tabIndex property.
1723 * var button1 = new OO.ui.ButtonWidget( {
1724 * label: 'fourth',
1725 * tabIndex: 4
1726 * } );
1727 * var button2 = new OO.ui.ButtonWidget( {
1728 * label: 'second',
1729 * tabIndex: 2
1730 * } );
1731 * var button3 = new OO.ui.ButtonWidget( {
1732 * label: 'third',
1733 * tabIndex: 3
1734 * } );
1735 * var button4 = new OO.ui.ButtonWidget( {
1736 * label: 'first',
1737 * tabIndex: 1
1738 * } );
1739 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
1741 * @abstract
1742 * @class
1744 * @constructor
1745 * @param {Object} [config] Configuration options
1746 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
1747 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
1748 * functionality will be applied to it instead.
1749 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
1750 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
1751 * to remove the element from the tab-navigation flow.
1753 OO.ui.mixin.TabIndexedElement = function OoUiMixinTabIndexedElement( config ) {
1754 // Configuration initialization
1755 config = $.extend( { tabIndex: 0 }, config );
1757 // Properties
1758 this.$tabIndexed = null;
1759 this.tabIndex = null;
1761 // Events
1762 this.connect( this, { disable: 'onTabIndexedElementDisable' } );
1764 // Initialization
1765 this.setTabIndex( config.tabIndex );
1766 this.setTabIndexedElement( config.$tabIndexed || this.$element );
1769 /* Setup */
1771 OO.initClass( OO.ui.mixin.TabIndexedElement );
1773 /* Methods */
1776 * Set the element that should use the tabindex functionality.
1778 * This method is used to retarget a tabindex mixin so that its functionality applies
1779 * to the specified element. If an element is currently using the functionality, the mixin’s
1780 * effect on that element is removed before the new element is set up.
1782 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
1783 * @chainable
1785 OO.ui.mixin.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
1786 var tabIndex = this.tabIndex;
1787 // Remove attributes from old $tabIndexed
1788 this.setTabIndex( null );
1789 // Force update of new $tabIndexed
1790 this.$tabIndexed = $tabIndexed;
1791 this.tabIndex = tabIndex;
1792 return this.updateTabIndex();
1796 * Set the value of the tabindex.
1798 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
1799 * @chainable
1801 OO.ui.mixin.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
1802 tabIndex = typeof tabIndex === 'number' ? tabIndex : null;
1804 if ( this.tabIndex !== tabIndex ) {
1805 this.tabIndex = tabIndex;
1806 this.updateTabIndex();
1809 return this;
1813 * Update the `tabindex` attribute, in case of changes to tab index or
1814 * disabled state.
1816 * @private
1817 * @chainable
1819 OO.ui.mixin.TabIndexedElement.prototype.updateTabIndex = function () {
1820 if ( this.$tabIndexed ) {
1821 if ( this.tabIndex !== null ) {
1822 // Do not index over disabled elements
1823 this.$tabIndexed.attr( {
1824 tabindex: this.isDisabled() ? -1 : this.tabIndex,
1825 // Support: ChromeVox and NVDA
1826 // These do not seem to inherit aria-disabled from parent elements
1827 'aria-disabled': this.isDisabled().toString()
1828 } );
1829 } else {
1830 this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
1833 return this;
1837 * Handle disable events.
1839 * @private
1840 * @param {boolean} disabled Element is disabled
1842 OO.ui.mixin.TabIndexedElement.prototype.onTabIndexedElementDisable = function () {
1843 this.updateTabIndex();
1847 * Get the value of the tabindex.
1849 * @return {number|null} Tabindex value
1851 OO.ui.mixin.TabIndexedElement.prototype.getTabIndex = function () {
1852 return this.tabIndex;
1856 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
1857 * interface element that can be configured with access keys for accessibility.
1858 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
1860 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
1862 * @abstract
1863 * @class
1865 * @constructor
1866 * @param {Object} [config] Configuration options
1867 * @cfg {jQuery} [$button] The button element created by the class.
1868 * If this configuration is omitted, the button element will use a generated `<a>`.
1869 * @cfg {boolean} [framed=true] Render the button with a frame
1871 OO.ui.mixin.ButtonElement = function OoUiMixinButtonElement( config ) {
1872 // Configuration initialization
1873 config = config || {};
1875 // Properties
1876 this.$button = null;
1877 this.framed = null;
1878 this.active = config.active !== undefined && config.active;
1879 this.onMouseUpHandler = this.onMouseUp.bind( this );
1880 this.onMouseDownHandler = this.onMouseDown.bind( this );
1881 this.onKeyDownHandler = this.onKeyDown.bind( this );
1882 this.onKeyUpHandler = this.onKeyUp.bind( this );
1883 this.onClickHandler = this.onClick.bind( this );
1884 this.onKeyPressHandler = this.onKeyPress.bind( this );
1886 // Initialization
1887 this.$element.addClass( 'oo-ui-buttonElement' );
1888 this.toggleFramed( config.framed === undefined || config.framed );
1889 this.setButtonElement( config.$button || $( '<a>' ) );
1892 /* Setup */
1894 OO.initClass( OO.ui.mixin.ButtonElement );
1896 /* Static Properties */
1899 * Cancel mouse down events.
1901 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
1902 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
1903 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
1904 * parent widget.
1906 * @static
1907 * @inheritable
1908 * @property {boolean}
1910 OO.ui.mixin.ButtonElement.static.cancelButtonMouseDownEvents = true;
1912 /* Events */
1915 * A 'click' event is emitted when the button element is clicked.
1917 * @event click
1920 /* Methods */
1923 * Set the button element.
1925 * This method is used to retarget a button mixin so that its functionality applies to
1926 * the specified button element instead of the one created by the class. If a button element
1927 * is already set, the method will remove the mixin’s effect on that element.
1929 * @param {jQuery} $button Element to use as button
1931 OO.ui.mixin.ButtonElement.prototype.setButtonElement = function ( $button ) {
1932 if ( this.$button ) {
1933 this.$button
1934 .removeClass( 'oo-ui-buttonElement-button' )
1935 .removeAttr( 'role accesskey' )
1936 .off( {
1937 mousedown: this.onMouseDownHandler,
1938 keydown: this.onKeyDownHandler,
1939 click: this.onClickHandler,
1940 keypress: this.onKeyPressHandler
1941 } );
1944 this.$button = $button
1945 .addClass( 'oo-ui-buttonElement-button' )
1946 .on( {
1947 mousedown: this.onMouseDownHandler,
1948 keydown: this.onKeyDownHandler,
1949 click: this.onClickHandler,
1950 keypress: this.onKeyPressHandler
1951 } );
1953 // Add `role="button"` on `<a>` elements, where it's needed
1954 // `toUppercase()` is added for XHTML documents
1955 if ( this.$button.prop( 'tagName' ).toUpperCase() === 'A' ) {
1956 this.$button.attr( 'role', 'button' );
1961 * Handles mouse down events.
1963 * @protected
1964 * @param {jQuery.Event} e Mouse down event
1966 OO.ui.mixin.ButtonElement.prototype.onMouseDown = function ( e ) {
1967 if ( this.isDisabled() || e.which !== OO.ui.MouseButtons.LEFT ) {
1968 return;
1970 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
1971 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
1972 // reliably remove the pressed class
1973 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true );
1974 // Prevent change of focus unless specifically configured otherwise
1975 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
1976 return false;
1981 * Handles mouse up events.
1983 * @protected
1984 * @param {MouseEvent} e Mouse up event
1986 OO.ui.mixin.ButtonElement.prototype.onMouseUp = function ( e ) {
1987 if ( this.isDisabled() || e.which !== OO.ui.MouseButtons.LEFT ) {
1988 return;
1990 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
1991 // Stop listening for mouseup, since we only needed this once
1992 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true );
1996 * Handles mouse click events.
1998 * @protected
1999 * @param {jQuery.Event} e Mouse click event
2000 * @fires click
2002 OO.ui.mixin.ButtonElement.prototype.onClick = function ( e ) {
2003 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
2004 if ( this.emit( 'click' ) ) {
2005 return false;
2011 * Handles key down events.
2013 * @protected
2014 * @param {jQuery.Event} e Key down event
2016 OO.ui.mixin.ButtonElement.prototype.onKeyDown = function ( e ) {
2017 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
2018 return;
2020 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
2021 // Run the keyup handler no matter where the key is when the button is let go, so we can
2022 // reliably remove the pressed class
2023 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler, true );
2027 * Handles key up events.
2029 * @protected
2030 * @param {KeyboardEvent} e Key up event
2032 OO.ui.mixin.ButtonElement.prototype.onKeyUp = function ( e ) {
2033 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
2034 return;
2036 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
2037 // Stop listening for keyup, since we only needed this once
2038 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler, true );
2042 * Handles key press events.
2044 * @protected
2045 * @param {jQuery.Event} e Key press event
2046 * @fires click
2048 OO.ui.mixin.ButtonElement.prototype.onKeyPress = function ( e ) {
2049 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
2050 if ( this.emit( 'click' ) ) {
2051 return false;
2057 * Check if button has a frame.
2059 * @return {boolean} Button is framed
2061 OO.ui.mixin.ButtonElement.prototype.isFramed = function () {
2062 return this.framed;
2066 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
2068 * @param {boolean} [framed] Make button framed, omit to toggle
2069 * @chainable
2071 OO.ui.mixin.ButtonElement.prototype.toggleFramed = function ( framed ) {
2072 framed = framed === undefined ? !this.framed : !!framed;
2073 if ( framed !== this.framed ) {
2074 this.framed = framed;
2075 this.$element
2076 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
2077 .toggleClass( 'oo-ui-buttonElement-framed', framed );
2078 this.updateThemeClasses();
2081 return this;
2085 * Set the button's active state.
2087 * The active state can be set on:
2089 * - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected
2090 * - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on
2091 * - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page
2093 * @protected
2094 * @param {boolean} value Make button active
2095 * @chainable
2097 OO.ui.mixin.ButtonElement.prototype.setActive = function ( value ) {
2098 this.active = !!value;
2099 this.$element.toggleClass( 'oo-ui-buttonElement-active', this.active );
2100 this.updateThemeClasses();
2101 return this;
2105 * Check if the button is active
2107 * @protected
2108 * @return {boolean} The button is active
2110 OO.ui.mixin.ButtonElement.prototype.isActive = function () {
2111 return this.active;
2115 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
2116 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
2117 * items from the group is done through the interface the class provides.
2118 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2120 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
2122 * @abstract
2123 * @class
2125 * @constructor
2126 * @param {Object} [config] Configuration options
2127 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
2128 * is omitted, the group element will use a generated `<div>`.
2130 OO.ui.mixin.GroupElement = function OoUiMixinGroupElement( config ) {
2131 // Configuration initialization
2132 config = config || {};
2134 // Properties
2135 this.$group = null;
2136 this.items = [];
2137 this.aggregateItemEvents = {};
2139 // Initialization
2140 this.setGroupElement( config.$group || $( '<div>' ) );
2143 /* Events */
2146 * @event change
2148 * A change event is emitted when the set of selected items changes.
2150 * @param {OO.ui.Element[]} items Items currently in the group
2153 /* Methods */
2156 * Set the group element.
2158 * If an element is already set, items will be moved to the new element.
2160 * @param {jQuery} $group Element to use as group
2162 OO.ui.mixin.GroupElement.prototype.setGroupElement = function ( $group ) {
2163 var i, len;
2165 this.$group = $group;
2166 for ( i = 0, len = this.items.length; i < len; i++ ) {
2167 this.$group.append( this.items[ i ].$element );
2172 * Check if a group contains no items.
2174 * @return {boolean} Group is empty
2176 OO.ui.mixin.GroupElement.prototype.isEmpty = function () {
2177 return !this.items.length;
2181 * Get all items in the group.
2183 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
2184 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
2185 * from a group).
2187 * @return {OO.ui.Element[]} An array of items.
2189 OO.ui.mixin.GroupElement.prototype.getItems = function () {
2190 return this.items.slice( 0 );
2194 * Get an item by its data.
2196 * Only the first item with matching data will be returned. To return all matching items,
2197 * use the #getItemsFromData method.
2199 * @param {Object} data Item data to search for
2200 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2202 OO.ui.mixin.GroupElement.prototype.getItemFromData = function ( data ) {
2203 var i, len, item,
2204 hash = OO.getHash( data );
2206 for ( i = 0, len = this.items.length; i < len; i++ ) {
2207 item = this.items[ i ];
2208 if ( hash === OO.getHash( item.getData() ) ) {
2209 return item;
2213 return null;
2217 * Get items by their data.
2219 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
2221 * @param {Object} data Item data to search for
2222 * @return {OO.ui.Element[]} Items with equivalent data
2224 OO.ui.mixin.GroupElement.prototype.getItemsFromData = function ( data ) {
2225 var i, len, item,
2226 hash = OO.getHash( data ),
2227 items = [];
2229 for ( i = 0, len = this.items.length; i < len; i++ ) {
2230 item = this.items[ i ];
2231 if ( hash === OO.getHash( item.getData() ) ) {
2232 items.push( item );
2236 return items;
2240 * Aggregate the events emitted by the group.
2242 * When events are aggregated, the group will listen to all contained items for the event,
2243 * and then emit the event under a new name. The new event will contain an additional leading
2244 * parameter containing the item that emitted the original event. Other arguments emitted from
2245 * the original event are passed through.
2247 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
2248 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
2249 * A `null` value will remove aggregated events.
2251 * @throws {Error} An error is thrown if aggregation already exists.
2253 OO.ui.mixin.GroupElement.prototype.aggregate = function ( events ) {
2254 var i, len, item, add, remove, itemEvent, groupEvent;
2256 for ( itemEvent in events ) {
2257 groupEvent = events[ itemEvent ];
2259 // Remove existing aggregated event
2260 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
2261 // Don't allow duplicate aggregations
2262 if ( groupEvent ) {
2263 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
2265 // Remove event aggregation from existing items
2266 for ( i = 0, len = this.items.length; i < len; i++ ) {
2267 item = this.items[ i ];
2268 if ( item.connect && item.disconnect ) {
2269 remove = {};
2270 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
2271 item.disconnect( this, remove );
2274 // Prevent future items from aggregating event
2275 delete this.aggregateItemEvents[ itemEvent ];
2278 // Add new aggregate event
2279 if ( groupEvent ) {
2280 // Make future items aggregate event
2281 this.aggregateItemEvents[ itemEvent ] = groupEvent;
2282 // Add event aggregation to existing items
2283 for ( i = 0, len = this.items.length; i < len; i++ ) {
2284 item = this.items[ i ];
2285 if ( item.connect && item.disconnect ) {
2286 add = {};
2287 add[ itemEvent ] = [ 'emit', groupEvent, item ];
2288 item.connect( this, add );
2296 * Add items to the group.
2298 * Items will be added to the end of the group array unless the optional `index` parameter specifies
2299 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
2301 * @param {OO.ui.Element[]} items An array of items to add to the group
2302 * @param {number} [index] Index of the insertion point
2303 * @chainable
2305 OO.ui.mixin.GroupElement.prototype.addItems = function ( items, index ) {
2306 var i, len, item, itemEvent, events, currentIndex,
2307 itemElements = [];
2309 for ( i = 0, len = items.length; i < len; i++ ) {
2310 item = items[ i ];
2312 // Check if item exists then remove it first, effectively "moving" it
2313 currentIndex = this.items.indexOf( item );
2314 if ( currentIndex >= 0 ) {
2315 this.removeItems( [ item ] );
2316 // Adjust index to compensate for removal
2317 if ( currentIndex < index ) {
2318 index--;
2321 // Add the item
2322 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
2323 events = {};
2324 for ( itemEvent in this.aggregateItemEvents ) {
2325 events[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
2327 item.connect( this, events );
2329 item.setElementGroup( this );
2330 itemElements.push( item.$element.get( 0 ) );
2333 if ( index === undefined || index < 0 || index >= this.items.length ) {
2334 this.$group.append( itemElements );
2335 this.items.push.apply( this.items, items );
2336 } else if ( index === 0 ) {
2337 this.$group.prepend( itemElements );
2338 this.items.unshift.apply( this.items, items );
2339 } else {
2340 this.items[ index ].$element.before( itemElements );
2341 this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
2344 this.emit( 'change', this.getItems() );
2345 return this;
2349 * Remove the specified items from a group.
2351 * Removed items are detached (not removed) from the DOM so that they may be reused.
2352 * To remove all items from a group, you may wish to use the #clearItems method instead.
2354 * @param {OO.ui.Element[]} items An array of items to remove
2355 * @chainable
2357 OO.ui.mixin.GroupElement.prototype.removeItems = function ( items ) {
2358 var i, len, item, index, events, itemEvent;
2360 // Remove specific items
2361 for ( i = 0, len = items.length; i < len; i++ ) {
2362 item = items[ i ];
2363 index = this.items.indexOf( item );
2364 if ( index !== -1 ) {
2365 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
2366 events = {};
2367 for ( itemEvent in this.aggregateItemEvents ) {
2368 events[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
2370 item.disconnect( this, events );
2372 item.setElementGroup( null );
2373 this.items.splice( index, 1 );
2374 item.$element.detach();
2378 this.emit( 'change', this.getItems() );
2379 return this;
2383 * Clear all items from the group.
2385 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2386 * To remove only a subset of items from a group, use the #removeItems method.
2388 * @chainable
2390 OO.ui.mixin.GroupElement.prototype.clearItems = function () {
2391 var i, len, item, remove, itemEvent;
2393 // Remove all items
2394 for ( i = 0, len = this.items.length; i < len; i++ ) {
2395 item = this.items[ i ];
2396 if (
2397 item.connect && item.disconnect &&
2398 !$.isEmptyObject( this.aggregateItemEvents )
2400 remove = {};
2401 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
2402 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
2404 item.disconnect( this, remove );
2406 item.setElementGroup( null );
2407 item.$element.detach();
2410 this.emit( 'change', this.getItems() );
2411 this.items = [];
2412 return this;
2416 * IconElement is often mixed into other classes to generate an icon.
2417 * Icons are graphics, about the size of normal text. They are used to aid the user
2418 * in locating a control or to convey information in a space-efficient way. See the
2419 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
2420 * included in the library.
2422 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2424 * @abstract
2425 * @class
2427 * @constructor
2428 * @param {Object} [config] Configuration options
2429 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2430 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2431 * the icon element be set to an existing icon instead of the one generated by this class, set a
2432 * value using a jQuery selection. For example:
2434 * // Use a <div> tag instead of a <span>
2435 * $icon: $("<div>")
2436 * // Use an existing icon element instead of the one generated by the class
2437 * $icon: this.$element
2438 * // Use an icon element from a child widget
2439 * $icon: this.childwidget.$element
2440 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
2441 * symbolic names. A map is used for i18n purposes and contains a `default` icon
2442 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
2443 * by the user's language.
2445 * Example of an i18n map:
2447 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2448 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
2449 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2450 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
2451 * text. The icon title is displayed when users move the mouse over the icon.
2453 OO.ui.mixin.IconElement = function OoUiMixinIconElement( config ) {
2454 // Configuration initialization
2455 config = config || {};
2457 // Properties
2458 this.$icon = null;
2459 this.icon = null;
2460 this.iconTitle = null;
2462 // Initialization
2463 this.setIcon( config.icon || this.constructor.static.icon );
2464 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
2465 this.setIconElement( config.$icon || $( '<span>' ) );
2468 /* Setup */
2470 OO.initClass( OO.ui.mixin.IconElement );
2472 /* Static Properties */
2475 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
2476 * for i18n purposes and contains a `default` icon name and additional names keyed by
2477 * language code. The `default` name is used when no icon is keyed by the user's language.
2479 * Example of an i18n map:
2481 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2483 * Note: the static property will be overridden if the #icon configuration is used.
2485 * @static
2486 * @inheritable
2487 * @property {Object|string}
2489 OO.ui.mixin.IconElement.static.icon = null;
2492 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2493 * function that returns title text, or `null` for no title.
2495 * The static property will be overridden if the #iconTitle configuration is used.
2497 * @static
2498 * @inheritable
2499 * @property {string|Function|null}
2501 OO.ui.mixin.IconElement.static.iconTitle = null;
2503 /* Methods */
2506 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2507 * applies to the specified icon element instead of the one created by the class. If an icon
2508 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2509 * and mixin methods will no longer affect the element.
2511 * @param {jQuery} $icon Element to use as icon
2513 OO.ui.mixin.IconElement.prototype.setIconElement = function ( $icon ) {
2514 if ( this.$icon ) {
2515 this.$icon
2516 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
2517 .removeAttr( 'title' );
2520 this.$icon = $icon
2521 .addClass( 'oo-ui-iconElement-icon' )
2522 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
2523 if ( this.iconTitle !== null ) {
2524 this.$icon.attr( 'title', this.iconTitle );
2527 this.updateThemeClasses();
2531 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
2532 * The icon parameter can also be set to a map of icon names. See the #icon config setting
2533 * for an example.
2535 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
2536 * by language code, or `null` to remove the icon.
2537 * @chainable
2539 OO.ui.mixin.IconElement.prototype.setIcon = function ( icon ) {
2540 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
2541 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
2543 if ( this.icon !== icon ) {
2544 if ( this.$icon ) {
2545 if ( this.icon !== null ) {
2546 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
2548 if ( icon !== null ) {
2549 this.$icon.addClass( 'oo-ui-icon-' + icon );
2552 this.icon = icon;
2555 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
2556 this.updateThemeClasses();
2558 return this;
2562 * Set the icon title. Use `null` to remove the title.
2564 * @param {string|Function|null} iconTitle A text string used as the icon title,
2565 * a function that returns title text, or `null` for no title.
2566 * @chainable
2568 OO.ui.mixin.IconElement.prototype.setIconTitle = function ( iconTitle ) {
2569 iconTitle = typeof iconTitle === 'function' ||
2570 ( typeof iconTitle === 'string' && iconTitle.length ) ?
2571 OO.ui.resolveMsg( iconTitle ) : null;
2573 if ( this.iconTitle !== iconTitle ) {
2574 this.iconTitle = iconTitle;
2575 if ( this.$icon ) {
2576 if ( this.iconTitle !== null ) {
2577 this.$icon.attr( 'title', iconTitle );
2578 } else {
2579 this.$icon.removeAttr( 'title' );
2584 return this;
2588 * Get the symbolic name of the icon.
2590 * @return {string} Icon name
2592 OO.ui.mixin.IconElement.prototype.getIcon = function () {
2593 return this.icon;
2597 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
2599 * @return {string} Icon title text
2601 OO.ui.mixin.IconElement.prototype.getIconTitle = function () {
2602 return this.iconTitle;
2606 * IndicatorElement is often mixed into other classes to generate an indicator.
2607 * Indicators are small graphics that are generally used in two ways:
2609 * - To draw attention to the status of an item. For example, an indicator might be
2610 * used to show that an item in a list has errors that need to be resolved.
2611 * - To clarify the function of a control that acts in an exceptional way (a button
2612 * that opens a menu instead of performing an action directly, for example).
2614 * For a list of indicators included in the library, please see the
2615 * [OOjs UI documentation on MediaWiki] [1].
2617 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2619 * @abstract
2620 * @class
2622 * @constructor
2623 * @param {Object} [config] Configuration options
2624 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
2625 * configuration is omitted, the indicator element will use a generated `<span>`.
2626 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2627 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
2628 * in the library.
2629 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2630 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
2631 * or a function that returns title text. The indicator title is displayed when users move
2632 * the mouse over the indicator.
2634 OO.ui.mixin.IndicatorElement = function OoUiMixinIndicatorElement( config ) {
2635 // Configuration initialization
2636 config = config || {};
2638 // Properties
2639 this.$indicator = null;
2640 this.indicator = null;
2641 this.indicatorTitle = null;
2643 // Initialization
2644 this.setIndicator( config.indicator || this.constructor.static.indicator );
2645 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
2646 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
2649 /* Setup */
2651 OO.initClass( OO.ui.mixin.IndicatorElement );
2653 /* Static Properties */
2656 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2657 * The static property will be overridden if the #indicator configuration is used.
2659 * @static
2660 * @inheritable
2661 * @property {string|null}
2663 OO.ui.mixin.IndicatorElement.static.indicator = null;
2666 * A text string used as the indicator title, a function that returns title text, or `null`
2667 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
2669 * @static
2670 * @inheritable
2671 * @property {string|Function|null}
2673 OO.ui.mixin.IndicatorElement.static.indicatorTitle = null;
2675 /* Methods */
2678 * Set the indicator element.
2680 * If an element is already set, it will be cleaned up before setting up the new element.
2682 * @param {jQuery} $indicator Element to use as indicator
2684 OO.ui.mixin.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
2685 if ( this.$indicator ) {
2686 this.$indicator
2687 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
2688 .removeAttr( 'title' );
2691 this.$indicator = $indicator
2692 .addClass( 'oo-ui-indicatorElement-indicator' )
2693 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
2694 if ( this.indicatorTitle !== null ) {
2695 this.$indicator.attr( 'title', this.indicatorTitle );
2698 this.updateThemeClasses();
2702 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
2704 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
2705 * @chainable
2707 OO.ui.mixin.IndicatorElement.prototype.setIndicator = function ( indicator ) {
2708 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
2710 if ( this.indicator !== indicator ) {
2711 if ( this.$indicator ) {
2712 if ( this.indicator !== null ) {
2713 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
2715 if ( indicator !== null ) {
2716 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
2719 this.indicator = indicator;
2722 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
2723 this.updateThemeClasses();
2725 return this;
2729 * Set the indicator title.
2731 * The title is displayed when a user moves the mouse over the indicator.
2733 * @param {string|Function|null} indicatorTitle Indicator title text, a function that returns text, or
2734 * `null` for no indicator title
2735 * @chainable
2737 OO.ui.mixin.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
2738 indicatorTitle = typeof indicatorTitle === 'function' ||
2739 ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ?
2740 OO.ui.resolveMsg( indicatorTitle ) : null;
2742 if ( this.indicatorTitle !== indicatorTitle ) {
2743 this.indicatorTitle = indicatorTitle;
2744 if ( this.$indicator ) {
2745 if ( this.indicatorTitle !== null ) {
2746 this.$indicator.attr( 'title', indicatorTitle );
2747 } else {
2748 this.$indicator.removeAttr( 'title' );
2753 return this;
2757 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2759 * @return {string} Symbolic name of indicator
2761 OO.ui.mixin.IndicatorElement.prototype.getIndicator = function () {
2762 return this.indicator;
2766 * Get the indicator title.
2768 * The title is displayed when a user moves the mouse over the indicator.
2770 * @return {string} Indicator title text
2772 OO.ui.mixin.IndicatorElement.prototype.getIndicatorTitle = function () {
2773 return this.indicatorTitle;
2777 * LabelElement is often mixed into other classes to generate a label, which
2778 * helps identify the function of an interface element.
2779 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
2781 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2783 * @abstract
2784 * @class
2786 * @constructor
2787 * @param {Object} [config] Configuration options
2788 * @cfg {jQuery} [$label] The label element created by the class. If this
2789 * configuration is omitted, the label element will use a generated `<span>`.
2790 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
2791 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
2792 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
2793 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2795 OO.ui.mixin.LabelElement = function OoUiMixinLabelElement( config ) {
2796 // Configuration initialization
2797 config = config || {};
2799 // Properties
2800 this.$label = null;
2801 this.label = null;
2803 // Initialization
2804 this.setLabel( config.label || this.constructor.static.label );
2805 this.setLabelElement( config.$label || $( '<span>' ) );
2808 /* Setup */
2810 OO.initClass( OO.ui.mixin.LabelElement );
2812 /* Events */
2815 * @event labelChange
2816 * @param {string} value
2819 /* Static Properties */
2822 * The label text. The label can be specified as a plaintext string, a function that will
2823 * produce a string in the future, or `null` for no label. The static value will
2824 * be overridden if a label is specified with the #label config option.
2826 * @static
2827 * @inheritable
2828 * @property {string|Function|null}
2830 OO.ui.mixin.LabelElement.static.label = null;
2832 /* Static methods */
2835 * Highlight the first occurrence of the query in the given text
2837 * @param {string} text Text
2838 * @param {string} query Query to find
2839 * @return {jQuery} Text with the first match of the query
2840 * sub-string wrapped in highlighted span
2842 OO.ui.mixin.LabelElement.static.highlightQuery = function ( text, query ) {
2843 var $result = $( '<span>' ),
2844 offset = text.toLowerCase().indexOf( query.toLowerCase() );
2846 if ( !query.length || offset === -1 ) {
2847 return $result.text( text );
2849 $result.append(
2850 document.createTextNode( text.slice( 0, offset ) ),
2851 $( '<span>' )
2852 .addClass( 'oo-ui-labelElement-label-highlight' )
2853 .text( text.slice( offset, offset + query.length ) ),
2854 document.createTextNode( text.slice( offset + query.length ) )
2856 return $result.contents();
2859 /* Methods */
2862 * Set the label element.
2864 * If an element is already set, it will be cleaned up before setting up the new element.
2866 * @param {jQuery} $label Element to use as label
2868 OO.ui.mixin.LabelElement.prototype.setLabelElement = function ( $label ) {
2869 if ( this.$label ) {
2870 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
2873 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
2874 this.setLabelContent( this.label );
2878 * Set the label.
2880 * An empty string will result in the label being hidden. A string containing only whitespace will
2881 * be converted to a single `&nbsp;`.
2883 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
2884 * text; or null for no label
2885 * @chainable
2887 OO.ui.mixin.LabelElement.prototype.setLabel = function ( label ) {
2888 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
2889 label = ( ( typeof label === 'string' || label instanceof jQuery ) && label.length ) || ( label instanceof OO.ui.HtmlSnippet && label.toString().length ) ? label : null;
2891 if ( this.label !== label ) {
2892 if ( this.$label ) {
2893 this.setLabelContent( label );
2895 this.label = label;
2896 this.emit( 'labelChange' );
2899 this.$element.toggleClass( 'oo-ui-labelElement', !!this.label );
2901 return this;
2905 * Set the label as plain text with a highlighted query
2907 * @param {string} text Text label to set
2908 * @param {string} query Substring of text to highlight
2909 * @chainable
2911 OO.ui.mixin.LabelElement.prototype.setHighlightedQuery = function ( text, query ) {
2912 return this.setLabel( this.constructor.static.highlightQuery( text, query ) );
2916 * Get the label.
2918 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
2919 * text; or null for no label
2921 OO.ui.mixin.LabelElement.prototype.getLabel = function () {
2922 return this.label;
2926 * Fit the label.
2928 * @chainable
2929 * @deprecated since 0.16.0
2931 OO.ui.mixin.LabelElement.prototype.fitLabel = function () {
2932 OO.ui.warnDeprecation( 'LabelElement#fitLabel: This is a deprecated no-op.' );
2933 return this;
2937 * Set the content of the label.
2939 * Do not call this method until after the label element has been set by #setLabelElement.
2941 * @private
2942 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
2943 * text; or null for no label
2945 OO.ui.mixin.LabelElement.prototype.setLabelContent = function ( label ) {
2946 if ( typeof label === 'string' ) {
2947 if ( label.match( /^\s*$/ ) ) {
2948 // Convert whitespace only string to a single non-breaking space
2949 this.$label.html( '&nbsp;' );
2950 } else {
2951 this.$label.text( label );
2953 } else if ( label instanceof OO.ui.HtmlSnippet ) {
2954 this.$label.html( label.toString() );
2955 } else if ( label instanceof jQuery ) {
2956 this.$label.empty().append( label );
2957 } else {
2958 this.$label.empty();
2963 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
2964 * additional functionality to an element created by another class. The class provides
2965 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
2966 * which are used to customize the look and feel of a widget to better describe its
2967 * importance and functionality.
2969 * The library currently contains the following styling flags for general use:
2971 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
2972 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
2973 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
2975 * The flags affect the appearance of the buttons:
2977 * @example
2978 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
2979 * var button1 = new OO.ui.ButtonWidget( {
2980 * label: 'Constructive',
2981 * flags: 'constructive'
2982 * } );
2983 * var button2 = new OO.ui.ButtonWidget( {
2984 * label: 'Destructive',
2985 * flags: 'destructive'
2986 * } );
2987 * var button3 = new OO.ui.ButtonWidget( {
2988 * label: 'Progressive',
2989 * flags: 'progressive'
2990 * } );
2991 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
2993 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
2994 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
2996 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
2998 * @abstract
2999 * @class
3001 * @constructor
3002 * @param {Object} [config] Configuration options
3003 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
3004 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
3005 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
3006 * @cfg {jQuery} [$flagged] The flagged element. By default,
3007 * the flagged functionality is applied to the element created by the class ($element).
3008 * If a different element is specified, the flagged functionality will be applied to it instead.
3010 OO.ui.mixin.FlaggedElement = function OoUiMixinFlaggedElement( config ) {
3011 // Configuration initialization
3012 config = config || {};
3014 // Properties
3015 this.flags = {};
3016 this.$flagged = null;
3018 // Initialization
3019 this.setFlags( config.flags );
3020 this.setFlaggedElement( config.$flagged || this.$element );
3023 /* Events */
3026 * @event flag
3027 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
3028 * parameter contains the name of each modified flag and indicates whether it was
3029 * added or removed.
3031 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
3032 * that the flag was added, `false` that the flag was removed.
3035 /* Methods */
3038 * Set the flagged element.
3040 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
3041 * If an element is already set, the method will remove the mixin’s effect on that element.
3043 * @param {jQuery} $flagged Element that should be flagged
3045 OO.ui.mixin.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
3046 var classNames = Object.keys( this.flags ).map( function ( flag ) {
3047 return 'oo-ui-flaggedElement-' + flag;
3048 } ).join( ' ' );
3050 if ( this.$flagged ) {
3051 this.$flagged.removeClass( classNames );
3054 this.$flagged = $flagged.addClass( classNames );
3058 * Check if the specified flag is set.
3060 * @param {string} flag Name of flag
3061 * @return {boolean} The flag is set
3063 OO.ui.mixin.FlaggedElement.prototype.hasFlag = function ( flag ) {
3064 // This may be called before the constructor, thus before this.flags is set
3065 return this.flags && ( flag in this.flags );
3069 * Get the names of all flags set.
3071 * @return {string[]} Flag names
3073 OO.ui.mixin.FlaggedElement.prototype.getFlags = function () {
3074 // This may be called before the constructor, thus before this.flags is set
3075 return Object.keys( this.flags || {} );
3079 * Clear all flags.
3081 * @chainable
3082 * @fires flag
3084 OO.ui.mixin.FlaggedElement.prototype.clearFlags = function () {
3085 var flag, className,
3086 changes = {},
3087 remove = [],
3088 classPrefix = 'oo-ui-flaggedElement-';
3090 for ( flag in this.flags ) {
3091 className = classPrefix + flag;
3092 changes[ flag ] = false;
3093 delete this.flags[ flag ];
3094 remove.push( className );
3097 if ( this.$flagged ) {
3098 this.$flagged.removeClass( remove.join( ' ' ) );
3101 this.updateThemeClasses();
3102 this.emit( 'flag', changes );
3104 return this;
3108 * Add one or more flags.
3110 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
3111 * or an object keyed by flag name with a boolean value that indicates whether the flag should
3112 * be added (`true`) or removed (`false`).
3113 * @chainable
3114 * @fires flag
3116 OO.ui.mixin.FlaggedElement.prototype.setFlags = function ( flags ) {
3117 var i, len, flag, className,
3118 changes = {},
3119 add = [],
3120 remove = [],
3121 classPrefix = 'oo-ui-flaggedElement-';
3123 if ( typeof flags === 'string' ) {
3124 className = classPrefix + flags;
3125 // Set
3126 if ( !this.flags[ flags ] ) {
3127 this.flags[ flags ] = true;
3128 add.push( className );
3130 } else if ( Array.isArray( flags ) ) {
3131 for ( i = 0, len = flags.length; i < len; i++ ) {
3132 flag = flags[ i ];
3133 className = classPrefix + flag;
3134 // Set
3135 if ( !this.flags[ flag ] ) {
3136 changes[ flag ] = true;
3137 this.flags[ flag ] = true;
3138 add.push( className );
3141 } else if ( OO.isPlainObject( flags ) ) {
3142 for ( flag in flags ) {
3143 className = classPrefix + flag;
3144 if ( flags[ flag ] ) {
3145 // Set
3146 if ( !this.flags[ flag ] ) {
3147 changes[ flag ] = true;
3148 this.flags[ flag ] = true;
3149 add.push( className );
3151 } else {
3152 // Remove
3153 if ( this.flags[ flag ] ) {
3154 changes[ flag ] = false;
3155 delete this.flags[ flag ];
3156 remove.push( className );
3162 if ( this.$flagged ) {
3163 this.$flagged
3164 .addClass( add.join( ' ' ) )
3165 .removeClass( remove.join( ' ' ) );
3168 this.updateThemeClasses();
3169 this.emit( 'flag', changes );
3171 return this;
3175 * TitledElement is mixed into other classes to provide a `title` attribute.
3176 * Titles are rendered by the browser and are made visible when the user moves
3177 * the mouse over the element. Titles are not visible on touch devices.
3179 * @example
3180 * // TitledElement provides a 'title' attribute to the
3181 * // ButtonWidget class
3182 * var button = new OO.ui.ButtonWidget( {
3183 * label: 'Button with Title',
3184 * title: 'I am a button'
3185 * } );
3186 * $( 'body' ).append( button.$element );
3188 * @abstract
3189 * @class
3191 * @constructor
3192 * @param {Object} [config] Configuration options
3193 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
3194 * If this config is omitted, the title functionality is applied to $element, the
3195 * element created by the class.
3196 * @cfg {string|Function} [title] The title text or a function that returns text. If
3197 * this config is omitted, the value of the {@link #static-title static title} property is used.
3199 OO.ui.mixin.TitledElement = function OoUiMixinTitledElement( config ) {
3200 // Configuration initialization
3201 config = config || {};
3203 // Properties
3204 this.$titled = null;
3205 this.title = null;
3207 // Initialization
3208 this.setTitle( config.title !== undefined ? config.title : this.constructor.static.title );
3209 this.setTitledElement( config.$titled || this.$element );
3212 /* Setup */
3214 OO.initClass( OO.ui.mixin.TitledElement );
3216 /* Static Properties */
3219 * The title text, a function that returns text, or `null` for no title. The value of the static property
3220 * is overridden if the #title config option is used.
3222 * @static
3223 * @inheritable
3224 * @property {string|Function|null}
3226 OO.ui.mixin.TitledElement.static.title = null;
3228 /* Methods */
3231 * Set the titled element.
3233 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
3234 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
3236 * @param {jQuery} $titled Element that should use the 'titled' functionality
3238 OO.ui.mixin.TitledElement.prototype.setTitledElement = function ( $titled ) {
3239 if ( this.$titled ) {
3240 this.$titled.removeAttr( 'title' );
3243 this.$titled = $titled;
3244 if ( this.title ) {
3245 this.$titled.attr( 'title', this.title );
3250 * Set title.
3252 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
3253 * @chainable
3255 OO.ui.mixin.TitledElement.prototype.setTitle = function ( title ) {
3256 title = typeof title === 'function' ? OO.ui.resolveMsg( title ) : title;
3257 title = ( typeof title === 'string' && title.length ) ? title : null;
3259 if ( this.title !== title ) {
3260 if ( this.$titled ) {
3261 if ( title !== null ) {
3262 this.$titled.attr( 'title', title );
3263 } else {
3264 this.$titled.removeAttr( 'title' );
3267 this.title = title;
3270 return this;
3274 * Get title.
3276 * @return {string} Title string
3278 OO.ui.mixin.TitledElement.prototype.getTitle = function () {
3279 return this.title;
3283 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
3284 * Accesskeys allow an user to go to a specific element by using
3285 * a shortcut combination of a browser specific keys + the key
3286 * set to the field.
3288 * @example
3289 * // AccessKeyedElement provides an 'accesskey' attribute to the
3290 * // ButtonWidget class
3291 * var button = new OO.ui.ButtonWidget( {
3292 * label: 'Button with Accesskey',
3293 * accessKey: 'k'
3294 * } );
3295 * $( 'body' ).append( button.$element );
3297 * @abstract
3298 * @class
3300 * @constructor
3301 * @param {Object} [config] Configuration options
3302 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3303 * If this config is omitted, the accesskey functionality is applied to $element, the
3304 * element created by the class.
3305 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3306 * this config is omitted, no accesskey will be added.
3308 OO.ui.mixin.AccessKeyedElement = function OoUiMixinAccessKeyedElement( config ) {
3309 // Configuration initialization
3310 config = config || {};
3312 // Properties
3313 this.$accessKeyed = null;
3314 this.accessKey = null;
3316 // Initialization
3317 this.setAccessKey( config.accessKey || null );
3318 this.setAccessKeyedElement( config.$accessKeyed || this.$element );
3321 /* Setup */
3323 OO.initClass( OO.ui.mixin.AccessKeyedElement );
3325 /* Static Properties */
3328 * The access key, a function that returns a key, or `null` for no accesskey.
3330 * @static
3331 * @inheritable
3332 * @property {string|Function|null}
3334 OO.ui.mixin.AccessKeyedElement.static.accessKey = null;
3336 /* Methods */
3339 * Set the accesskeyed element.
3341 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
3342 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
3344 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
3346 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKeyedElement = function ( $accessKeyed ) {
3347 if ( this.$accessKeyed ) {
3348 this.$accessKeyed.removeAttr( 'accesskey' );
3351 this.$accessKeyed = $accessKeyed;
3352 if ( this.accessKey ) {
3353 this.$accessKeyed.attr( 'accesskey', this.accessKey );
3358 * Set accesskey.
3360 * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no accesskey
3361 * @chainable
3363 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKey = function ( accessKey ) {
3364 accessKey = typeof accessKey === 'string' ? OO.ui.resolveMsg( accessKey ) : null;
3366 if ( this.accessKey !== accessKey ) {
3367 if ( this.$accessKeyed ) {
3368 if ( accessKey !== null ) {
3369 this.$accessKeyed.attr( 'accesskey', accessKey );
3370 } else {
3371 this.$accessKeyed.removeAttr( 'accesskey' );
3374 this.accessKey = accessKey;
3377 return this;
3381 * Get accesskey.
3383 * @return {string} accessKey string
3385 OO.ui.mixin.AccessKeyedElement.prototype.getAccessKey = function () {
3386 return this.accessKey;
3390 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3391 * feels, and functionality can be customized via the class’s configuration options
3392 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
3393 * and examples.
3395 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
3397 * @example
3398 * // A button widget
3399 * var button = new OO.ui.ButtonWidget( {
3400 * label: 'Button with Icon',
3401 * icon: 'remove',
3402 * iconTitle: 'Remove'
3403 * } );
3404 * $( 'body' ).append( button.$element );
3406 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3408 * @class
3409 * @extends OO.ui.Widget
3410 * @mixins OO.ui.mixin.ButtonElement
3411 * @mixins OO.ui.mixin.IconElement
3412 * @mixins OO.ui.mixin.IndicatorElement
3413 * @mixins OO.ui.mixin.LabelElement
3414 * @mixins OO.ui.mixin.TitledElement
3415 * @mixins OO.ui.mixin.FlaggedElement
3416 * @mixins OO.ui.mixin.TabIndexedElement
3417 * @mixins OO.ui.mixin.AccessKeyedElement
3419 * @constructor
3420 * @param {Object} [config] Configuration options
3421 * @cfg {boolean} [active=false] Whether button should be shown as active
3422 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3423 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3424 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3426 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
3427 // Configuration initialization
3428 config = config || {};
3430 // Parent constructor
3431 OO.ui.ButtonWidget.parent.call( this, config );
3433 // Mixin constructors
3434 OO.ui.mixin.ButtonElement.call( this, config );
3435 OO.ui.mixin.IconElement.call( this, config );
3436 OO.ui.mixin.IndicatorElement.call( this, config );
3437 OO.ui.mixin.LabelElement.call( this, config );
3438 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
3439 OO.ui.mixin.FlaggedElement.call( this, config );
3440 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
3441 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$button } ) );
3443 // Properties
3444 this.href = null;
3445 this.target = null;
3446 this.noFollow = false;
3448 // Events
3449 this.connect( this, { disable: 'onDisable' } );
3451 // Initialization
3452 this.$button.append( this.$icon, this.$label, this.$indicator );
3453 this.$element
3454 .addClass( 'oo-ui-buttonWidget' )
3455 .append( this.$button );
3456 this.setActive( config.active );
3457 this.setHref( config.href );
3458 this.setTarget( config.target );
3459 this.setNoFollow( config.noFollow );
3462 /* Setup */
3464 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
3465 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.ButtonElement );
3466 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IconElement );
3467 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IndicatorElement );
3468 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.LabelElement );
3469 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TitledElement );
3470 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.FlaggedElement );
3471 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TabIndexedElement );
3472 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.AccessKeyedElement );
3474 /* Static Properties */
3477 * @inheritdoc
3479 OO.ui.ButtonWidget.static.cancelButtonMouseDownEvents = false;
3481 /* Methods */
3484 * Get hyperlink location.
3486 * @return {string} Hyperlink location
3488 OO.ui.ButtonWidget.prototype.getHref = function () {
3489 return this.href;
3493 * Get hyperlink target.
3495 * @return {string} Hyperlink target
3497 OO.ui.ButtonWidget.prototype.getTarget = function () {
3498 return this.target;
3502 * Get search engine traversal hint.
3504 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3506 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
3507 return this.noFollow;
3511 * Set hyperlink location.
3513 * @param {string|null} href Hyperlink location, null to remove
3515 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
3516 href = typeof href === 'string' ? href : null;
3517 if ( href !== null && !OO.ui.isSafeUrl( href ) ) {
3518 href = './' + href;
3521 if ( href !== this.href ) {
3522 this.href = href;
3523 this.updateHref();
3526 return this;
3530 * Update the `href` attribute, in case of changes to href or
3531 * disabled state.
3533 * @private
3534 * @chainable
3536 OO.ui.ButtonWidget.prototype.updateHref = function () {
3537 if ( this.href !== null && !this.isDisabled() ) {
3538 this.$button.attr( 'href', this.href );
3539 } else {
3540 this.$button.removeAttr( 'href' );
3543 return this;
3547 * Handle disable events.
3549 * @private
3550 * @param {boolean} disabled Element is disabled
3552 OO.ui.ButtonWidget.prototype.onDisable = function () {
3553 this.updateHref();
3557 * Set hyperlink target.
3559 * @param {string|null} target Hyperlink target, null to remove
3561 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
3562 target = typeof target === 'string' ? target : null;
3564 if ( target !== this.target ) {
3565 this.target = target;
3566 if ( target !== null ) {
3567 this.$button.attr( 'target', target );
3568 } else {
3569 this.$button.removeAttr( 'target' );
3573 return this;
3577 * Set search engine traversal hint.
3579 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3581 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
3582 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
3584 if ( noFollow !== this.noFollow ) {
3585 this.noFollow = noFollow;
3586 if ( noFollow ) {
3587 this.$button.attr( 'rel', 'nofollow' );
3588 } else {
3589 this.$button.removeAttr( 'rel' );
3593 return this;
3596 // Override method visibility hints from ButtonElement
3598 * @method setActive
3601 * @method isActive
3605 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3606 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3607 * removed, and cleared from the group.
3609 * @example
3610 * // Example: A ButtonGroupWidget with two buttons
3611 * var button1 = new OO.ui.PopupButtonWidget( {
3612 * label: 'Select a category',
3613 * icon: 'menu',
3614 * popup: {
3615 * $content: $( '<p>List of categories...</p>' ),
3616 * padded: true,
3617 * align: 'left'
3619 * } );
3620 * var button2 = new OO.ui.ButtonWidget( {
3621 * label: 'Add item'
3622 * });
3623 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
3624 * items: [button1, button2]
3625 * } );
3626 * $( 'body' ).append( buttonGroup.$element );
3628 * @class
3629 * @extends OO.ui.Widget
3630 * @mixins OO.ui.mixin.GroupElement
3632 * @constructor
3633 * @param {Object} [config] Configuration options
3634 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
3636 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
3637 // Configuration initialization
3638 config = config || {};
3640 // Parent constructor
3641 OO.ui.ButtonGroupWidget.parent.call( this, config );
3643 // Mixin constructors
3644 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
3646 // Initialization
3647 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
3648 if ( Array.isArray( config.items ) ) {
3649 this.addItems( config.items );
3653 /* Setup */
3655 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
3656 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.GroupElement );
3659 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
3660 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
3661 * for a list of icons included in the library.
3663 * @example
3664 * // An icon widget with a label
3665 * var myIcon = new OO.ui.IconWidget( {
3666 * icon: 'help',
3667 * iconTitle: 'Help'
3668 * } );
3669 * // Create a label.
3670 * var iconLabel = new OO.ui.LabelWidget( {
3671 * label: 'Help'
3672 * } );
3673 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
3675 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
3677 * @class
3678 * @extends OO.ui.Widget
3679 * @mixins OO.ui.mixin.IconElement
3680 * @mixins OO.ui.mixin.TitledElement
3681 * @mixins OO.ui.mixin.FlaggedElement
3683 * @constructor
3684 * @param {Object} [config] Configuration options
3686 OO.ui.IconWidget = function OoUiIconWidget( config ) {
3687 // Configuration initialization
3688 config = config || {};
3690 // Parent constructor
3691 OO.ui.IconWidget.parent.call( this, config );
3693 // Mixin constructors
3694 OO.ui.mixin.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
3695 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
3696 OO.ui.mixin.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) );
3698 // Initialization
3699 this.$element.addClass( 'oo-ui-iconWidget' );
3702 /* Setup */
3704 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
3705 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.IconElement );
3706 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.TitledElement );
3707 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.FlaggedElement );
3709 /* Static Properties */
3711 OO.ui.IconWidget.static.tagName = 'span';
3714 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
3715 * attention to the status of an item or to clarify the function of a control. For a list of
3716 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
3718 * @example
3719 * // Example of an indicator widget
3720 * var indicator1 = new OO.ui.IndicatorWidget( {
3721 * indicator: 'alert'
3722 * } );
3724 * // Create a fieldset layout to add a label
3725 * var fieldset = new OO.ui.FieldsetLayout();
3726 * fieldset.addItems( [
3727 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
3728 * ] );
3729 * $( 'body' ).append( fieldset.$element );
3731 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3733 * @class
3734 * @extends OO.ui.Widget
3735 * @mixins OO.ui.mixin.IndicatorElement
3736 * @mixins OO.ui.mixin.TitledElement
3738 * @constructor
3739 * @param {Object} [config] Configuration options
3741 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
3742 // Configuration initialization
3743 config = config || {};
3745 // Parent constructor
3746 OO.ui.IndicatorWidget.parent.call( this, config );
3748 // Mixin constructors
3749 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
3750 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
3752 // Initialization
3753 this.$element.addClass( 'oo-ui-indicatorWidget' );
3756 /* Setup */
3758 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
3759 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.IndicatorElement );
3760 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.TitledElement );
3762 /* Static Properties */
3764 OO.ui.IndicatorWidget.static.tagName = 'span';
3767 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
3768 * be configured with a `label` option that is set to a string, a label node, or a function:
3770 * - String: a plaintext string
3771 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
3772 * label that includes a link or special styling, such as a gray color or additional graphical elements.
3773 * - Function: a function that will produce a string in the future. Functions are used
3774 * in cases where the value of the label is not currently defined.
3776 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
3777 * will come into focus when the label is clicked.
3779 * @example
3780 * // Examples of LabelWidgets
3781 * var label1 = new OO.ui.LabelWidget( {
3782 * label: 'plaintext label'
3783 * } );
3784 * var label2 = new OO.ui.LabelWidget( {
3785 * label: $( '<a href="default.html">jQuery label</a>' )
3786 * } );
3787 * // Create a fieldset layout with fields for each example
3788 * var fieldset = new OO.ui.FieldsetLayout();
3789 * fieldset.addItems( [
3790 * new OO.ui.FieldLayout( label1 ),
3791 * new OO.ui.FieldLayout( label2 )
3792 * ] );
3793 * $( 'body' ).append( fieldset.$element );
3795 * @class
3796 * @extends OO.ui.Widget
3797 * @mixins OO.ui.mixin.LabelElement
3798 * @mixins OO.ui.mixin.TitledElement
3800 * @constructor
3801 * @param {Object} [config] Configuration options
3802 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
3803 * Clicking the label will focus the specified input field.
3805 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
3806 // Configuration initialization
3807 config = config || {};
3809 // Parent constructor
3810 OO.ui.LabelWidget.parent.call( this, config );
3812 // Mixin constructors
3813 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
3814 OO.ui.mixin.TitledElement.call( this, config );
3816 // Properties
3817 this.input = config.input;
3819 // Events
3820 if ( this.input instanceof OO.ui.InputWidget ) {
3821 this.$element.on( 'click', this.onClick.bind( this ) );
3824 // Initialization
3825 this.$element.addClass( 'oo-ui-labelWidget' );
3828 /* Setup */
3830 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
3831 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.LabelElement );
3832 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.TitledElement );
3834 /* Static Properties */
3836 OO.ui.LabelWidget.static.tagName = 'span';
3838 /* Methods */
3841 * Handles label mouse click events.
3843 * @private
3844 * @param {jQuery.Event} e Mouse click event
3846 OO.ui.LabelWidget.prototype.onClick = function () {
3847 this.input.simulateLabelClick();
3848 return false;
3852 * PendingElement is a mixin that is used to create elements that notify users that something is happening
3853 * and that they should wait before proceeding. The pending state is visually represented with a pending
3854 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
3855 * field of a {@link OO.ui.TextInputWidget text input widget}.
3857 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
3858 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
3859 * in process dialogs.
3861 * @example
3862 * function MessageDialog( config ) {
3863 * MessageDialog.parent.call( this, config );
3865 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
3867 * MessageDialog.static.actions = [
3868 * { action: 'save', label: 'Done', flags: 'primary' },
3869 * { label: 'Cancel', flags: 'safe' }
3870 * ];
3872 * MessageDialog.prototype.initialize = function () {
3873 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
3874 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
3875 * 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>' );
3876 * this.$body.append( this.content.$element );
3877 * };
3878 * MessageDialog.prototype.getBodyHeight = function () {
3879 * return 100;
3881 * MessageDialog.prototype.getActionProcess = function ( action ) {
3882 * var dialog = this;
3883 * if ( action === 'save' ) {
3884 * dialog.getActions().get({actions: 'save'})[0].pushPending();
3885 * return new OO.ui.Process()
3886 * .next( 1000 )
3887 * .next( function () {
3888 * dialog.getActions().get({actions: 'save'})[0].popPending();
3889 * } );
3891 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
3892 * };
3894 * var windowManager = new OO.ui.WindowManager();
3895 * $( 'body' ).append( windowManager.$element );
3897 * var dialog = new MessageDialog();
3898 * windowManager.addWindows( [ dialog ] );
3899 * windowManager.openWindow( dialog );
3901 * @abstract
3902 * @class
3904 * @constructor
3905 * @param {Object} [config] Configuration options
3906 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
3908 OO.ui.mixin.PendingElement = function OoUiMixinPendingElement( config ) {
3909 // Configuration initialization
3910 config = config || {};
3912 // Properties
3913 this.pending = 0;
3914 this.$pending = null;
3916 // Initialisation
3917 this.setPendingElement( config.$pending || this.$element );
3920 /* Setup */
3922 OO.initClass( OO.ui.mixin.PendingElement );
3924 /* Methods */
3927 * Set the pending element (and clean up any existing one).
3929 * @param {jQuery} $pending The element to set to pending.
3931 OO.ui.mixin.PendingElement.prototype.setPendingElement = function ( $pending ) {
3932 if ( this.$pending ) {
3933 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
3936 this.$pending = $pending;
3937 if ( this.pending > 0 ) {
3938 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
3943 * Check if an element is pending.
3945 * @return {boolean} Element is pending
3947 OO.ui.mixin.PendingElement.prototype.isPending = function () {
3948 return !!this.pending;
3952 * Increase the pending counter. The pending state will remain active until the counter is zero
3953 * (i.e., the number of calls to #pushPending and #popPending is the same).
3955 * @chainable
3957 OO.ui.mixin.PendingElement.prototype.pushPending = function () {
3958 if ( this.pending === 0 ) {
3959 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
3960 this.updateThemeClasses();
3962 this.pending++;
3964 return this;
3968 * Decrease the pending counter. The pending state will remain active until the counter is zero
3969 * (i.e., the number of calls to #pushPending and #popPending is the same).
3971 * @chainable
3973 OO.ui.mixin.PendingElement.prototype.popPending = function () {
3974 if ( this.pending === 1 ) {
3975 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
3976 this.updateThemeClasses();
3978 this.pending = Math.max( 0, this.pending - 1 );
3980 return this;
3984 * Element that can be automatically clipped to visible boundaries.
3986 * Whenever the element's natural height changes, you have to call
3987 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
3988 * clipping correctly.
3990 * The dimensions of #$clippableContainer will be compared to the boundaries of the
3991 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
3992 * then #$clippable will be given a fixed reduced height and/or width and will be made
3993 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
3994 * but you can build a static footer by setting #$clippableContainer to an element that contains
3995 * #$clippable and the footer.
3997 * @abstract
3998 * @class
4000 * @constructor
4001 * @param {Object} [config] Configuration options
4002 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
4003 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
4004 * omit to use #$clippable
4006 OO.ui.mixin.ClippableElement = function OoUiMixinClippableElement( config ) {
4007 // Configuration initialization
4008 config = config || {};
4010 // Properties
4011 this.$clippable = null;
4012 this.$clippableContainer = null;
4013 this.clipping = false;
4014 this.clippedHorizontally = false;
4015 this.clippedVertically = false;
4016 this.$clippableScrollableContainer = null;
4017 this.$clippableScroller = null;
4018 this.$clippableWindow = null;
4019 this.idealWidth = null;
4020 this.idealHeight = null;
4021 this.onClippableScrollHandler = this.clip.bind( this );
4022 this.onClippableWindowResizeHandler = this.clip.bind( this );
4024 // Initialization
4025 if ( config.$clippableContainer ) {
4026 this.setClippableContainer( config.$clippableContainer );
4028 this.setClippableElement( config.$clippable || this.$element );
4031 /* Methods */
4034 * Set clippable element.
4036 * If an element is already set, it will be cleaned up before setting up the new element.
4038 * @param {jQuery} $clippable Element to make clippable
4040 OO.ui.mixin.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
4041 if ( this.$clippable ) {
4042 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
4043 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
4044 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
4047 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
4048 this.clip();
4052 * Set clippable container.
4054 * This is the container that will be measured when deciding whether to clip. When clipping,
4055 * #$clippable will be resized in order to keep the clippable container fully visible.
4057 * If the clippable container is unset, #$clippable will be used.
4059 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
4061 OO.ui.mixin.ClippableElement.prototype.setClippableContainer = function ( $clippableContainer ) {
4062 this.$clippableContainer = $clippableContainer;
4063 if ( this.$clippable ) {
4064 this.clip();
4069 * Toggle clipping.
4071 * Do not turn clipping on until after the element is attached to the DOM and visible.
4073 * @param {boolean} [clipping] Enable clipping, omit to toggle
4074 * @chainable
4076 OO.ui.mixin.ClippableElement.prototype.toggleClipping = function ( clipping ) {
4077 clipping = clipping === undefined ? !this.clipping : !!clipping;
4079 if ( this.clipping !== clipping ) {
4080 this.clipping = clipping;
4081 if ( clipping ) {
4082 this.$clippableScrollableContainer = $( this.getClosestScrollableElementContainer() );
4083 // If the clippable container is the root, we have to listen to scroll events and check
4084 // jQuery.scrollTop on the window because of browser inconsistencies
4085 this.$clippableScroller = this.$clippableScrollableContainer.is( 'html, body' ) ?
4086 $( OO.ui.Element.static.getWindow( this.$clippableScrollableContainer ) ) :
4087 this.$clippableScrollableContainer;
4088 this.$clippableScroller.on( 'scroll', this.onClippableScrollHandler );
4089 this.$clippableWindow = $( this.getElementWindow() )
4090 .on( 'resize', this.onClippableWindowResizeHandler );
4091 // Initial clip after visible
4092 this.clip();
4093 } else {
4094 this.$clippable.css( {
4095 width: '',
4096 height: '',
4097 maxWidth: '',
4098 maxHeight: '',
4099 overflowX: '',
4100 overflowY: ''
4101 } );
4102 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
4104 this.$clippableScrollableContainer = null;
4105 this.$clippableScroller.off( 'scroll', this.onClippableScrollHandler );
4106 this.$clippableScroller = null;
4107 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
4108 this.$clippableWindow = null;
4112 return this;
4116 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4118 * @return {boolean} Element will be clipped to the visible area
4120 OO.ui.mixin.ClippableElement.prototype.isClipping = function () {
4121 return this.clipping;
4125 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
4127 * @return {boolean} Part of the element is being clipped
4129 OO.ui.mixin.ClippableElement.prototype.isClipped = function () {
4130 return this.clippedHorizontally || this.clippedVertically;
4134 * Check if the right of the element is being clipped by the nearest scrollable container.
4136 * @return {boolean} Part of the element is being clipped
4138 OO.ui.mixin.ClippableElement.prototype.isClippedHorizontally = function () {
4139 return this.clippedHorizontally;
4143 * Check if the bottom of the element is being clipped by the nearest scrollable container.
4145 * @return {boolean} Part of the element is being clipped
4147 OO.ui.mixin.ClippableElement.prototype.isClippedVertically = function () {
4148 return this.clippedVertically;
4152 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
4154 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
4155 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
4157 OO.ui.mixin.ClippableElement.prototype.setIdealSize = function ( width, height ) {
4158 this.idealWidth = width;
4159 this.idealHeight = height;
4161 if ( !this.clipping ) {
4162 // Update dimensions
4163 this.$clippable.css( { width: width, height: height } );
4165 // While clipping, idealWidth and idealHeight are not considered
4169 * Clip element to visible boundaries and allow scrolling when needed. You should call this method
4170 * when the element's natural height changes.
4172 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
4173 * overlapped by, the visible area of the nearest scrollable container.
4175 * Because calling clip() when the natural height changes isn't always possible, we also set
4176 * max-height when the element isn't being clipped. This means that if the element tries to grow
4177 * beyond the edge, something reasonable will happen before clip() is called.
4179 * @chainable
4181 OO.ui.mixin.ClippableElement.prototype.clip = function () {
4182 var $container, extraHeight, extraWidth, ccOffset,
4183 $scrollableContainer, scOffset, scHeight, scWidth,
4184 ccWidth, scrollerIsWindow, scrollTop, scrollLeft,
4185 desiredWidth, desiredHeight, allotedWidth, allotedHeight,
4186 naturalWidth, naturalHeight, clipWidth, clipHeight,
4187 buffer = 7; // Chosen by fair dice roll
4189 if ( !this.clipping ) {
4190 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
4191 return this;
4194 $container = this.$clippableContainer || this.$clippable;
4195 extraHeight = $container.outerHeight() - this.$clippable.outerHeight();
4196 extraWidth = $container.outerWidth() - this.$clippable.outerWidth();
4197 ccOffset = $container.offset();
4198 if ( this.$clippableScrollableContainer.is( 'html, body' ) ) {
4199 $scrollableContainer = this.$clippableWindow;
4200 scOffset = { top: 0, left: 0 };
4201 } else {
4202 $scrollableContainer = this.$clippableScrollableContainer;
4203 scOffset = $scrollableContainer.offset();
4205 scHeight = $scrollableContainer.innerHeight() - buffer;
4206 scWidth = $scrollableContainer.innerWidth() - buffer;
4207 ccWidth = $container.outerWidth() + buffer;
4208 scrollerIsWindow = this.$clippableScroller[ 0 ] === this.$clippableWindow[ 0 ];
4209 scrollTop = scrollerIsWindow ? this.$clippableScroller.scrollTop() : 0;
4210 scrollLeft = scrollerIsWindow ? this.$clippableScroller.scrollLeft() : 0;
4211 desiredWidth = ccOffset.left < 0 ?
4212 ccWidth + ccOffset.left :
4213 ( scOffset.left + scrollLeft + scWidth ) - ccOffset.left;
4214 desiredHeight = ( scOffset.top + scrollTop + scHeight ) - ccOffset.top;
4215 // It should never be desirable to exceed the dimensions of the browser viewport... right?
4216 desiredWidth = Math.min( desiredWidth, document.documentElement.clientWidth );
4217 desiredHeight = Math.min( desiredHeight, document.documentElement.clientHeight );
4218 allotedWidth = Math.ceil( desiredWidth - extraWidth );
4219 allotedHeight = Math.ceil( desiredHeight - extraHeight );
4220 naturalWidth = this.$clippable.prop( 'scrollWidth' );
4221 naturalHeight = this.$clippable.prop( 'scrollHeight' );
4222 clipWidth = allotedWidth < naturalWidth;
4223 clipHeight = allotedHeight < naturalHeight;
4225 if ( clipWidth ) {
4226 this.$clippable.css( {
4227 overflowX: 'scroll',
4228 width: Math.max( 0, allotedWidth ),
4229 maxWidth: ''
4230 } );
4231 } else {
4232 this.$clippable.css( {
4233 overflowX: '',
4234 width: this.idealWidth ? this.idealWidth - extraWidth : '',
4235 maxWidth: Math.max( 0, allotedWidth )
4236 } );
4238 if ( clipHeight ) {
4239 this.$clippable.css( {
4240 overflowY: 'scroll',
4241 height: Math.max( 0, allotedHeight ),
4242 maxHeight: ''
4243 } );
4244 } else {
4245 this.$clippable.css( {
4246 overflowY: '',
4247 height: this.idealHeight ? this.idealHeight - extraHeight : '',
4248 maxHeight: Math.max( 0, allotedHeight )
4249 } );
4252 // If we stopped clipping in at least one of the dimensions
4253 if ( ( this.clippedHorizontally && !clipWidth ) || ( this.clippedVertically && !clipHeight ) ) {
4254 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
4257 this.clippedHorizontally = clipWidth;
4258 this.clippedVertically = clipHeight;
4260 return this;
4264 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
4265 * By default, each popup has an anchor that points toward its origin.
4266 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
4268 * @example
4269 * // A popup widget.
4270 * var popup = new OO.ui.PopupWidget( {
4271 * $content: $( '<p>Hi there!</p>' ),
4272 * padded: true,
4273 * width: 300
4274 * } );
4276 * $( 'body' ).append( popup.$element );
4277 * // To display the popup, toggle the visibility to 'true'.
4278 * popup.toggle( true );
4280 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
4282 * @class
4283 * @extends OO.ui.Widget
4284 * @mixins OO.ui.mixin.LabelElement
4285 * @mixins OO.ui.mixin.ClippableElement
4287 * @constructor
4288 * @param {Object} [config] Configuration options
4289 * @cfg {number} [width=320] Width of popup in pixels
4290 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
4291 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
4292 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
4293 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
4294 * popup is leaning towards the right of the screen.
4295 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
4296 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
4297 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
4298 * sentence in the given language.
4299 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
4300 * See the [OOjs UI docs on MediaWiki][3] for an example.
4301 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
4302 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
4303 * @cfg {jQuery} [$content] Content to append to the popup's body
4304 * @cfg {jQuery} [$footer] Content to append to the popup's footer
4305 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
4306 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
4307 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
4308 * for an example.
4309 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
4310 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
4311 * button.
4312 * @cfg {boolean} [padded=false] Add padding to the popup's body
4314 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
4315 // Configuration initialization
4316 config = config || {};
4318 // Parent constructor
4319 OO.ui.PopupWidget.parent.call( this, config );
4321 // Properties (must be set before ClippableElement constructor call)
4322 this.$body = $( '<div>' );
4323 this.$popup = $( '<div>' );
4325 // Mixin constructors
4326 OO.ui.mixin.LabelElement.call( this, config );
4327 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, {
4328 $clippable: this.$body,
4329 $clippableContainer: this.$popup
4330 } ) );
4332 // Properties
4333 this.$anchor = $( '<div>' );
4334 // If undefined, will be computed lazily in updateDimensions()
4335 this.$container = config.$container;
4336 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
4337 this.autoClose = !!config.autoClose;
4338 this.$autoCloseIgnore = config.$autoCloseIgnore;
4339 this.transitionTimeout = null;
4340 this.anchor = null;
4341 this.width = config.width !== undefined ? config.width : 320;
4342 this.height = config.height !== undefined ? config.height : null;
4343 this.setAlignment( config.align );
4344 this.onMouseDownHandler = this.onMouseDown.bind( this );
4345 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
4347 // Initialization
4348 this.toggleAnchor( config.anchor === undefined || config.anchor );
4349 this.$body.addClass( 'oo-ui-popupWidget-body' );
4350 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
4351 this.$popup
4352 .addClass( 'oo-ui-popupWidget-popup' )
4353 .append( this.$body );
4354 this.$element
4355 .addClass( 'oo-ui-popupWidget' )
4356 .append( this.$popup, this.$anchor );
4357 // Move content, which was added to #$element by OO.ui.Widget, to the body
4358 // FIXME This is gross, we should use '$body' or something for the config
4359 if ( config.$content instanceof jQuery ) {
4360 this.$body.append( config.$content );
4363 if ( config.padded ) {
4364 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
4367 if ( config.head ) {
4368 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
4369 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
4370 this.$head = $( '<div>' )
4371 .addClass( 'oo-ui-popupWidget-head' )
4372 .append( this.$label, this.closeButton.$element );
4373 this.$popup.prepend( this.$head );
4376 if ( config.$footer ) {
4377 this.$footer = $( '<div>' )
4378 .addClass( 'oo-ui-popupWidget-footer' )
4379 .append( config.$footer );
4380 this.$popup.append( this.$footer );
4383 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
4384 // that reference properties not initialized at that time of parent class construction
4385 // TODO: Find a better way to handle post-constructor setup
4386 this.visible = false;
4387 this.$element.addClass( 'oo-ui-element-hidden' );
4390 /* Setup */
4392 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
4393 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.LabelElement );
4394 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.ClippableElement );
4396 /* Methods */
4399 * Handles mouse down events.
4401 * @private
4402 * @param {MouseEvent} e Mouse down event
4404 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
4405 if (
4406 this.isVisible() &&
4407 !OO.ui.contains( this.$element.add( this.$autoCloseIgnore ).get(), e.target, true )
4409 this.toggle( false );
4414 * Bind mouse down listener.
4416 * @private
4418 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
4419 // Capture clicks outside popup
4420 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler, true );
4424 * Handles close button click events.
4426 * @private
4428 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
4429 if ( this.isVisible() ) {
4430 this.toggle( false );
4435 * Unbind mouse down listener.
4437 * @private
4439 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
4440 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler, true );
4444 * Handles key down events.
4446 * @private
4447 * @param {KeyboardEvent} e Key down event
4449 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
4450 if (
4451 e.which === OO.ui.Keys.ESCAPE &&
4452 this.isVisible()
4454 this.toggle( false );
4455 e.preventDefault();
4456 e.stopPropagation();
4461 * Bind key down listener.
4463 * @private
4465 OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
4466 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
4470 * Unbind key down listener.
4472 * @private
4474 OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
4475 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
4479 * Show, hide, or toggle the visibility of the anchor.
4481 * @param {boolean} [show] Show anchor, omit to toggle
4483 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
4484 show = show === undefined ? !this.anchored : !!show;
4486 if ( this.anchored !== show ) {
4487 if ( show ) {
4488 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
4489 } else {
4490 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
4492 this.anchored = show;
4497 * Check if the anchor is visible.
4499 * @return {boolean} Anchor is visible
4501 OO.ui.PopupWidget.prototype.hasAnchor = function () {
4502 return this.anchor;
4506 * @inheritdoc
4508 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
4509 var change;
4510 show = show === undefined ? !this.isVisible() : !!show;
4512 change = show !== this.isVisible();
4514 // Parent method
4515 OO.ui.PopupWidget.parent.prototype.toggle.call( this, show );
4517 if ( change ) {
4518 if ( show ) {
4519 if ( this.autoClose ) {
4520 this.bindMouseDownListener();
4521 this.bindKeyDownListener();
4523 this.updateDimensions();
4524 this.toggleClipping( true );
4525 } else {
4526 this.toggleClipping( false );
4527 if ( this.autoClose ) {
4528 this.unbindMouseDownListener();
4529 this.unbindKeyDownListener();
4534 return this;
4538 * Set the size of the popup.
4540 * Changing the size may also change the popup's position depending on the alignment.
4542 * @param {number} width Width in pixels
4543 * @param {number} height Height in pixels
4544 * @param {boolean} [transition=false] Use a smooth transition
4545 * @chainable
4547 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
4548 this.width = width;
4549 this.height = height !== undefined ? height : null;
4550 if ( this.isVisible() ) {
4551 this.updateDimensions( transition );
4556 * Update the size and position.
4558 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
4559 * be called automatically.
4561 * @param {boolean} [transition=false] Use a smooth transition
4562 * @chainable
4564 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
4565 var popupOffset, originOffset, containerLeft, containerWidth, containerRight,
4566 popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth,
4567 align = this.align,
4568 widget = this;
4570 if ( !this.$container ) {
4571 // Lazy-initialize $container if not specified in constructor
4572 this.$container = $( this.getClosestScrollableElementContainer() );
4575 // Set height and width before measuring things, since it might cause our measurements
4576 // to change (e.g. due to scrollbars appearing or disappearing)
4577 this.$popup.css( {
4578 width: this.width,
4579 height: this.height !== null ? this.height : 'auto'
4580 } );
4582 // If we are in RTL, we need to flip the alignment, unless it is center
4583 if ( align === 'forwards' || align === 'backwards' ) {
4584 if ( this.$container.css( 'direction' ) === 'rtl' ) {
4585 align = ( { forwards: 'force-left', backwards: 'force-right' } )[ this.align ];
4586 } else {
4587 align = ( { forwards: 'force-right', backwards: 'force-left' } )[ this.align ];
4592 // Compute initial popupOffset based on alignment
4593 popupOffset = this.width * ( { 'force-left': -1, center: -0.5, 'force-right': 0 } )[ align ];
4595 // Figure out if this will cause the popup to go beyond the edge of the container
4596 originOffset = this.$element.offset().left;
4597 containerLeft = this.$container.offset().left;
4598 containerWidth = this.$container.innerWidth();
4599 containerRight = containerLeft + containerWidth;
4600 popupLeft = popupOffset - this.containerPadding;
4601 popupRight = popupOffset + this.containerPadding + this.width + this.containerPadding;
4602 overlapLeft = ( originOffset + popupLeft ) - containerLeft;
4603 overlapRight = containerRight - ( originOffset + popupRight );
4605 // Adjust offset to make the popup not go beyond the edge, if needed
4606 if ( overlapRight < 0 ) {
4607 popupOffset += overlapRight;
4608 } else if ( overlapLeft < 0 ) {
4609 popupOffset -= overlapLeft;
4612 // Adjust offset to avoid anchor being rendered too close to the edge
4613 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
4614 // TODO: Find a measurement that works for CSS anchors and image anchors
4615 anchorWidth = this.$anchor[ 0 ].scrollWidth * 2;
4616 if ( popupOffset + this.width < anchorWidth ) {
4617 popupOffset = anchorWidth - this.width;
4618 } else if ( -popupOffset < anchorWidth ) {
4619 popupOffset = -anchorWidth;
4622 // Prevent transition from being interrupted
4623 clearTimeout( this.transitionTimeout );
4624 if ( transition ) {
4625 // Enable transition
4626 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
4629 // Position body relative to anchor
4630 this.$popup.css( 'margin-left', popupOffset );
4632 if ( transition ) {
4633 // Prevent transitioning after transition is complete
4634 this.transitionTimeout = setTimeout( function () {
4635 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
4636 }, 200 );
4637 } else {
4638 // Prevent transitioning immediately
4639 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
4642 // Reevaluate clipping state since we've relocated and resized the popup
4643 this.clip();
4645 return this;
4649 * Set popup alignment
4651 * @param {string} [align=center] Alignment of the popup, `center`, `force-left`, `force-right`,
4652 * `backwards` or `forwards`.
4654 OO.ui.PopupWidget.prototype.setAlignment = function ( align ) {
4655 // Transform values deprecated since v0.11.0
4656 if ( align === 'left' || align === 'right' ) {
4657 OO.ui.warnDeprecation( 'PopupWidget#setAlignment parameter value `' + align + '` is deprecated. Use `force-right` or `force-left` instead.' );
4658 align = { left: 'force-right', right: 'force-left' }[ align ];
4661 // Validate alignment
4662 if ( [ 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align ) > -1 ) {
4663 this.align = align;
4664 } else {
4665 this.align = 'center';
4670 * Get popup alignment
4672 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
4673 * `backwards` or `forwards`.
4675 OO.ui.PopupWidget.prototype.getAlignment = function () {
4676 return this.align;
4680 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
4681 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
4682 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
4683 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
4685 * @abstract
4686 * @class
4688 * @constructor
4689 * @param {Object} [config] Configuration options
4690 * @cfg {Object} [popup] Configuration to pass to popup
4691 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
4693 OO.ui.mixin.PopupElement = function OoUiMixinPopupElement( config ) {
4694 // Configuration initialization
4695 config = config || {};
4697 // Properties
4698 this.popup = new OO.ui.PopupWidget( $.extend(
4699 { autoClose: true },
4700 config.popup,
4701 { $autoCloseIgnore: this.$element.add( config.popup && config.popup.$autoCloseIgnore ) }
4702 ) );
4705 /* Methods */
4708 * Get popup.
4710 * @return {OO.ui.PopupWidget} Popup widget
4712 OO.ui.mixin.PopupElement.prototype.getPopup = function () {
4713 return this.popup;
4717 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
4718 * which is used to display additional information or options.
4720 * @example
4721 * // Example of a popup button.
4722 * var popupButton = new OO.ui.PopupButtonWidget( {
4723 * label: 'Popup button with options',
4724 * icon: 'menu',
4725 * popup: {
4726 * $content: $( '<p>Additional options here.</p>' ),
4727 * padded: true,
4728 * align: 'force-left'
4730 * } );
4731 * // Append the button to the DOM.
4732 * $( 'body' ).append( popupButton.$element );
4734 * @class
4735 * @extends OO.ui.ButtonWidget
4736 * @mixins OO.ui.mixin.PopupElement
4738 * @constructor
4739 * @param {Object} [config] Configuration options
4741 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
4742 // Parent constructor
4743 OO.ui.PopupButtonWidget.parent.call( this, config );
4745 // Mixin constructors
4746 OO.ui.mixin.PopupElement.call( this, config );
4748 // Events
4749 this.connect( this, { click: 'onAction' } );
4751 // Initialization
4752 this.$element
4753 .addClass( 'oo-ui-popupButtonWidget' )
4754 .attr( 'aria-haspopup', 'true' )
4755 .append( this.popup.$element );
4758 /* Setup */
4760 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
4761 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.mixin.PopupElement );
4763 /* Methods */
4766 * Handle the button action being triggered.
4768 * @private
4770 OO.ui.PopupButtonWidget.prototype.onAction = function () {
4771 this.popup.toggle();
4775 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
4777 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
4779 * @private
4780 * @abstract
4781 * @class
4782 * @mixins OO.ui.mixin.GroupElement
4784 * @constructor
4785 * @param {Object} [config] Configuration options
4787 OO.ui.mixin.GroupWidget = function OoUiMixinGroupWidget( config ) {
4788 // Mixin constructors
4789 OO.ui.mixin.GroupElement.call( this, config );
4792 /* Setup */
4794 OO.mixinClass( OO.ui.mixin.GroupWidget, OO.ui.mixin.GroupElement );
4796 /* Methods */
4799 * Set the disabled state of the widget.
4801 * This will also update the disabled state of child widgets.
4803 * @param {boolean} disabled Disable widget
4804 * @chainable
4806 OO.ui.mixin.GroupWidget.prototype.setDisabled = function ( disabled ) {
4807 var i, len;
4809 // Parent method
4810 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
4811 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
4813 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
4814 if ( this.items ) {
4815 for ( i = 0, len = this.items.length; i < len; i++ ) {
4816 this.items[ i ].updateDisabled();
4820 return this;
4824 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
4826 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
4827 * allows bidirectional communication.
4829 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
4831 * @private
4832 * @abstract
4833 * @class
4835 * @constructor
4837 OO.ui.mixin.ItemWidget = function OoUiMixinItemWidget() {
4841 /* Methods */
4844 * Check if widget is disabled.
4846 * Checks parent if present, making disabled state inheritable.
4848 * @return {boolean} Widget is disabled
4850 OO.ui.mixin.ItemWidget.prototype.isDisabled = function () {
4851 return this.disabled ||
4852 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
4856 * Set group element is in.
4858 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
4859 * @chainable
4861 OO.ui.mixin.ItemWidget.prototype.setElementGroup = function ( group ) {
4862 // Parent method
4863 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
4864 OO.ui.Element.prototype.setElementGroup.call( this, group );
4866 // Initialize item disabled states
4867 this.updateDisabled();
4869 return this;
4873 * OptionWidgets are special elements that can be selected and configured with data. The
4874 * data is often unique for each option, but it does not have to be. OptionWidgets are used
4875 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
4876 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
4878 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
4880 * @class
4881 * @extends OO.ui.Widget
4882 * @mixins OO.ui.mixin.ItemWidget
4883 * @mixins OO.ui.mixin.LabelElement
4884 * @mixins OO.ui.mixin.FlaggedElement
4885 * @mixins OO.ui.mixin.AccessKeyedElement
4887 * @constructor
4888 * @param {Object} [config] Configuration options
4890 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
4891 // Configuration initialization
4892 config = config || {};
4894 // Parent constructor
4895 OO.ui.OptionWidget.parent.call( this, config );
4897 // Mixin constructors
4898 OO.ui.mixin.ItemWidget.call( this );
4899 OO.ui.mixin.LabelElement.call( this, config );
4900 OO.ui.mixin.FlaggedElement.call( this, config );
4901 OO.ui.mixin.AccessKeyedElement.call( this, config );
4903 // Properties
4904 this.selected = false;
4905 this.highlighted = false;
4906 this.pressed = false;
4908 // Initialization
4909 this.$element
4910 .data( 'oo-ui-optionWidget', this )
4911 // Allow programmatic focussing (and by accesskey), but not tabbing
4912 .attr( 'tabindex', '-1' )
4913 .attr( 'role', 'option' )
4914 .attr( 'aria-selected', 'false' )
4915 .addClass( 'oo-ui-optionWidget' )
4916 .append( this.$label );
4919 /* Setup */
4921 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
4922 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.ItemWidget );
4923 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.LabelElement );
4924 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.FlaggedElement );
4925 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.AccessKeyedElement );
4927 /* Static Properties */
4929 OO.ui.OptionWidget.static.selectable = true;
4931 OO.ui.OptionWidget.static.highlightable = true;
4933 OO.ui.OptionWidget.static.pressable = true;
4935 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
4937 /* Methods */
4940 * Check if the option can be selected.
4942 * @return {boolean} Item is selectable
4944 OO.ui.OptionWidget.prototype.isSelectable = function () {
4945 return this.constructor.static.selectable && !this.isDisabled() && this.isVisible();
4949 * Check if the option can be highlighted. A highlight indicates that the option
4950 * may be selected when a user presses enter or clicks. Disabled items cannot
4951 * be highlighted.
4953 * @return {boolean} Item is highlightable
4955 OO.ui.OptionWidget.prototype.isHighlightable = function () {
4956 return this.constructor.static.highlightable && !this.isDisabled() && this.isVisible();
4960 * Check if the option can be pressed. The pressed state occurs when a user mouses
4961 * down on an item, but has not yet let go of the mouse.
4963 * @return {boolean} Item is pressable
4965 OO.ui.OptionWidget.prototype.isPressable = function () {
4966 return this.constructor.static.pressable && !this.isDisabled() && this.isVisible();
4970 * Check if the option is selected.
4972 * @return {boolean} Item is selected
4974 OO.ui.OptionWidget.prototype.isSelected = function () {
4975 return this.selected;
4979 * Check if the option is highlighted. A highlight indicates that the
4980 * item may be selected when a user presses enter or clicks.
4982 * @return {boolean} Item is highlighted
4984 OO.ui.OptionWidget.prototype.isHighlighted = function () {
4985 return this.highlighted;
4989 * Check if the option is pressed. The pressed state occurs when a user mouses
4990 * down on an item, but has not yet let go of the mouse. The item may appear
4991 * selected, but it will not be selected until the user releases the mouse.
4993 * @return {boolean} Item is pressed
4995 OO.ui.OptionWidget.prototype.isPressed = function () {
4996 return this.pressed;
5000 * Set the option’s selected state. In general, all modifications to the selection
5001 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
5002 * method instead of this method.
5004 * @param {boolean} [state=false] Select option
5005 * @chainable
5007 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
5008 if ( this.constructor.static.selectable ) {
5009 this.selected = !!state;
5010 this.$element
5011 .toggleClass( 'oo-ui-optionWidget-selected', state )
5012 .attr( 'aria-selected', state.toString() );
5013 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
5014 this.scrollElementIntoView();
5016 this.updateThemeClasses();
5018 return this;
5022 * Set the option’s highlighted state. In general, all programmatic
5023 * modifications to the highlight should be handled by the
5024 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
5025 * method instead of this method.
5027 * @param {boolean} [state=false] Highlight option
5028 * @chainable
5030 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
5031 if ( this.constructor.static.highlightable ) {
5032 this.highlighted = !!state;
5033 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
5034 this.updateThemeClasses();
5036 return this;
5040 * Set the option’s pressed state. In general, all
5041 * programmatic modifications to the pressed state should be handled by the
5042 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
5043 * method instead of this method.
5045 * @param {boolean} [state=false] Press option
5046 * @chainable
5048 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
5049 if ( this.constructor.static.pressable ) {
5050 this.pressed = !!state;
5051 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
5052 this.updateThemeClasses();
5054 return this;
5058 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
5059 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
5060 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
5061 * menu selects}.
5063 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
5064 * information, please see the [OOjs UI documentation on MediaWiki][1].
5066 * @example
5067 * // Example of a select widget with three options
5068 * var select = new OO.ui.SelectWidget( {
5069 * items: [
5070 * new OO.ui.OptionWidget( {
5071 * data: 'a',
5072 * label: 'Option One',
5073 * } ),
5074 * new OO.ui.OptionWidget( {
5075 * data: 'b',
5076 * label: 'Option Two',
5077 * } ),
5078 * new OO.ui.OptionWidget( {
5079 * data: 'c',
5080 * label: 'Option Three',
5081 * } )
5083 * } );
5084 * $( 'body' ).append( select.$element );
5086 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5088 * @abstract
5089 * @class
5090 * @extends OO.ui.Widget
5091 * @mixins OO.ui.mixin.GroupWidget
5093 * @constructor
5094 * @param {Object} [config] Configuration options
5095 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
5096 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
5097 * the [OOjs UI documentation on MediaWiki] [2] for examples.
5098 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5100 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
5101 // Configuration initialization
5102 config = config || {};
5104 // Parent constructor
5105 OO.ui.SelectWidget.parent.call( this, config );
5107 // Mixin constructors
5108 OO.ui.mixin.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
5110 // Properties
5111 this.pressed = false;
5112 this.selecting = null;
5113 this.onMouseUpHandler = this.onMouseUp.bind( this );
5114 this.onMouseMoveHandler = this.onMouseMove.bind( this );
5115 this.onKeyDownHandler = this.onKeyDown.bind( this );
5116 this.onKeyPressHandler = this.onKeyPress.bind( this );
5117 this.keyPressBuffer = '';
5118 this.keyPressBufferTimer = null;
5119 this.blockMouseOverEvents = 0;
5121 // Events
5122 this.connect( this, {
5123 toggle: 'onToggle'
5124 } );
5125 this.$element.on( {
5126 focusin: this.onFocus.bind( this ),
5127 mousedown: this.onMouseDown.bind( this ),
5128 mouseover: this.onMouseOver.bind( this ),
5129 mouseleave: this.onMouseLeave.bind( this )
5130 } );
5132 // Initialization
5133 this.$element
5134 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
5135 .attr( 'role', 'listbox' );
5136 if ( Array.isArray( config.items ) ) {
5137 this.addItems( config.items );
5141 /* Setup */
5143 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
5144 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupWidget );
5146 /* Events */
5149 * @event highlight
5151 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
5153 * @param {OO.ui.OptionWidget|null} item Highlighted item
5157 * @event press
5159 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
5160 * pressed state of an option.
5162 * @param {OO.ui.OptionWidget|null} item Pressed item
5166 * @event select
5168 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
5170 * @param {OO.ui.OptionWidget|null} item Selected item
5174 * @event choose
5175 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
5176 * @param {OO.ui.OptionWidget} item Chosen item
5180 * @event add
5182 * An `add` event is emitted when options are added to the select with the #addItems method.
5184 * @param {OO.ui.OptionWidget[]} items Added items
5185 * @param {number} index Index of insertion point
5189 * @event remove
5191 * A `remove` event is emitted when options are removed from the select with the #clearItems
5192 * or #removeItems methods.
5194 * @param {OO.ui.OptionWidget[]} items Removed items
5197 /* Methods */
5200 * Handle focus events
5202 * @private
5203 * @param {jQuery.Event} event
5205 OO.ui.SelectWidget.prototype.onFocus = function ( event ) {
5206 var item;
5207 if ( event.target === this.$element[ 0 ] ) {
5208 // This widget was focussed, e.g. by the user tabbing to it.
5209 // The styles for focus state depend on one of the items being selected.
5210 if ( !this.getSelectedItem() ) {
5211 item = this.getFirstSelectableItem();
5213 } else {
5214 // One of the options got focussed (and the event bubbled up here).
5215 // They can't be tabbed to, but they can be activated using accesskeys.
5216 item = this.getTargetItem( event );
5219 if ( item ) {
5220 if ( item.constructor.static.highlightable ) {
5221 this.highlightItem( item );
5222 } else {
5223 this.selectItem( item );
5227 if ( event.target !== this.$element[ 0 ] ) {
5228 this.$element.focus();
5233 * Handle mouse down events.
5235 * @private
5236 * @param {jQuery.Event} e Mouse down event
5238 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
5239 var item;
5241 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
5242 this.togglePressed( true );
5243 item = this.getTargetItem( e );
5244 if ( item && item.isSelectable() ) {
5245 this.pressItem( item );
5246 this.selecting = item;
5247 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true );
5248 this.getElementDocument().addEventListener( 'mousemove', this.onMouseMoveHandler, true );
5251 return false;
5255 * Handle mouse up events.
5257 * @private
5258 * @param {MouseEvent} e Mouse up event
5260 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
5261 var item;
5263 this.togglePressed( false );
5264 if ( !this.selecting ) {
5265 item = this.getTargetItem( e );
5266 if ( item && item.isSelectable() ) {
5267 this.selecting = item;
5270 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT && this.selecting ) {
5271 this.pressItem( null );
5272 this.chooseItem( this.selecting );
5273 this.selecting = null;
5276 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true );
5277 this.getElementDocument().removeEventListener( 'mousemove', this.onMouseMoveHandler, true );
5279 return false;
5283 * Handle mouse move events.
5285 * @private
5286 * @param {MouseEvent} e Mouse move event
5288 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
5289 var item;
5291 if ( !this.isDisabled() && this.pressed ) {
5292 item = this.getTargetItem( e );
5293 if ( item && item !== this.selecting && item.isSelectable() ) {
5294 this.pressItem( item );
5295 this.selecting = item;
5301 * Handle mouse over events.
5303 * @private
5304 * @param {jQuery.Event} e Mouse over event
5306 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
5307 var item;
5308 if ( this.blockMouseOverEvents ) {
5309 return;
5311 if ( !this.isDisabled() ) {
5312 item = this.getTargetItem( e );
5313 this.highlightItem( item && item.isHighlightable() ? item : null );
5315 return false;
5319 * Handle mouse leave events.
5321 * @private
5322 * @param {jQuery.Event} e Mouse over event
5324 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
5325 if ( !this.isDisabled() ) {
5326 this.highlightItem( null );
5328 return false;
5332 * Handle key down events.
5334 * @protected
5335 * @param {KeyboardEvent} e Key down event
5337 OO.ui.SelectWidget.prototype.onKeyDown = function ( e ) {
5338 var nextItem,
5339 handled = false,
5340 currentItem = this.getHighlightedItem() || this.getSelectedItem();
5342 if ( !this.isDisabled() && this.isVisible() ) {
5343 switch ( e.keyCode ) {
5344 case OO.ui.Keys.ENTER:
5345 if ( currentItem && currentItem.constructor.static.highlightable ) {
5346 // Was only highlighted, now let's select it. No-op if already selected.
5347 this.chooseItem( currentItem );
5348 handled = true;
5350 break;
5351 case OO.ui.Keys.UP:
5352 case OO.ui.Keys.LEFT:
5353 this.clearKeyPressBuffer();
5354 nextItem = this.getRelativeSelectableItem( currentItem, -1 );
5355 handled = true;
5356 break;
5357 case OO.ui.Keys.DOWN:
5358 case OO.ui.Keys.RIGHT:
5359 this.clearKeyPressBuffer();
5360 nextItem = this.getRelativeSelectableItem( currentItem, 1 );
5361 handled = true;
5362 break;
5363 case OO.ui.Keys.ESCAPE:
5364 case OO.ui.Keys.TAB:
5365 if ( currentItem && currentItem.constructor.static.highlightable ) {
5366 currentItem.setHighlighted( false );
5368 this.unbindKeyDownListener();
5369 this.unbindKeyPressListener();
5370 // Don't prevent tabbing away / defocusing
5371 handled = false;
5372 break;
5375 if ( nextItem ) {
5376 if ( nextItem.constructor.static.highlightable ) {
5377 this.highlightItem( nextItem );
5378 } else {
5379 this.chooseItem( nextItem );
5381 this.scrollItemIntoView( nextItem );
5384 if ( handled ) {
5385 e.preventDefault();
5386 e.stopPropagation();
5392 * Bind key down listener.
5394 * @protected
5396 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
5397 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler, true );
5401 * Unbind key down listener.
5403 * @protected
5405 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
5406 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler, true );
5410 * Scroll item into view, preventing spurious mouse highlight actions from happening.
5412 * @param {OO.ui.OptionWidget} item Item to scroll into view
5414 OO.ui.SelectWidget.prototype.scrollItemIntoView = function ( item ) {
5415 var widget = this;
5416 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling
5417 // and around 100-150 ms after it is finished.
5418 this.blockMouseOverEvents++;
5419 item.scrollElementIntoView().done( function () {
5420 setTimeout( function () {
5421 widget.blockMouseOverEvents--;
5422 }, 200 );
5423 } );
5427 * Clear the key-press buffer
5429 * @protected
5431 OO.ui.SelectWidget.prototype.clearKeyPressBuffer = function () {
5432 if ( this.keyPressBufferTimer ) {
5433 clearTimeout( this.keyPressBufferTimer );
5434 this.keyPressBufferTimer = null;
5436 this.keyPressBuffer = '';
5440 * Handle key press events.
5442 * @protected
5443 * @param {KeyboardEvent} e Key press event
5445 OO.ui.SelectWidget.prototype.onKeyPress = function ( e ) {
5446 var c, filter, item;
5448 if ( !e.charCode ) {
5449 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.keyPressBuffer !== '' ) {
5450 this.keyPressBuffer = this.keyPressBuffer.substr( 0, this.keyPressBuffer.length - 1 );
5451 return false;
5453 return;
5455 if ( String.fromCodePoint ) {
5456 c = String.fromCodePoint( e.charCode );
5457 } else {
5458 c = String.fromCharCode( e.charCode );
5461 if ( this.keyPressBufferTimer ) {
5462 clearTimeout( this.keyPressBufferTimer );
5464 this.keyPressBufferTimer = setTimeout( this.clearKeyPressBuffer.bind( this ), 1500 );
5466 item = this.getHighlightedItem() || this.getSelectedItem();
5468 if ( this.keyPressBuffer === c ) {
5469 // Common (if weird) special case: typing "xxxx" will cycle through all
5470 // the items beginning with "x".
5471 if ( item ) {
5472 item = this.getRelativeSelectableItem( item, 1 );
5474 } else {
5475 this.keyPressBuffer += c;
5478 filter = this.getItemMatcher( this.keyPressBuffer, false );
5479 if ( !item || !filter( item ) ) {
5480 item = this.getRelativeSelectableItem( item, 1, filter );
5482 if ( item ) {
5483 if ( this.isVisible() && item.constructor.static.highlightable ) {
5484 this.highlightItem( item );
5485 } else {
5486 this.chooseItem( item );
5488 this.scrollItemIntoView( item );
5491 e.preventDefault();
5492 e.stopPropagation();
5496 * Get a matcher for the specific string
5498 * @protected
5499 * @param {string} s String to match against items
5500 * @param {boolean} [exact=false] Only accept exact matches
5501 * @return {Function} function ( OO.ui.OptionItem ) => boolean
5503 OO.ui.SelectWidget.prototype.getItemMatcher = function ( s, exact ) {
5504 var re;
5506 if ( s.normalize ) {
5507 s = s.normalize();
5509 s = exact ? s.trim() : s.replace( /^\s+/, '' );
5510 re = '^\\s*' + s.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
5511 if ( exact ) {
5512 re += '\\s*$';
5514 re = new RegExp( re, 'i' );
5515 return function ( item ) {
5516 var l = item.getLabel();
5517 if ( typeof l !== 'string' ) {
5518 l = item.$label.text();
5520 if ( l.normalize ) {
5521 l = l.normalize();
5523 return re.test( l );
5528 * Bind key press listener.
5530 * @protected
5532 OO.ui.SelectWidget.prototype.bindKeyPressListener = function () {
5533 this.getElementWindow().addEventListener( 'keypress', this.onKeyPressHandler, true );
5537 * Unbind key down listener.
5539 * If you override this, be sure to call this.clearKeyPressBuffer() from your
5540 * implementation.
5542 * @protected
5544 OO.ui.SelectWidget.prototype.unbindKeyPressListener = function () {
5545 this.getElementWindow().removeEventListener( 'keypress', this.onKeyPressHandler, true );
5546 this.clearKeyPressBuffer();
5550 * Visibility change handler
5552 * @protected
5553 * @param {boolean} visible
5555 OO.ui.SelectWidget.prototype.onToggle = function ( visible ) {
5556 if ( !visible ) {
5557 this.clearKeyPressBuffer();
5562 * Get the closest item to a jQuery.Event.
5564 * @private
5565 * @param {jQuery.Event} e
5566 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
5568 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
5569 return $( e.target ).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
5573 * Get selected item.
5575 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
5577 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
5578 var i, len;
5580 for ( i = 0, len = this.items.length; i < len; i++ ) {
5581 if ( this.items[ i ].isSelected() ) {
5582 return this.items[ i ];
5585 return null;
5589 * Get highlighted item.
5591 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
5593 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
5594 var i, len;
5596 for ( i = 0, len = this.items.length; i < len; i++ ) {
5597 if ( this.items[ i ].isHighlighted() ) {
5598 return this.items[ i ];
5601 return null;
5605 * Toggle pressed state.
5607 * Press is a state that occurs when a user mouses down on an item, but
5608 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
5609 * until the user releases the mouse.
5611 * @param {boolean} pressed An option is being pressed
5613 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
5614 if ( pressed === undefined ) {
5615 pressed = !this.pressed;
5617 if ( pressed !== this.pressed ) {
5618 this.$element
5619 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
5620 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
5621 this.pressed = pressed;
5626 * Highlight an option. If the `item` param is omitted, no options will be highlighted
5627 * and any existing highlight will be removed. The highlight is mutually exclusive.
5629 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
5630 * @fires highlight
5631 * @chainable
5633 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
5634 var i, len, highlighted,
5635 changed = false;
5637 for ( i = 0, len = this.items.length; i < len; i++ ) {
5638 highlighted = this.items[ i ] === item;
5639 if ( this.items[ i ].isHighlighted() !== highlighted ) {
5640 this.items[ i ].setHighlighted( highlighted );
5641 changed = true;
5644 if ( changed ) {
5645 this.emit( 'highlight', item );
5648 return this;
5652 * Fetch an item by its label.
5654 * @param {string} label Label of the item to select.
5655 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
5656 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
5658 OO.ui.SelectWidget.prototype.getItemFromLabel = function ( label, prefix ) {
5659 var i, item, found,
5660 len = this.items.length,
5661 filter = this.getItemMatcher( label, true );
5663 for ( i = 0; i < len; i++ ) {
5664 item = this.items[ i ];
5665 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
5666 return item;
5670 if ( prefix ) {
5671 found = null;
5672 filter = this.getItemMatcher( label, false );
5673 for ( i = 0; i < len; i++ ) {
5674 item = this.items[ i ];
5675 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
5676 if ( found ) {
5677 return null;
5679 found = item;
5682 if ( found ) {
5683 return found;
5687 return null;
5691 * Programmatically select an option by its label. If the item does not exist,
5692 * all options will be deselected.
5694 * @param {string} [label] Label of the item to select.
5695 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
5696 * @fires select
5697 * @chainable
5699 OO.ui.SelectWidget.prototype.selectItemByLabel = function ( label, prefix ) {
5700 var itemFromLabel = this.getItemFromLabel( label, !!prefix );
5701 if ( label === undefined || !itemFromLabel ) {
5702 return this.selectItem();
5704 return this.selectItem( itemFromLabel );
5708 * Programmatically select an option by its data. If the `data` parameter is omitted,
5709 * or if the item does not exist, all options will be deselected.
5711 * @param {Object|string} [data] Value of the item to select, omit to deselect all
5712 * @fires select
5713 * @chainable
5715 OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) {
5716 var itemFromData = this.getItemFromData( data );
5717 if ( data === undefined || !itemFromData ) {
5718 return this.selectItem();
5720 return this.selectItem( itemFromData );
5724 * Programmatically select an option by its reference. If the `item` parameter is omitted,
5725 * all options will be deselected.
5727 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
5728 * @fires select
5729 * @chainable
5731 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
5732 var i, len, selected,
5733 changed = false;
5735 for ( i = 0, len = this.items.length; i < len; i++ ) {
5736 selected = this.items[ i ] === item;
5737 if ( this.items[ i ].isSelected() !== selected ) {
5738 this.items[ i ].setSelected( selected );
5739 changed = true;
5742 if ( changed ) {
5743 this.emit( 'select', item );
5746 return this;
5750 * Press an item.
5752 * Press is a state that occurs when a user mouses down on an item, but has not
5753 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
5754 * releases the mouse.
5756 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
5757 * @fires press
5758 * @chainable
5760 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
5761 var i, len, pressed,
5762 changed = false;
5764 for ( i = 0, len = this.items.length; i < len; i++ ) {
5765 pressed = this.items[ i ] === item;
5766 if ( this.items[ i ].isPressed() !== pressed ) {
5767 this.items[ i ].setPressed( pressed );
5768 changed = true;
5771 if ( changed ) {
5772 this.emit( 'press', item );
5775 return this;
5779 * Choose an item.
5781 * Note that ‘choose’ should never be modified programmatically. A user can choose
5782 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
5783 * use the #selectItem method.
5785 * This method is identical to #selectItem, but may vary in subclasses that take additional action
5786 * when users choose an item with the keyboard or mouse.
5788 * @param {OO.ui.OptionWidget} item Item to choose
5789 * @fires choose
5790 * @chainable
5792 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
5793 if ( item ) {
5794 this.selectItem( item );
5795 this.emit( 'choose', item );
5798 return this;
5802 * Get an option by its position relative to the specified item (or to the start of the option array,
5803 * if item is `null`). The direction in which to search through the option array is specified with a
5804 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
5805 * `null` if there are no options in the array.
5807 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
5808 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
5809 * @param {Function} [filter] Only consider items for which this function returns
5810 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
5811 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
5813 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction, filter ) {
5814 var currentIndex, nextIndex, i,
5815 increase = direction > 0 ? 1 : -1,
5816 len = this.items.length;
5818 if ( item instanceof OO.ui.OptionWidget ) {
5819 currentIndex = this.items.indexOf( item );
5820 nextIndex = ( currentIndex + increase + len ) % len;
5821 } else {
5822 // If no item is selected and moving forward, start at the beginning.
5823 // If moving backward, start at the end.
5824 nextIndex = direction > 0 ? 0 : len - 1;
5827 for ( i = 0; i < len; i++ ) {
5828 item = this.items[ nextIndex ];
5829 if (
5830 item instanceof OO.ui.OptionWidget && item.isSelectable() &&
5831 ( !filter || filter( item ) )
5833 return item;
5835 nextIndex = ( nextIndex + increase + len ) % len;
5837 return null;
5841 * Get the next selectable item or `null` if there are no selectable items.
5842 * Disabled options and menu-section markers and breaks are not selectable.
5844 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
5846 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
5847 return this.getRelativeSelectableItem( null, 1 );
5851 * Add an array of options to the select. Optionally, an index number can be used to
5852 * specify an insertion point.
5854 * @param {OO.ui.OptionWidget[]} items Items to add
5855 * @param {number} [index] Index to insert items after
5856 * @fires add
5857 * @chainable
5859 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
5860 // Mixin method
5861 OO.ui.mixin.GroupWidget.prototype.addItems.call( this, items, index );
5863 // Always provide an index, even if it was omitted
5864 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
5866 return this;
5870 * Remove the specified array of options from the select. Options will be detached
5871 * from the DOM, not removed, so they can be reused later. To remove all options from
5872 * the select, you may wish to use the #clearItems method instead.
5874 * @param {OO.ui.OptionWidget[]} items Items to remove
5875 * @fires remove
5876 * @chainable
5878 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
5879 var i, len, item;
5881 // Deselect items being removed
5882 for ( i = 0, len = items.length; i < len; i++ ) {
5883 item = items[ i ];
5884 if ( item.isSelected() ) {
5885 this.selectItem( null );
5889 // Mixin method
5890 OO.ui.mixin.GroupWidget.prototype.removeItems.call( this, items );
5892 this.emit( 'remove', items );
5894 return this;
5898 * Clear all options from the select. Options will be detached from the DOM, not removed,
5899 * so that they can be reused later. To remove a subset of options from the select, use
5900 * the #removeItems method.
5902 * @fires remove
5903 * @chainable
5905 OO.ui.SelectWidget.prototype.clearItems = function () {
5906 var items = this.items.slice();
5908 // Mixin method
5909 OO.ui.mixin.GroupWidget.prototype.clearItems.call( this );
5911 // Clear selection
5912 this.selectItem( null );
5914 this.emit( 'remove', items );
5916 return this;
5920 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
5921 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
5922 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
5923 * options. For more information about options and selects, please see the
5924 * [OOjs UI documentation on MediaWiki][1].
5926 * @example
5927 * // Decorated options in a select widget
5928 * var select = new OO.ui.SelectWidget( {
5929 * items: [
5930 * new OO.ui.DecoratedOptionWidget( {
5931 * data: 'a',
5932 * label: 'Option with icon',
5933 * icon: 'help'
5934 * } ),
5935 * new OO.ui.DecoratedOptionWidget( {
5936 * data: 'b',
5937 * label: 'Option with indicator',
5938 * indicator: 'next'
5939 * } )
5941 * } );
5942 * $( 'body' ).append( select.$element );
5944 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5946 * @class
5947 * @extends OO.ui.OptionWidget
5948 * @mixins OO.ui.mixin.IconElement
5949 * @mixins OO.ui.mixin.IndicatorElement
5951 * @constructor
5952 * @param {Object} [config] Configuration options
5954 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
5955 // Parent constructor
5956 OO.ui.DecoratedOptionWidget.parent.call( this, config );
5958 // Mixin constructors
5959 OO.ui.mixin.IconElement.call( this, config );
5960 OO.ui.mixin.IndicatorElement.call( this, config );
5962 // Initialization
5963 this.$element
5964 .addClass( 'oo-ui-decoratedOptionWidget' )
5965 .prepend( this.$icon )
5966 .append( this.$indicator );
5969 /* Setup */
5971 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
5972 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IconElement );
5973 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IndicatorElement );
5976 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
5977 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
5978 * the [OOjs UI documentation on MediaWiki] [1] for more information.
5980 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
5982 * @class
5983 * @extends OO.ui.DecoratedOptionWidget
5985 * @constructor
5986 * @param {Object} [config] Configuration options
5988 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
5989 // Configuration initialization
5990 config = $.extend( { icon: 'check' }, config );
5992 // Parent constructor
5993 OO.ui.MenuOptionWidget.parent.call( this, config );
5995 // Initialization
5996 this.$element
5997 .attr( 'role', 'menuitem' )
5998 .addClass( 'oo-ui-menuOptionWidget' );
6001 /* Setup */
6003 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
6005 /* Static Properties */
6007 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
6010 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
6011 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
6013 * @example
6014 * var myDropdown = new OO.ui.DropdownWidget( {
6015 * menu: {
6016 * items: [
6017 * new OO.ui.MenuSectionOptionWidget( {
6018 * label: 'Dogs'
6019 * } ),
6020 * new OO.ui.MenuOptionWidget( {
6021 * data: 'corgi',
6022 * label: 'Welsh Corgi'
6023 * } ),
6024 * new OO.ui.MenuOptionWidget( {
6025 * data: 'poodle',
6026 * label: 'Standard Poodle'
6027 * } ),
6028 * new OO.ui.MenuSectionOptionWidget( {
6029 * label: 'Cats'
6030 * } ),
6031 * new OO.ui.MenuOptionWidget( {
6032 * data: 'lion',
6033 * label: 'Lion'
6034 * } )
6037 * } );
6038 * $( 'body' ).append( myDropdown.$element );
6040 * @class
6041 * @extends OO.ui.DecoratedOptionWidget
6043 * @constructor
6044 * @param {Object} [config] Configuration options
6046 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
6047 // Parent constructor
6048 OO.ui.MenuSectionOptionWidget.parent.call( this, config );
6050 // Initialization
6051 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' );
6054 /* Setup */
6056 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
6058 /* Static Properties */
6060 OO.ui.MenuSectionOptionWidget.static.selectable = false;
6062 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
6065 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
6066 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
6067 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
6068 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
6069 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
6070 * and customized to be opened, closed, and displayed as needed.
6072 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
6073 * mouse outside the menu.
6075 * Menus also have support for keyboard interaction:
6077 * - Enter/Return key: choose and select a menu option
6078 * - Up-arrow key: highlight the previous menu option
6079 * - Down-arrow key: highlight the next menu option
6080 * - Esc key: hide the menu
6082 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
6083 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6085 * @class
6086 * @extends OO.ui.SelectWidget
6087 * @mixins OO.ui.mixin.ClippableElement
6089 * @constructor
6090 * @param {Object} [config] Configuration options
6091 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
6092 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
6093 * and {@link OO.ui.mixin.LookupElement LookupElement}
6094 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
6095 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiselectWidget CapsuleMultiselectWidget}
6096 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
6097 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
6098 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
6099 * that button, unless the button (or its parent widget) is passed in here.
6100 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
6101 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
6103 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
6104 // Configuration initialization
6105 config = config || {};
6107 // Parent constructor
6108 OO.ui.MenuSelectWidget.parent.call( this, config );
6110 // Mixin constructors
6111 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
6113 // Properties
6114 this.autoHide = config.autoHide === undefined || !!config.autoHide;
6115 this.filterFromInput = !!config.filterFromInput;
6116 this.$input = config.$input ? config.$input : config.input ? config.input.$input : null;
6117 this.$widget = config.widget ? config.widget.$element : null;
6118 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
6119 this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 );
6121 // Initialization
6122 this.$element
6123 .addClass( 'oo-ui-menuSelectWidget' )
6124 .attr( 'role', 'menu' );
6126 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
6127 // that reference properties not initialized at that time of parent class construction
6128 // TODO: Find a better way to handle post-constructor setup
6129 this.visible = false;
6130 this.$element.addClass( 'oo-ui-element-hidden' );
6133 /* Setup */
6135 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
6136 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement );
6138 /* Methods */
6141 * Handles document mouse down events.
6143 * @protected
6144 * @param {MouseEvent} e Mouse down event
6146 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
6147 if (
6148 !OO.ui.contains( this.$element[ 0 ], e.target, true ) &&
6149 ( !this.$widget || !OO.ui.contains( this.$widget[ 0 ], e.target, true ) )
6151 this.toggle( false );
6156 * @inheritdoc
6158 OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
6159 var currentItem = this.getHighlightedItem() || this.getSelectedItem();
6161 if ( !this.isDisabled() && this.isVisible() ) {
6162 switch ( e.keyCode ) {
6163 case OO.ui.Keys.LEFT:
6164 case OO.ui.Keys.RIGHT:
6165 // Do nothing if a text field is associated, arrow keys will be handled natively
6166 if ( !this.$input ) {
6167 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
6169 break;
6170 case OO.ui.Keys.ESCAPE:
6171 case OO.ui.Keys.TAB:
6172 if ( currentItem ) {
6173 currentItem.setHighlighted( false );
6175 this.toggle( false );
6176 // Don't prevent tabbing away, prevent defocusing
6177 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
6178 e.preventDefault();
6179 e.stopPropagation();
6181 break;
6182 default:
6183 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
6184 return;
6190 * Update menu item visibility after input changes.
6192 * @protected
6194 OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () {
6195 var i, item,
6196 len = this.items.length,
6197 showAll = !this.isVisible(),
6198 filter = showAll ? null : this.getItemMatcher( this.$input.val() );
6200 for ( i = 0; i < len; i++ ) {
6201 item = this.items[ i ];
6202 if ( item instanceof OO.ui.OptionWidget ) {
6203 item.toggle( showAll || filter( item ) );
6207 // Reevaluate clipping
6208 this.clip();
6212 * @inheritdoc
6214 OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
6215 if ( this.$input ) {
6216 this.$input.on( 'keydown', this.onKeyDownHandler );
6217 } else {
6218 OO.ui.MenuSelectWidget.parent.prototype.bindKeyDownListener.call( this );
6223 * @inheritdoc
6225 OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
6226 if ( this.$input ) {
6227 this.$input.off( 'keydown', this.onKeyDownHandler );
6228 } else {
6229 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyDownListener.call( this );
6234 * @inheritdoc
6236 OO.ui.MenuSelectWidget.prototype.bindKeyPressListener = function () {
6237 if ( this.$input ) {
6238 if ( this.filterFromInput ) {
6239 this.$input.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
6241 } else {
6242 OO.ui.MenuSelectWidget.parent.prototype.bindKeyPressListener.call( this );
6247 * @inheritdoc
6249 OO.ui.MenuSelectWidget.prototype.unbindKeyPressListener = function () {
6250 if ( this.$input ) {
6251 if ( this.filterFromInput ) {
6252 this.$input.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
6253 this.updateItemVisibility();
6255 } else {
6256 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyPressListener.call( this );
6261 * Choose an item.
6263 * When a user chooses an item, the menu is closed.
6265 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
6266 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
6268 * @param {OO.ui.OptionWidget} item Item to choose
6269 * @chainable
6271 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
6272 OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item );
6273 this.toggle( false );
6274 return this;
6278 * @inheritdoc
6280 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
6281 // Parent method
6282 OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index );
6284 // Reevaluate clipping
6285 this.clip();
6287 return this;
6291 * @inheritdoc
6293 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
6294 // Parent method
6295 OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items );
6297 // Reevaluate clipping
6298 this.clip();
6300 return this;
6304 * @inheritdoc
6306 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
6307 // Parent method
6308 OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this );
6310 // Reevaluate clipping
6311 this.clip();
6313 return this;
6317 * @inheritdoc
6319 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
6320 var change;
6322 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
6323 change = visible !== this.isVisible();
6325 // Parent method
6326 OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible );
6328 if ( change ) {
6329 if ( visible ) {
6330 this.bindKeyDownListener();
6331 this.bindKeyPressListener();
6333 this.toggleClipping( true );
6335 if ( this.getSelectedItem() ) {
6336 this.getSelectedItem().scrollElementIntoView( { duration: 0 } );
6339 // Auto-hide
6340 if ( this.autoHide ) {
6341 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
6343 } else {
6344 this.unbindKeyDownListener();
6345 this.unbindKeyPressListener();
6346 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
6347 this.toggleClipping( false );
6351 return this;
6355 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
6356 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
6357 * users can interact with it.
6359 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
6360 * OO.ui.DropdownInputWidget instead.
6362 * @example
6363 * // Example: A DropdownWidget with a menu that contains three options
6364 * var dropDown = new OO.ui.DropdownWidget( {
6365 * label: 'Dropdown menu: Select a menu option',
6366 * menu: {
6367 * items: [
6368 * new OO.ui.MenuOptionWidget( {
6369 * data: 'a',
6370 * label: 'First'
6371 * } ),
6372 * new OO.ui.MenuOptionWidget( {
6373 * data: 'b',
6374 * label: 'Second'
6375 * } ),
6376 * new OO.ui.MenuOptionWidget( {
6377 * data: 'c',
6378 * label: 'Third'
6379 * } )
6382 * } );
6384 * $( 'body' ).append( dropDown.$element );
6386 * dropDown.getMenu().selectItemByData( 'b' );
6388 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
6390 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
6392 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
6394 * @class
6395 * @extends OO.ui.Widget
6396 * @mixins OO.ui.mixin.IconElement
6397 * @mixins OO.ui.mixin.IndicatorElement
6398 * @mixins OO.ui.mixin.LabelElement
6399 * @mixins OO.ui.mixin.TitledElement
6400 * @mixins OO.ui.mixin.TabIndexedElement
6402 * @constructor
6403 * @param {Object} [config] Configuration options
6404 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
6405 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
6406 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
6407 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
6409 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
6410 // Configuration initialization
6411 config = $.extend( { indicator: 'down' }, config );
6413 // Parent constructor
6414 OO.ui.DropdownWidget.parent.call( this, config );
6416 // Properties (must be set before TabIndexedElement constructor call)
6417 this.$handle = this.$( '<span>' );
6418 this.$overlay = config.$overlay || this.$element;
6420 // Mixin constructors
6421 OO.ui.mixin.IconElement.call( this, config );
6422 OO.ui.mixin.IndicatorElement.call( this, config );
6423 OO.ui.mixin.LabelElement.call( this, config );
6424 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
6425 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
6427 // Properties
6428 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend( {
6429 widget: this,
6430 $container: this.$element
6431 }, config.menu ) );
6433 // Events
6434 this.$handle.on( {
6435 click: this.onClick.bind( this ),
6436 keydown: this.onKeyDown.bind( this ),
6437 // Hack? Handle type-to-search when menu is not expanded and not handling its own events
6438 keypress: this.menu.onKeyPressHandler,
6439 blur: this.menu.clearKeyPressBuffer.bind( this.menu )
6440 } );
6441 this.menu.connect( this, {
6442 select: 'onMenuSelect',
6443 toggle: 'onMenuToggle'
6444 } );
6446 // Initialization
6447 this.$handle
6448 .addClass( 'oo-ui-dropdownWidget-handle' )
6449 .append( this.$icon, this.$label, this.$indicator );
6450 this.$element
6451 .addClass( 'oo-ui-dropdownWidget' )
6452 .append( this.$handle );
6453 this.$overlay.append( this.menu.$element );
6456 /* Setup */
6458 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
6459 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IconElement );
6460 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IndicatorElement );
6461 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.LabelElement );
6462 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TitledElement );
6463 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TabIndexedElement );
6465 /* Methods */
6468 * Get the menu.
6470 * @return {OO.ui.MenuSelectWidget} Menu of widget
6472 OO.ui.DropdownWidget.prototype.getMenu = function () {
6473 return this.menu;
6477 * Handles menu select events.
6479 * @private
6480 * @param {OO.ui.MenuOptionWidget} item Selected menu item
6482 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
6483 var selectedLabel;
6485 if ( !item ) {
6486 this.setLabel( null );
6487 return;
6490 selectedLabel = item.getLabel();
6492 // If the label is a DOM element, clone it, because setLabel will append() it
6493 if ( selectedLabel instanceof jQuery ) {
6494 selectedLabel = selectedLabel.clone();
6497 this.setLabel( selectedLabel );
6501 * Handle menu toggle events.
6503 * @private
6504 * @param {boolean} isVisible Menu toggle event
6506 OO.ui.DropdownWidget.prototype.onMenuToggle = function ( isVisible ) {
6507 this.$element.toggleClass( 'oo-ui-dropdownWidget-open', isVisible );
6511 * Handle mouse click events.
6513 * @private
6514 * @param {jQuery.Event} e Mouse click event
6516 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
6517 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
6518 this.menu.toggle();
6520 return false;
6524 * Handle key down events.
6526 * @private
6527 * @param {jQuery.Event} e Key down event
6529 OO.ui.DropdownWidget.prototype.onKeyDown = function ( e ) {
6530 if (
6531 !this.isDisabled() &&
6533 e.which === OO.ui.Keys.ENTER ||
6535 !this.menu.isVisible() &&
6537 e.which === OO.ui.Keys.SPACE ||
6538 e.which === OO.ui.Keys.UP ||
6539 e.which === OO.ui.Keys.DOWN
6544 this.menu.toggle();
6545 return false;
6550 * RadioOptionWidget is an option widget that looks like a radio button.
6551 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
6552 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6554 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
6556 * @class
6557 * @extends OO.ui.OptionWidget
6559 * @constructor
6560 * @param {Object} [config] Configuration options
6562 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
6563 // Configuration initialization
6564 config = config || {};
6566 // Properties (must be done before parent constructor which calls #setDisabled)
6567 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
6569 // Parent constructor
6570 OO.ui.RadioOptionWidget.parent.call( this, config );
6572 // Initialization
6573 // Remove implicit role, we're handling it ourselves
6574 this.radio.$input.attr( 'role', 'presentation' );
6575 this.$element
6576 .addClass( 'oo-ui-radioOptionWidget' )
6577 .attr( 'role', 'radio' )
6578 .attr( 'aria-checked', 'false' )
6579 .removeAttr( 'aria-selected' )
6580 .prepend( this.radio.$element );
6583 /* Setup */
6585 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
6587 /* Static Properties */
6589 OO.ui.RadioOptionWidget.static.highlightable = false;
6591 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
6593 OO.ui.RadioOptionWidget.static.pressable = false;
6595 OO.ui.RadioOptionWidget.static.tagName = 'label';
6597 /* Methods */
6600 * @inheritdoc
6602 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
6603 OO.ui.RadioOptionWidget.parent.prototype.setSelected.call( this, state );
6605 this.radio.setSelected( state );
6606 this.$element
6607 .attr( 'aria-checked', state.toString() )
6608 .removeAttr( 'aria-selected' );
6610 return this;
6614 * @inheritdoc
6616 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
6617 OO.ui.RadioOptionWidget.parent.prototype.setDisabled.call( this, disabled );
6619 this.radio.setDisabled( this.isDisabled() );
6621 return this;
6625 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
6626 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
6627 * an interface for adding, removing and selecting options.
6628 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
6630 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
6631 * OO.ui.RadioSelectInputWidget instead.
6633 * @example
6634 * // A RadioSelectWidget with RadioOptions.
6635 * var option1 = new OO.ui.RadioOptionWidget( {
6636 * data: 'a',
6637 * label: 'Selected radio option'
6638 * } );
6640 * var option2 = new OO.ui.RadioOptionWidget( {
6641 * data: 'b',
6642 * label: 'Unselected radio option'
6643 * } );
6645 * var radioSelect=new OO.ui.RadioSelectWidget( {
6646 * items: [ option1, option2 ]
6647 * } );
6649 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
6650 * radioSelect.selectItem( option1 );
6652 * $( 'body' ).append( radioSelect.$element );
6654 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6657 * @class
6658 * @extends OO.ui.SelectWidget
6659 * @mixins OO.ui.mixin.TabIndexedElement
6661 * @constructor
6662 * @param {Object} [config] Configuration options
6664 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
6665 // Parent constructor
6666 OO.ui.RadioSelectWidget.parent.call( this, config );
6668 // Mixin constructors
6669 OO.ui.mixin.TabIndexedElement.call( this, config );
6671 // Events
6672 this.$element.on( {
6673 focus: this.bindKeyDownListener.bind( this ),
6674 blur: this.unbindKeyDownListener.bind( this )
6675 } );
6677 // Initialization
6678 this.$element
6679 .addClass( 'oo-ui-radioSelectWidget' )
6680 .attr( 'role', 'radiogroup' );
6683 /* Setup */
6685 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
6686 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.mixin.TabIndexedElement );
6689 * MultioptionWidgets are special elements that can be selected and configured with data. The
6690 * data is often unique for each option, but it does not have to be. MultioptionWidgets are used
6691 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
6692 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
6694 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Multioptions
6696 * @class
6697 * @extends OO.ui.Widget
6698 * @mixins OO.ui.mixin.ItemWidget
6699 * @mixins OO.ui.mixin.LabelElement
6701 * @constructor
6702 * @param {Object} [config] Configuration options
6703 * @cfg {boolean} [selected=false] Whether the option is initially selected
6705 OO.ui.MultioptionWidget = function OoUiMultioptionWidget( config ) {
6706 // Configuration initialization
6707 config = config || {};
6709 // Parent constructor
6710 OO.ui.MultioptionWidget.parent.call( this, config );
6712 // Mixin constructors
6713 OO.ui.mixin.ItemWidget.call( this );
6714 OO.ui.mixin.LabelElement.call( this, config );
6716 // Properties
6717 this.selected = null;
6719 // Initialization
6720 this.$element
6721 .addClass( 'oo-ui-multioptionWidget' )
6722 .append( this.$label );
6723 this.setSelected( config.selected );
6726 /* Setup */
6728 OO.inheritClass( OO.ui.MultioptionWidget, OO.ui.Widget );
6729 OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.ItemWidget );
6730 OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.LabelElement );
6732 /* Events */
6735 * @event change
6737 * A change event is emitted when the selected state of the option changes.
6739 * @param {boolean} selected Whether the option is now selected
6742 /* Methods */
6745 * Check if the option is selected.
6747 * @return {boolean} Item is selected
6749 OO.ui.MultioptionWidget.prototype.isSelected = function () {
6750 return this.selected;
6754 * Set the option’s selected state. In general, all modifications to the selection
6755 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
6756 * method instead of this method.
6758 * @param {boolean} [state=false] Select option
6759 * @chainable
6761 OO.ui.MultioptionWidget.prototype.setSelected = function ( state ) {
6762 state = !!state;
6763 if ( this.selected !== state ) {
6764 this.selected = state;
6765 this.emit( 'change', state );
6766 this.$element.toggleClass( 'oo-ui-multioptionWidget-selected', state );
6768 return this;
6772 * MultiselectWidget allows selecting multiple options from a list.
6774 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
6776 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
6778 * @class
6779 * @abstract
6780 * @extends OO.ui.Widget
6781 * @mixins OO.ui.mixin.GroupWidget
6783 * @constructor
6784 * @param {Object} [config] Configuration options
6785 * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
6787 OO.ui.MultiselectWidget = function OoUiMultiselectWidget( config ) {
6788 // Parent constructor
6789 OO.ui.MultiselectWidget.parent.call( this, config );
6791 // Configuration initialization
6792 config = config || {};
6794 // Mixin constructors
6795 OO.ui.mixin.GroupWidget.call( this, config );
6797 // Events
6798 this.aggregate( { change: 'select' } );
6799 // This is mostly for compatibility with CapsuleMultiselectWidget... normally, 'change' is emitted
6800 // by GroupElement only when items are added/removed
6801 this.connect( this, { select: [ 'emit', 'change' ] } );
6803 // Initialization
6804 if ( config.items ) {
6805 this.addItems( config.items );
6807 this.$group.addClass( 'oo-ui-multiselectWidget-group' );
6808 this.$element.addClass( 'oo-ui-multiselectWidget' )
6809 .append( this.$group );
6812 /* Setup */
6814 OO.inheritClass( OO.ui.MultiselectWidget, OO.ui.Widget );
6815 OO.mixinClass( OO.ui.MultiselectWidget, OO.ui.mixin.GroupWidget );
6817 /* Events */
6820 * @event change
6822 * A change event is emitted when the set of items changes, or an item is selected or deselected.
6826 * @event select
6828 * A select event is emitted when an item is selected or deselected.
6831 /* Methods */
6834 * Get options that are selected.
6836 * @return {OO.ui.MultioptionWidget[]} Selected options
6838 OO.ui.MultiselectWidget.prototype.getSelectedItems = function () {
6839 return this.items.filter( function ( item ) {
6840 return item.isSelected();
6841 } );
6845 * Get the data of options that are selected.
6847 * @return {Object[]|string[]} Values of selected options
6849 OO.ui.MultiselectWidget.prototype.getSelectedItemsData = function () {
6850 return this.getSelectedItems().map( function ( item ) {
6851 return item.data;
6852 } );
6856 * Select options by reference. Options not mentioned in the `items` array will be deselected.
6858 * @param {OO.ui.MultioptionWidget[]} items Items to select
6859 * @chainable
6861 OO.ui.MultiselectWidget.prototype.selectItems = function ( items ) {
6862 this.items.forEach( function ( item ) {
6863 var selected = items.indexOf( item ) !== -1;
6864 item.setSelected( selected );
6865 } );
6866 return this;
6870 * Select items by their data. Options not mentioned in the `datas` array will be deselected.
6872 * @param {Object[]|string[]} datas Values of items to select
6873 * @chainable
6875 OO.ui.MultiselectWidget.prototype.selectItemsByData = function ( datas ) {
6876 var items,
6877 widget = this;
6878 items = datas.map( function ( data ) {
6879 return widget.getItemFromData( data );
6880 } );
6881 this.selectItems( items );
6882 return this;
6886 * CheckboxMultioptionWidget is an option widget that looks like a checkbox.
6887 * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
6888 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6890 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
6892 * @class
6893 * @extends OO.ui.MultioptionWidget
6895 * @constructor
6896 * @param {Object} [config] Configuration options
6898 OO.ui.CheckboxMultioptionWidget = function OoUiCheckboxMultioptionWidget( config ) {
6899 // Configuration initialization
6900 config = config || {};
6902 // Properties (must be done before parent constructor which calls #setDisabled)
6903 this.checkbox = new OO.ui.CheckboxInputWidget();
6905 // Parent constructor
6906 OO.ui.CheckboxMultioptionWidget.parent.call( this, config );
6908 // Events
6909 this.checkbox.on( 'change', this.onCheckboxChange.bind( this ) );
6910 this.$element.on( 'keydown', this.onKeyDown.bind( this ) );
6912 // Initialization
6913 this.$element
6914 .addClass( 'oo-ui-checkboxMultioptionWidget' )
6915 .prepend( this.checkbox.$element );
6918 /* Setup */
6920 OO.inheritClass( OO.ui.CheckboxMultioptionWidget, OO.ui.MultioptionWidget );
6922 /* Static Properties */
6924 OO.ui.CheckboxMultioptionWidget.static.tagName = 'label';
6926 /* Methods */
6929 * Handle checkbox selected state change.
6931 * @private
6933 OO.ui.CheckboxMultioptionWidget.prototype.onCheckboxChange = function () {
6934 this.setSelected( this.checkbox.isSelected() );
6938 * @inheritdoc
6940 OO.ui.CheckboxMultioptionWidget.prototype.setSelected = function ( state ) {
6941 OO.ui.CheckboxMultioptionWidget.parent.prototype.setSelected.call( this, state );
6942 this.checkbox.setSelected( state );
6943 return this;
6947 * @inheritdoc
6949 OO.ui.CheckboxMultioptionWidget.prototype.setDisabled = function ( disabled ) {
6950 OO.ui.CheckboxMultioptionWidget.parent.prototype.setDisabled.call( this, disabled );
6951 this.checkbox.setDisabled( this.isDisabled() );
6952 return this;
6956 * Focus the widget.
6958 OO.ui.CheckboxMultioptionWidget.prototype.focus = function () {
6959 this.checkbox.focus();
6963 * Handle key down events.
6965 * @protected
6966 * @param {jQuery.Event} e
6968 OO.ui.CheckboxMultioptionWidget.prototype.onKeyDown = function ( e ) {
6970 element = this.getElementGroup(),
6971 nextItem;
6973 if ( e.keyCode === OO.ui.Keys.LEFT || e.keyCode === OO.ui.Keys.UP ) {
6974 nextItem = element.getRelativeFocusableItem( this, -1 );
6975 } else if ( e.keyCode === OO.ui.Keys.RIGHT || e.keyCode === OO.ui.Keys.DOWN ) {
6976 nextItem = element.getRelativeFocusableItem( this, 1 );
6979 if ( nextItem ) {
6980 e.preventDefault();
6981 nextItem.focus();
6986 * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
6987 * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
6988 * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
6989 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
6991 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
6992 * OO.ui.CheckboxMultiselectInputWidget instead.
6994 * @example
6995 * // A CheckboxMultiselectWidget with CheckboxMultioptions.
6996 * var option1 = new OO.ui.CheckboxMultioptionWidget( {
6997 * data: 'a',
6998 * selected: true,
6999 * label: 'Selected checkbox'
7000 * } );
7002 * var option2 = new OO.ui.CheckboxMultioptionWidget( {
7003 * data: 'b',
7004 * label: 'Unselected checkbox'
7005 * } );
7007 * var multiselect=new OO.ui.CheckboxMultiselectWidget( {
7008 * items: [ option1, option2 ]
7009 * } );
7011 * $( 'body' ).append( multiselect.$element );
7013 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
7015 * @class
7016 * @extends OO.ui.MultiselectWidget
7018 * @constructor
7019 * @param {Object} [config] Configuration options
7021 OO.ui.CheckboxMultiselectWidget = function OoUiCheckboxMultiselectWidget( config ) {
7022 // Parent constructor
7023 OO.ui.CheckboxMultiselectWidget.parent.call( this, config );
7025 // Properties
7026 this.$lastClicked = null;
7028 // Events
7029 this.$group.on( 'click', this.onClick.bind( this ) );
7031 // Initialization
7032 this.$element
7033 .addClass( 'oo-ui-checkboxMultiselectWidget' );
7036 /* Setup */
7038 OO.inheritClass( OO.ui.CheckboxMultiselectWidget, OO.ui.MultiselectWidget );
7040 /* Methods */
7043 * Get an option by its position relative to the specified item (or to the start of the option array,
7044 * if item is `null`). The direction in which to search through the option array is specified with a
7045 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
7046 * `null` if there are no options in the array.
7048 * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
7049 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
7050 * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items in the select
7052 OO.ui.CheckboxMultiselectWidget.prototype.getRelativeFocusableItem = function ( item, direction ) {
7053 var currentIndex, nextIndex, i,
7054 increase = direction > 0 ? 1 : -1,
7055 len = this.items.length;
7057 if ( item ) {
7058 currentIndex = this.items.indexOf( item );
7059 nextIndex = ( currentIndex + increase + len ) % len;
7060 } else {
7061 // If no item is selected and moving forward, start at the beginning.
7062 // If moving backward, start at the end.
7063 nextIndex = direction > 0 ? 0 : len - 1;
7066 for ( i = 0; i < len; i++ ) {
7067 item = this.items[ nextIndex ];
7068 if ( item && !item.isDisabled() ) {
7069 return item;
7071 nextIndex = ( nextIndex + increase + len ) % len;
7073 return null;
7077 * Handle click events on checkboxes.
7079 * @param {jQuery.Event} e
7081 OO.ui.CheckboxMultiselectWidget.prototype.onClick = function ( e ) {
7082 var $options, lastClickedIndex, nowClickedIndex, i, direction, wasSelected, items,
7083 $lastClicked = this.$lastClicked,
7084 $nowClicked = $( e.target ).closest( '.oo-ui-checkboxMultioptionWidget' )
7085 .not( '.oo-ui-widget-disabled' );
7087 // Allow selecting multiple options at once by Shift-clicking them
7088 if ( $lastClicked && $nowClicked.length && e.shiftKey ) {
7089 $options = this.$group.find( '.oo-ui-checkboxMultioptionWidget' );
7090 lastClickedIndex = $options.index( $lastClicked );
7091 nowClickedIndex = $options.index( $nowClicked );
7092 // If it's the same item, either the user is being silly, or it's a fake event generated by the
7093 // browser. In either case we don't need custom handling.
7094 if ( nowClickedIndex !== lastClickedIndex ) {
7095 items = this.items;
7096 wasSelected = items[ nowClickedIndex ].isSelected();
7097 direction = nowClickedIndex > lastClickedIndex ? 1 : -1;
7099 // This depends on the DOM order of the items and the order of the .items array being the same.
7100 for ( i = lastClickedIndex; i !== nowClickedIndex; i += direction ) {
7101 if ( !items[ i ].isDisabled() ) {
7102 items[ i ].setSelected( !wasSelected );
7105 // For the now-clicked element, use immediate timeout to allow the browser to do its own
7106 // handling first, then set our value. The order in which events happen is different for
7107 // clicks on the <input> and on the <label> and there are additional fake clicks fired for
7108 // non-click actions that change the checkboxes.
7109 e.preventDefault();
7110 setTimeout( function () {
7111 if ( !items[ nowClickedIndex ].isDisabled() ) {
7112 items[ nowClickedIndex ].setSelected( !wasSelected );
7114 } );
7118 if ( $nowClicked.length ) {
7119 this.$lastClicked = $nowClicked;
7124 * Element that will stick under a specified container, even when it is inserted elsewhere in the
7125 * document (for example, in a OO.ui.Window's $overlay).
7127 * The elements's position is automatically calculated and maintained when window is resized or the
7128 * page is scrolled. If you reposition the container manually, you have to call #position to make
7129 * sure the element is still placed correctly.
7131 * As positioning is only possible when both the element and the container are attached to the DOM
7132 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
7133 * the #toggle method to display a floating popup, for example.
7135 * @abstract
7136 * @class
7138 * @constructor
7139 * @param {Object} [config] Configuration options
7140 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
7141 * @cfg {jQuery} [$floatableContainer] Node to position below
7143 OO.ui.mixin.FloatableElement = function OoUiMixinFloatableElement( config ) {
7144 // Configuration initialization
7145 config = config || {};
7147 // Properties
7148 this.$floatable = null;
7149 this.$floatableContainer = null;
7150 this.$floatableWindow = null;
7151 this.$floatableClosestScrollable = null;
7152 this.onFloatableScrollHandler = this.position.bind( this );
7153 this.onFloatableWindowResizeHandler = this.position.bind( this );
7155 // Initialization
7156 this.setFloatableContainer( config.$floatableContainer );
7157 this.setFloatableElement( config.$floatable || this.$element );
7160 /* Methods */
7163 * Set floatable element.
7165 * If an element is already set, it will be cleaned up before setting up the new element.
7167 * @param {jQuery} $floatable Element to make floatable
7169 OO.ui.mixin.FloatableElement.prototype.setFloatableElement = function ( $floatable ) {
7170 if ( this.$floatable ) {
7171 this.$floatable.removeClass( 'oo-ui-floatableElement-floatable' );
7172 this.$floatable.css( { left: '', top: '' } );
7175 this.$floatable = $floatable.addClass( 'oo-ui-floatableElement-floatable' );
7176 this.position();
7180 * Set floatable container.
7182 * The element will be always positioned under the specified container.
7184 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
7186 OO.ui.mixin.FloatableElement.prototype.setFloatableContainer = function ( $floatableContainer ) {
7187 this.$floatableContainer = $floatableContainer;
7188 if ( this.$floatable ) {
7189 this.position();
7194 * Toggle positioning.
7196 * Do not turn positioning on until after the element is attached to the DOM and visible.
7198 * @param {boolean} [positioning] Enable positioning, omit to toggle
7199 * @chainable
7201 OO.ui.mixin.FloatableElement.prototype.togglePositioning = function ( positioning ) {
7202 var closestScrollableOfContainer, closestScrollableOfFloatable;
7204 positioning = positioning === undefined ? !this.positioning : !!positioning;
7206 if ( this.positioning !== positioning ) {
7207 this.positioning = positioning;
7209 closestScrollableOfContainer = OO.ui.Element.static.getClosestScrollableContainer( this.$floatableContainer[ 0 ] );
7210 closestScrollableOfFloatable = OO.ui.Element.static.getClosestScrollableContainer( this.$floatable[ 0 ] );
7211 this.needsCustomPosition = closestScrollableOfContainer !== closestScrollableOfFloatable;
7212 // If the scrollable is the root, we have to listen to scroll events
7213 // on the window because of browser inconsistencies.
7214 if ( $( closestScrollableOfContainer ).is( 'html, body' ) ) {
7215 closestScrollableOfContainer = OO.ui.Element.static.getWindow( closestScrollableOfContainer );
7218 if ( positioning ) {
7219 this.$floatableWindow = $( this.getElementWindow() );
7220 this.$floatableWindow.on( 'resize', this.onFloatableWindowResizeHandler );
7222 this.$floatableClosestScrollable = $( closestScrollableOfContainer );
7223 this.$floatableClosestScrollable.on( 'scroll', this.onFloatableScrollHandler );
7225 // Initial position after visible
7226 this.position();
7227 } else {
7228 if ( this.$floatableWindow ) {
7229 this.$floatableWindow.off( 'resize', this.onFloatableWindowResizeHandler );
7230 this.$floatableWindow = null;
7233 if ( this.$floatableClosestScrollable ) {
7234 this.$floatableClosestScrollable.off( 'scroll', this.onFloatableScrollHandler );
7235 this.$floatableClosestScrollable = null;
7238 this.$floatable.css( { left: '', top: '' } );
7242 return this;
7246 * Check whether the bottom edge of the given element is within the viewport of the given container.
7248 * @private
7249 * @param {jQuery} $element
7250 * @param {jQuery} $container
7251 * @return {boolean}
7253 OO.ui.mixin.FloatableElement.prototype.isElementInViewport = function ( $element, $container ) {
7254 var elemRect, contRect,
7255 leftEdgeInBounds = false,
7256 bottomEdgeInBounds = false,
7257 rightEdgeInBounds = false;
7259 elemRect = $element[ 0 ].getBoundingClientRect();
7260 if ( $container[ 0 ] === window ) {
7261 contRect = {
7262 top: 0,
7263 left: 0,
7264 right: document.documentElement.clientWidth,
7265 bottom: document.documentElement.clientHeight
7267 } else {
7268 contRect = $container[ 0 ].getBoundingClientRect();
7271 // For completeness, if we still cared about topEdgeInBounds, that'd be:
7272 // elemRect.top >= contRect.top && elemRect.top <= contRect.bottom
7273 if ( elemRect.left >= contRect.left && elemRect.left <= contRect.right ) {
7274 leftEdgeInBounds = true;
7276 if ( elemRect.bottom >= contRect.top && elemRect.bottom <= contRect.bottom ) {
7277 bottomEdgeInBounds = true;
7279 if ( elemRect.right >= contRect.left && elemRect.right <= contRect.right ) {
7280 rightEdgeInBounds = true;
7283 // We only care that any part of the bottom edge is visible
7284 return bottomEdgeInBounds && ( leftEdgeInBounds || rightEdgeInBounds );
7288 * Position the floatable below its container.
7290 * This should only be done when both of them are attached to the DOM and visible.
7292 * @chainable
7294 OO.ui.mixin.FloatableElement.prototype.position = function () {
7295 var pos;
7297 if ( !this.positioning ) {
7298 return this;
7301 if ( !this.isElementInViewport( this.$floatableContainer, this.$floatableClosestScrollable ) ) {
7302 this.$floatable.addClass( 'oo-ui-element-hidden' );
7303 return;
7304 } else {
7305 this.$floatable.removeClass( 'oo-ui-element-hidden' );
7308 if ( !this.needsCustomPosition ) {
7309 return;
7312 pos = OO.ui.Element.static.getRelativePosition( this.$floatableContainer, this.$floatable.offsetParent() );
7314 // Position under container
7315 pos.top += this.$floatableContainer.height();
7316 this.$floatable.css( pos );
7318 // We updated the position, so re-evaluate the clipping state.
7319 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
7320 // will not notice the need to update itself.)
7321 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
7322 // it not listen to the right events in the right places?
7323 if ( this.clip ) {
7324 this.clip();
7327 return this;
7331 * FloatingMenuSelectWidget is a menu that will stick under a specified
7332 * container, even when it is inserted elsewhere in the document (for example,
7333 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
7334 * menu from being clipped too aggresively.
7336 * The menu's position is automatically calculated and maintained when the menu
7337 * is toggled or the window is resized.
7339 * See OO.ui.ComboBoxInputWidget for an example of a widget that uses this class.
7341 * @class
7342 * @extends OO.ui.MenuSelectWidget
7343 * @mixins OO.ui.mixin.FloatableElement
7345 * @constructor
7346 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
7347 * Deprecated, omit this parameter and specify `$container` instead.
7348 * @param {Object} [config] Configuration options
7349 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
7351 OO.ui.FloatingMenuSelectWidget = function OoUiFloatingMenuSelectWidget( inputWidget, config ) {
7352 // Allow 'inputWidget' parameter and config for backwards compatibility
7353 if ( OO.isPlainObject( inputWidget ) && config === undefined ) {
7354 config = inputWidget;
7355 inputWidget = config.inputWidget;
7358 // Configuration initialization
7359 config = config || {};
7361 // Parent constructor
7362 OO.ui.FloatingMenuSelectWidget.parent.call( this, config );
7364 // Properties (must be set before mixin constructors)
7365 this.inputWidget = inputWidget; // For backwards compatibility
7366 this.$container = config.$container || this.inputWidget.$element;
7368 // Mixins constructors
7369 OO.ui.mixin.FloatableElement.call( this, $.extend( {}, config, { $floatableContainer: this.$container } ) );
7371 // Initialization
7372 this.$element.addClass( 'oo-ui-floatingMenuSelectWidget' );
7373 // For backwards compatibility
7374 this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' );
7377 /* Setup */
7379 OO.inheritClass( OO.ui.FloatingMenuSelectWidget, OO.ui.MenuSelectWidget );
7380 OO.mixinClass( OO.ui.FloatingMenuSelectWidget, OO.ui.mixin.FloatableElement );
7382 /* Methods */
7385 * @inheritdoc
7387 OO.ui.FloatingMenuSelectWidget.prototype.toggle = function ( visible ) {
7388 var change;
7389 visible = visible === undefined ? !this.isVisible() : !!visible;
7390 change = visible !== this.isVisible();
7392 if ( change && visible ) {
7393 // Make sure the width is set before the parent method runs.
7394 this.setIdealSize( this.$container.width() );
7397 // Parent method
7398 // This will call this.clip(), which is nonsensical since we're not positioned yet...
7399 OO.ui.FloatingMenuSelectWidget.parent.prototype.toggle.call( this, visible );
7401 if ( change ) {
7402 this.togglePositioning( this.isVisible() );
7405 return this;
7409 * The old name for the FloatingMenuSelectWidget widget, provided for backwards-compatibility.
7411 * @class
7412 * @extends OO.ui.FloatingMenuSelectWidget
7414 * @constructor
7415 * @deprecated since v0.12.5.
7417 OO.ui.TextInputMenuSelectWidget = function OoUiTextInputMenuSelectWidget() {
7418 OO.ui.warnDeprecation( 'TextInputMenuSelectWidget is deprecated. Use the FloatingMenuSelectWidget instead.' );
7419 // Parent constructor
7420 OO.ui.TextInputMenuSelectWidget.parent.apply( this, arguments );
7423 OO.inheritClass( OO.ui.TextInputMenuSelectWidget, OO.ui.FloatingMenuSelectWidget );
7426 * Progress bars visually display the status of an operation, such as a download,
7427 * and can be either determinate or indeterminate:
7429 * - **determinate** process bars show the percent of an operation that is complete.
7431 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
7432 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
7433 * not use percentages.
7435 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
7437 * @example
7438 * // Examples of determinate and indeterminate progress bars.
7439 * var progressBar1 = new OO.ui.ProgressBarWidget( {
7440 * progress: 33
7441 * } );
7442 * var progressBar2 = new OO.ui.ProgressBarWidget();
7444 * // Create a FieldsetLayout to layout progress bars
7445 * var fieldset = new OO.ui.FieldsetLayout;
7446 * fieldset.addItems( [
7447 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
7448 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
7449 * ] );
7450 * $( 'body' ).append( fieldset.$element );
7452 * @class
7453 * @extends OO.ui.Widget
7455 * @constructor
7456 * @param {Object} [config] Configuration options
7457 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
7458 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
7459 * By default, the progress bar is indeterminate.
7461 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
7462 // Configuration initialization
7463 config = config || {};
7465 // Parent constructor
7466 OO.ui.ProgressBarWidget.parent.call( this, config );
7468 // Properties
7469 this.$bar = $( '<div>' );
7470 this.progress = null;
7472 // Initialization
7473 this.setProgress( config.progress !== undefined ? config.progress : false );
7474 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
7475 this.$element
7476 .attr( {
7477 role: 'progressbar',
7478 'aria-valuemin': 0,
7479 'aria-valuemax': 100
7481 .addClass( 'oo-ui-progressBarWidget' )
7482 .append( this.$bar );
7485 /* Setup */
7487 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
7489 /* Static Properties */
7491 OO.ui.ProgressBarWidget.static.tagName = 'div';
7493 /* Methods */
7496 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
7498 * @return {number|boolean} Progress percent
7500 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
7501 return this.progress;
7505 * Set the percent of the process completed or `false` for an indeterminate process.
7507 * @param {number|boolean} progress Progress percent or `false` for indeterminate
7509 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
7510 this.progress = progress;
7512 if ( progress !== false ) {
7513 this.$bar.css( 'width', this.progress + '%' );
7514 this.$element.attr( 'aria-valuenow', this.progress );
7515 } else {
7516 this.$bar.css( 'width', '' );
7517 this.$element.removeAttr( 'aria-valuenow' );
7519 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress === false );
7523 * InputWidget is the base class for all input widgets, which
7524 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
7525 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
7526 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
7528 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7530 * @abstract
7531 * @class
7532 * @extends OO.ui.Widget
7533 * @mixins OO.ui.mixin.FlaggedElement
7534 * @mixins OO.ui.mixin.TabIndexedElement
7535 * @mixins OO.ui.mixin.TitledElement
7536 * @mixins OO.ui.mixin.AccessKeyedElement
7538 * @constructor
7539 * @param {Object} [config] Configuration options
7540 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
7541 * @cfg {string} [value=''] The value of the input.
7542 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
7543 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
7544 * before it is accepted.
7546 OO.ui.InputWidget = function OoUiInputWidget( config ) {
7547 // Configuration initialization
7548 config = config || {};
7550 // Parent constructor
7551 OO.ui.InputWidget.parent.call( this, config );
7553 // Properties
7554 // See #reusePreInfuseDOM about config.$input
7555 this.$input = config.$input || this.getInputElement( config );
7556 this.value = '';
7557 this.inputFilter = config.inputFilter;
7559 // Mixin constructors
7560 OO.ui.mixin.FlaggedElement.call( this, config );
7561 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
7562 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
7563 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$input } ) );
7565 // Events
7566 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
7568 // Initialization
7569 this.$input
7570 .addClass( 'oo-ui-inputWidget-input' )
7571 .attr( 'name', config.name )
7572 .prop( 'disabled', this.isDisabled() );
7573 this.$element
7574 .addClass( 'oo-ui-inputWidget' )
7575 .append( this.$input );
7576 this.setValue( config.value );
7577 if ( config.dir ) {
7578 this.setDir( config.dir );
7582 /* Setup */
7584 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
7585 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.FlaggedElement );
7586 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TabIndexedElement );
7587 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TitledElement );
7588 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.AccessKeyedElement );
7590 /* Static Properties */
7592 OO.ui.InputWidget.static.supportsSimpleLabel = true;
7594 /* Static Methods */
7597 * @inheritdoc
7599 OO.ui.InputWidget.static.reusePreInfuseDOM = function ( node, config ) {
7600 config = OO.ui.InputWidget.parent.static.reusePreInfuseDOM( node, config );
7601 // Reusing $input lets browsers preserve inputted values across page reloads (T114134)
7602 config.$input = $( node ).find( '.oo-ui-inputWidget-input' );
7603 return config;
7607 * @inheritdoc
7609 OO.ui.InputWidget.static.gatherPreInfuseState = function ( node, config ) {
7610 var state = OO.ui.InputWidget.parent.static.gatherPreInfuseState( node, config );
7611 if ( config.$input && config.$input.length ) {
7612 state.value = config.$input.val();
7613 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
7614 state.focus = config.$input.is( ':focus' );
7616 return state;
7619 /* Events */
7622 * @event change
7624 * A change event is emitted when the value of the input changes.
7626 * @param {string} value
7629 /* Methods */
7632 * Get input element.
7634 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
7635 * different circumstances. The element must have a `value` property (like form elements).
7637 * @protected
7638 * @param {Object} config Configuration options
7639 * @return {jQuery} Input element
7641 OO.ui.InputWidget.prototype.getInputElement = function () {
7642 return $( '<input>' );
7646 * Handle potentially value-changing events.
7648 * @private
7649 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
7651 OO.ui.InputWidget.prototype.onEdit = function () {
7652 var widget = this;
7653 if ( !this.isDisabled() ) {
7654 // Allow the stack to clear so the value will be updated
7655 setTimeout( function () {
7656 widget.setValue( widget.$input.val() );
7657 } );
7662 * Get the value of the input.
7664 * @return {string} Input value
7666 OO.ui.InputWidget.prototype.getValue = function () {
7667 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
7668 // it, and we won't know unless they're kind enough to trigger a 'change' event.
7669 var value = this.$input.val();
7670 if ( this.value !== value ) {
7671 this.setValue( value );
7673 return this.value;
7677 * Set the directionality of the input.
7679 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
7680 * @chainable
7682 OO.ui.InputWidget.prototype.setDir = function ( dir ) {
7683 this.$input.prop( 'dir', dir );
7684 return this;
7688 * Set the value of the input.
7690 * @param {string} value New value
7691 * @fires change
7692 * @chainable
7694 OO.ui.InputWidget.prototype.setValue = function ( value ) {
7695 value = this.cleanUpValue( value );
7696 // Update the DOM if it has changed. Note that with cleanUpValue, it
7697 // is possible for the DOM value to change without this.value changing.
7698 if ( this.$input.val() !== value ) {
7699 this.$input.val( value );
7701 if ( this.value !== value ) {
7702 this.value = value;
7703 this.emit( 'change', this.value );
7705 return this;
7709 * Clean up incoming value.
7711 * Ensures value is a string, and converts undefined and null to empty string.
7713 * @private
7714 * @param {string} value Original value
7715 * @return {string} Cleaned up value
7717 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
7718 if ( value === undefined || value === null ) {
7719 return '';
7720 } else if ( this.inputFilter ) {
7721 return this.inputFilter( String( value ) );
7722 } else {
7723 return String( value );
7728 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
7729 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
7730 * called directly.
7732 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
7733 if ( !this.isDisabled() ) {
7734 if ( this.$input.is( ':checkbox, :radio' ) ) {
7735 this.$input.click();
7737 if ( this.$input.is( ':input' ) ) {
7738 this.$input[ 0 ].focus();
7744 * @inheritdoc
7746 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
7747 OO.ui.InputWidget.parent.prototype.setDisabled.call( this, state );
7748 if ( this.$input ) {
7749 this.$input.prop( 'disabled', this.isDisabled() );
7751 return this;
7755 * Focus the input.
7757 * @chainable
7759 OO.ui.InputWidget.prototype.focus = function () {
7760 this.$input[ 0 ].focus();
7761 return this;
7765 * Blur the input.
7767 * @chainable
7769 OO.ui.InputWidget.prototype.blur = function () {
7770 this.$input[ 0 ].blur();
7771 return this;
7775 * @inheritdoc
7777 OO.ui.InputWidget.prototype.restorePreInfuseState = function ( state ) {
7778 OO.ui.InputWidget.parent.prototype.restorePreInfuseState.call( this, state );
7779 if ( state.value !== undefined && state.value !== this.getValue() ) {
7780 this.setValue( state.value );
7782 if ( state.focus ) {
7783 this.focus();
7788 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
7789 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
7790 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
7791 * HTML `<button>` (the default) or an HTML `<input>` tags. See the
7792 * [OOjs UI documentation on MediaWiki] [1] for more information.
7794 * @example
7795 * // A ButtonInputWidget rendered as an HTML button, the default.
7796 * var button = new OO.ui.ButtonInputWidget( {
7797 * label: 'Input button',
7798 * icon: 'check',
7799 * value: 'check'
7800 * } );
7801 * $( 'body' ).append( button.$element );
7803 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
7805 * @class
7806 * @extends OO.ui.InputWidget
7807 * @mixins OO.ui.mixin.ButtonElement
7808 * @mixins OO.ui.mixin.IconElement
7809 * @mixins OO.ui.mixin.IndicatorElement
7810 * @mixins OO.ui.mixin.LabelElement
7811 * @mixins OO.ui.mixin.TitledElement
7813 * @constructor
7814 * @param {Object} [config] Configuration options
7815 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
7816 * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
7817 * Widgets configured to be an `<input>` do not support {@link #icon icons} and {@link #indicator indicators},
7818 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
7819 * be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
7821 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
7822 // Configuration initialization
7823 config = $.extend( { type: 'button', useInputTag: false }, config );
7825 // See InputWidget#reusePreInfuseDOM about config.$input
7826 if ( config.$input ) {
7827 config.$input.empty();
7830 // Properties (must be set before parent constructor, which calls #setValue)
7831 this.useInputTag = config.useInputTag;
7833 // Parent constructor
7834 OO.ui.ButtonInputWidget.parent.call( this, config );
7836 // Mixin constructors
7837 OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
7838 OO.ui.mixin.IconElement.call( this, config );
7839 OO.ui.mixin.IndicatorElement.call( this, config );
7840 OO.ui.mixin.LabelElement.call( this, config );
7841 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
7843 // Initialization
7844 if ( !config.useInputTag ) {
7845 this.$input.append( this.$icon, this.$label, this.$indicator );
7847 this.$element.addClass( 'oo-ui-buttonInputWidget' );
7850 /* Setup */
7852 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
7853 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.ButtonElement );
7854 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IconElement );
7855 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IndicatorElement );
7856 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.LabelElement );
7857 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.TitledElement );
7859 /* Static Properties */
7862 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
7863 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
7865 OO.ui.ButtonInputWidget.static.supportsSimpleLabel = false;
7867 /* Methods */
7870 * @inheritdoc
7871 * @protected
7873 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
7874 var type;
7875 type = [ 'button', 'submit', 'reset' ].indexOf( config.type ) !== -1 ? config.type : 'button';
7876 return $( '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + type + '">' );
7880 * Set label value.
7882 * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
7884 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
7885 * text, or `null` for no label
7886 * @chainable
7888 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
7889 if ( typeof label === 'function' ) {
7890 label = OO.ui.resolveMsg( label );
7893 if ( this.useInputTag ) {
7894 // Discard non-plaintext labels
7895 if ( typeof label !== 'string' ) {
7896 label = '';
7899 this.$input.val( label );
7902 return OO.ui.mixin.LabelElement.prototype.setLabel.call( this, label );
7906 * Set the value of the input.
7908 * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
7909 * they do not support {@link #value values}.
7911 * @param {string} value New value
7912 * @chainable
7914 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
7915 if ( !this.useInputTag ) {
7916 OO.ui.ButtonInputWidget.parent.prototype.setValue.call( this, value );
7918 return this;
7922 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
7923 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
7924 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
7925 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
7927 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
7929 * @example
7930 * // An example of selected, unselected, and disabled checkbox inputs
7931 * var checkbox1=new OO.ui.CheckboxInputWidget( {
7932 * value: 'a',
7933 * selected: true
7934 * } );
7935 * var checkbox2=new OO.ui.CheckboxInputWidget( {
7936 * value: 'b'
7937 * } );
7938 * var checkbox3=new OO.ui.CheckboxInputWidget( {
7939 * value:'c',
7940 * disabled: true
7941 * } );
7942 * // Create a fieldset layout with fields for each checkbox.
7943 * var fieldset = new OO.ui.FieldsetLayout( {
7944 * label: 'Checkboxes'
7945 * } );
7946 * fieldset.addItems( [
7947 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
7948 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
7949 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
7950 * ] );
7951 * $( 'body' ).append( fieldset.$element );
7953 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7955 * @class
7956 * @extends OO.ui.InputWidget
7958 * @constructor
7959 * @param {Object} [config] Configuration options
7960 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
7962 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
7963 // Configuration initialization
7964 config = config || {};
7966 // Parent constructor
7967 OO.ui.CheckboxInputWidget.parent.call( this, config );
7969 // Initialization
7970 this.$element
7971 .addClass( 'oo-ui-checkboxInputWidget' )
7972 // Required for pretty styling in MediaWiki theme
7973 .append( $( '<span>' ) );
7974 this.setSelected( config.selected !== undefined ? config.selected : false );
7977 /* Setup */
7979 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
7981 /* Static Methods */
7984 * @inheritdoc
7986 OO.ui.CheckboxInputWidget.static.gatherPreInfuseState = function ( node, config ) {
7987 var state = OO.ui.CheckboxInputWidget.parent.static.gatherPreInfuseState( node, config );
7988 state.checked = config.$input.prop( 'checked' );
7989 return state;
7992 /* Methods */
7995 * @inheritdoc
7996 * @protected
7998 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
7999 return $( '<input>' ).attr( 'type', 'checkbox' );
8003 * @inheritdoc
8005 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
8006 var widget = this;
8007 if ( !this.isDisabled() ) {
8008 // Allow the stack to clear so the value will be updated
8009 setTimeout( function () {
8010 widget.setSelected( widget.$input.prop( 'checked' ) );
8011 } );
8016 * Set selection state of this checkbox.
8018 * @param {boolean} state `true` for selected
8019 * @chainable
8021 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
8022 state = !!state;
8023 if ( this.selected !== state ) {
8024 this.selected = state;
8025 this.$input.prop( 'checked', this.selected );
8026 this.emit( 'change', this.selected );
8028 return this;
8032 * Check if this checkbox is selected.
8034 * @return {boolean} Checkbox is selected
8036 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
8037 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
8038 // it, and we won't know unless they're kind enough to trigger a 'change' event.
8039 var selected = this.$input.prop( 'checked' );
8040 if ( this.selected !== selected ) {
8041 this.setSelected( selected );
8043 return this.selected;
8047 * @inheritdoc
8049 OO.ui.CheckboxInputWidget.prototype.restorePreInfuseState = function ( state ) {
8050 OO.ui.CheckboxInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
8051 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
8052 this.setSelected( state.checked );
8057 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
8058 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
8059 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
8060 * more information about input widgets.
8062 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
8063 * are no options. If no `value` configuration option is provided, the first option is selected.
8064 * If you need a state representing no value (no option being selected), use a DropdownWidget.
8066 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
8068 * @example
8069 * // Example: A DropdownInputWidget with three options
8070 * var dropdownInput = new OO.ui.DropdownInputWidget( {
8071 * options: [
8072 * { data: 'a', label: 'First' },
8073 * { data: 'b', label: 'Second'},
8074 * { data: 'c', label: 'Third' }
8076 * } );
8077 * $( 'body' ).append( dropdownInput.$element );
8079 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8081 * @class
8082 * @extends OO.ui.InputWidget
8083 * @mixins OO.ui.mixin.TitledElement
8085 * @constructor
8086 * @param {Object} [config] Configuration options
8087 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
8088 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
8090 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
8091 // Configuration initialization
8092 config = config || {};
8094 // See InputWidget#reusePreInfuseDOM about config.$input
8095 if ( config.$input ) {
8096 config.$input.addClass( 'oo-ui-element-hidden' );
8099 // Properties (must be done before parent constructor which calls #setDisabled)
8100 this.dropdownWidget = new OO.ui.DropdownWidget( config.dropdown );
8102 // Parent constructor
8103 OO.ui.DropdownInputWidget.parent.call( this, config );
8105 // Mixin constructors
8106 OO.ui.mixin.TitledElement.call( this, config );
8108 // Events
8109 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
8111 // Initialization
8112 this.setOptions( config.options || [] );
8113 this.$element
8114 .addClass( 'oo-ui-dropdownInputWidget' )
8115 .append( this.dropdownWidget.$element );
8118 /* Setup */
8120 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
8121 OO.mixinClass( OO.ui.DropdownInputWidget, OO.ui.mixin.TitledElement );
8123 /* Methods */
8126 * @inheritdoc
8127 * @protected
8129 OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
8130 return $( '<input>' ).attr( 'type', 'hidden' );
8134 * Handles menu select events.
8136 * @private
8137 * @param {OO.ui.MenuOptionWidget} item Selected menu item
8139 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
8140 this.setValue( item.getData() );
8144 * @inheritdoc
8146 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
8147 value = this.cleanUpValue( value );
8148 this.dropdownWidget.getMenu().selectItemByData( value );
8149 OO.ui.DropdownInputWidget.parent.prototype.setValue.call( this, value );
8150 return this;
8154 * @inheritdoc
8156 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
8157 this.dropdownWidget.setDisabled( state );
8158 OO.ui.DropdownInputWidget.parent.prototype.setDisabled.call( this, state );
8159 return this;
8163 * Set the options available for this input.
8165 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
8166 * @chainable
8168 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
8170 value = this.getValue(),
8171 widget = this;
8173 // Rebuild the dropdown menu
8174 this.dropdownWidget.getMenu()
8175 .clearItems()
8176 .addItems( options.map( function ( opt ) {
8177 var optValue = widget.cleanUpValue( opt.data );
8178 return new OO.ui.MenuOptionWidget( {
8179 data: optValue,
8180 label: opt.label !== undefined ? opt.label : optValue
8181 } );
8182 } ) );
8184 // Restore the previous value, or reset to something sensible
8185 if ( this.dropdownWidget.getMenu().getItemFromData( value ) ) {
8186 // Previous value is still available, ensure consistency with the dropdown
8187 this.setValue( value );
8188 } else {
8189 // No longer valid, reset
8190 if ( options.length ) {
8191 this.setValue( options[ 0 ].data );
8195 return this;
8199 * @inheritdoc
8201 OO.ui.DropdownInputWidget.prototype.focus = function () {
8202 this.dropdownWidget.getMenu().toggle( true );
8203 return this;
8207 * @inheritdoc
8209 OO.ui.DropdownInputWidget.prototype.blur = function () {
8210 this.dropdownWidget.getMenu().toggle( false );
8211 return this;
8215 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
8216 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
8217 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
8218 * please see the [OOjs UI documentation on MediaWiki][1].
8220 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
8222 * @example
8223 * // An example of selected, unselected, and disabled radio inputs
8224 * var radio1 = new OO.ui.RadioInputWidget( {
8225 * value: 'a',
8226 * selected: true
8227 * } );
8228 * var radio2 = new OO.ui.RadioInputWidget( {
8229 * value: 'b'
8230 * } );
8231 * var radio3 = new OO.ui.RadioInputWidget( {
8232 * value: 'c',
8233 * disabled: true
8234 * } );
8235 * // Create a fieldset layout with fields for each radio button.
8236 * var fieldset = new OO.ui.FieldsetLayout( {
8237 * label: 'Radio inputs'
8238 * } );
8239 * fieldset.addItems( [
8240 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
8241 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
8242 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
8243 * ] );
8244 * $( 'body' ).append( fieldset.$element );
8246 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8248 * @class
8249 * @extends OO.ui.InputWidget
8251 * @constructor
8252 * @param {Object} [config] Configuration options
8253 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
8255 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
8256 // Configuration initialization
8257 config = config || {};
8259 // Parent constructor
8260 OO.ui.RadioInputWidget.parent.call( this, config );
8262 // Initialization
8263 this.$element
8264 .addClass( 'oo-ui-radioInputWidget' )
8265 // Required for pretty styling in MediaWiki theme
8266 .append( $( '<span>' ) );
8267 this.setSelected( config.selected !== undefined ? config.selected : false );
8270 /* Setup */
8272 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
8274 /* Static Methods */
8277 * @inheritdoc
8279 OO.ui.RadioInputWidget.static.gatherPreInfuseState = function ( node, config ) {
8280 var state = OO.ui.RadioInputWidget.parent.static.gatherPreInfuseState( node, config );
8281 state.checked = config.$input.prop( 'checked' );
8282 return state;
8285 /* Methods */
8288 * @inheritdoc
8289 * @protected
8291 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
8292 return $( '<input>' ).attr( 'type', 'radio' );
8296 * @inheritdoc
8298 OO.ui.RadioInputWidget.prototype.onEdit = function () {
8299 // RadioInputWidget doesn't track its state.
8303 * Set selection state of this radio button.
8305 * @param {boolean} state `true` for selected
8306 * @chainable
8308 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
8309 // RadioInputWidget doesn't track its state.
8310 this.$input.prop( 'checked', state );
8311 return this;
8315 * Check if this radio button is selected.
8317 * @return {boolean} Radio is selected
8319 OO.ui.RadioInputWidget.prototype.isSelected = function () {
8320 return this.$input.prop( 'checked' );
8324 * @inheritdoc
8326 OO.ui.RadioInputWidget.prototype.restorePreInfuseState = function ( state ) {
8327 OO.ui.RadioInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
8328 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
8329 this.setSelected( state.checked );
8334 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
8335 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
8336 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
8337 * more information about input widgets.
8339 * This and OO.ui.DropdownInputWidget support the same configuration options.
8341 * @example
8342 * // Example: A RadioSelectInputWidget with three options
8343 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
8344 * options: [
8345 * { data: 'a', label: 'First' },
8346 * { data: 'b', label: 'Second'},
8347 * { data: 'c', label: 'Third' }
8349 * } );
8350 * $( 'body' ).append( radioSelectInput.$element );
8352 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8354 * @class
8355 * @extends OO.ui.InputWidget
8357 * @constructor
8358 * @param {Object} [config] Configuration options
8359 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
8361 OO.ui.RadioSelectInputWidget = function OoUiRadioSelectInputWidget( config ) {
8362 // Configuration initialization
8363 config = config || {};
8365 // Properties (must be done before parent constructor which calls #setDisabled)
8366 this.radioSelectWidget = new OO.ui.RadioSelectWidget();
8368 // Parent constructor
8369 OO.ui.RadioSelectInputWidget.parent.call( this, config );
8371 // Events
8372 this.radioSelectWidget.connect( this, { select: 'onMenuSelect' } );
8374 // Initialization
8375 this.setOptions( config.options || [] );
8376 this.$element
8377 .addClass( 'oo-ui-radioSelectInputWidget' )
8378 .append( this.radioSelectWidget.$element );
8381 /* Setup */
8383 OO.inheritClass( OO.ui.RadioSelectInputWidget, OO.ui.InputWidget );
8385 /* Static Properties */
8387 OO.ui.RadioSelectInputWidget.static.supportsSimpleLabel = false;
8389 /* Static Methods */
8392 * @inheritdoc
8394 OO.ui.RadioSelectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
8395 var state = OO.ui.RadioSelectInputWidget.parent.static.gatherPreInfuseState( node, config );
8396 state.value = $( node ).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
8397 return state;
8401 * @inheritdoc
8403 OO.ui.RadioSelectInputWidget.static.reusePreInfuseDOM = function ( node, config ) {
8404 config = OO.ui.RadioSelectInputWidget.parent.static.reusePreInfuseDOM( node, config );
8405 // Cannot reuse the `<input type=radio>` set
8406 delete config.$input;
8407 return config;
8410 /* Methods */
8413 * @inheritdoc
8414 * @protected
8416 OO.ui.RadioSelectInputWidget.prototype.getInputElement = function () {
8417 return $( '<input>' ).attr( 'type', 'hidden' );
8421 * Handles menu select events.
8423 * @private
8424 * @param {OO.ui.RadioOptionWidget} item Selected menu item
8426 OO.ui.RadioSelectInputWidget.prototype.onMenuSelect = function ( item ) {
8427 this.setValue( item.getData() );
8431 * @inheritdoc
8433 OO.ui.RadioSelectInputWidget.prototype.setValue = function ( value ) {
8434 value = this.cleanUpValue( value );
8435 this.radioSelectWidget.selectItemByData( value );
8436 OO.ui.RadioSelectInputWidget.parent.prototype.setValue.call( this, value );
8437 return this;
8441 * @inheritdoc
8443 OO.ui.RadioSelectInputWidget.prototype.setDisabled = function ( state ) {
8444 this.radioSelectWidget.setDisabled( state );
8445 OO.ui.RadioSelectInputWidget.parent.prototype.setDisabled.call( this, state );
8446 return this;
8450 * Set the options available for this input.
8452 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
8453 * @chainable
8455 OO.ui.RadioSelectInputWidget.prototype.setOptions = function ( options ) {
8457 value = this.getValue(),
8458 widget = this;
8460 // Rebuild the radioSelect menu
8461 this.radioSelectWidget
8462 .clearItems()
8463 .addItems( options.map( function ( opt ) {
8464 var optValue = widget.cleanUpValue( opt.data );
8465 return new OO.ui.RadioOptionWidget( {
8466 data: optValue,
8467 label: opt.label !== undefined ? opt.label : optValue
8468 } );
8469 } ) );
8471 // Restore the previous value, or reset to something sensible
8472 if ( this.radioSelectWidget.getItemFromData( value ) ) {
8473 // Previous value is still available, ensure consistency with the radioSelect
8474 this.setValue( value );
8475 } else {
8476 // No longer valid, reset
8477 if ( options.length ) {
8478 this.setValue( options[ 0 ].data );
8482 return this;
8486 * CheckboxMultiselectInputWidget is a
8487 * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
8488 * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
8489 * HTML `<input type=checkbox>` tags. Please see the [OOjs UI documentation on MediaWiki][1] for
8490 * more information about input widgets.
8492 * @example
8493 * // Example: A CheckboxMultiselectInputWidget with three options
8494 * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
8495 * options: [
8496 * { data: 'a', label: 'First' },
8497 * { data: 'b', label: 'Second'},
8498 * { data: 'c', label: 'Third' }
8500 * } );
8501 * $( 'body' ).append( multiselectInput.$element );
8503 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8505 * @class
8506 * @extends OO.ui.InputWidget
8508 * @constructor
8509 * @param {Object} [config] Configuration options
8510 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
8512 OO.ui.CheckboxMultiselectInputWidget = function OoUiCheckboxMultiselectInputWidget( config ) {
8513 // Configuration initialization
8514 config = config || {};
8516 // Properties (must be done before parent constructor which calls #setDisabled)
8517 this.checkboxMultiselectWidget = new OO.ui.CheckboxMultiselectWidget();
8519 // Parent constructor
8520 OO.ui.CheckboxMultiselectInputWidget.parent.call( this, config );
8522 // Properties
8523 this.inputName = config.name;
8525 // Initialization
8526 this.$element
8527 .addClass( 'oo-ui-checkboxMultiselectInputWidget' )
8528 .append( this.checkboxMultiselectWidget.$element );
8529 // We don't use this.$input, but rather the CheckboxInputWidgets inside each option
8530 this.$input.detach();
8531 this.setOptions( config.options || [] );
8532 // Have to repeat this from parent, as we need options to be set up for this to make sense
8533 this.setValue( config.value );
8536 /* Setup */
8538 OO.inheritClass( OO.ui.CheckboxMultiselectInputWidget, OO.ui.InputWidget );
8540 /* Static Properties */
8542 OO.ui.CheckboxMultiselectInputWidget.static.supportsSimpleLabel = false;
8544 /* Static Methods */
8547 * @inheritdoc
8549 OO.ui.CheckboxMultiselectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
8550 var state = OO.ui.CheckboxMultiselectInputWidget.parent.static.gatherPreInfuseState( node, config );
8551 state.value = $( node ).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
8552 .toArray().map( function ( el ) { return el.value; } );
8553 return state;
8557 * @inheritdoc
8559 OO.ui.CheckboxMultiselectInputWidget.static.reusePreInfuseDOM = function ( node, config ) {
8560 config = OO.ui.CheckboxMultiselectInputWidget.parent.static.reusePreInfuseDOM( node, config );
8561 // Cannot reuse the `<input type=checkbox>` set
8562 delete config.$input;
8563 return config;
8566 /* Methods */
8569 * @inheritdoc
8570 * @protected
8572 OO.ui.CheckboxMultiselectInputWidget.prototype.getInputElement = function () {
8573 // Actually unused
8574 return $( '<div>' );
8578 * @inheritdoc
8580 OO.ui.CheckboxMultiselectInputWidget.prototype.getValue = function () {
8581 var value = this.$element.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
8582 .toArray().map( function ( el ) { return el.value; } );
8583 if ( this.value !== value ) {
8584 this.setValue( value );
8586 return this.value;
8590 * @inheritdoc
8592 OO.ui.CheckboxMultiselectInputWidget.prototype.setValue = function ( value ) {
8593 value = this.cleanUpValue( value );
8594 this.checkboxMultiselectWidget.selectItemsByData( value );
8595 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.setValue.call( this, value );
8596 return this;
8600 * Clean up incoming value.
8602 * @param {string[]} value Original value
8603 * @return {string[]} Cleaned up value
8605 OO.ui.CheckboxMultiselectInputWidget.prototype.cleanUpValue = function ( value ) {
8606 var i, singleValue,
8607 cleanValue = [];
8608 if ( !Array.isArray( value ) ) {
8609 return cleanValue;
8611 for ( i = 0; i < value.length; i++ ) {
8612 singleValue =
8613 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.cleanUpValue.call( this, value[ i ] );
8614 // Remove options that we don't have here
8615 if ( !this.checkboxMultiselectWidget.getItemFromData( singleValue ) ) {
8616 continue;
8618 cleanValue.push( singleValue );
8620 return cleanValue;
8624 * @inheritdoc
8626 OO.ui.CheckboxMultiselectInputWidget.prototype.setDisabled = function ( state ) {
8627 this.checkboxMultiselectWidget.setDisabled( state );
8628 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.setDisabled.call( this, state );
8629 return this;
8633 * Set the options available for this input.
8635 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
8636 * @chainable
8638 OO.ui.CheckboxMultiselectInputWidget.prototype.setOptions = function ( options ) {
8639 var widget = this;
8641 // Rebuild the checkboxMultiselectWidget menu
8642 this.checkboxMultiselectWidget
8643 .clearItems()
8644 .addItems( options.map( function ( opt ) {
8645 var optValue, item;
8646 optValue =
8647 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.cleanUpValue.call( widget, opt.data );
8648 item = new OO.ui.CheckboxMultioptionWidget( {
8649 data: optValue,
8650 label: opt.label !== undefined ? opt.label : optValue
8651 } );
8652 // Set the 'name' and 'value' for form submission
8653 item.checkbox.$input.attr( 'name', widget.inputName );
8654 item.checkbox.setValue( optValue );
8655 return item;
8656 } ) );
8658 // Re-set the value, checking the checkboxes as needed.
8659 // This will also get rid of any stale options that we just removed.
8660 this.setValue( this.getValue() );
8662 return this;
8666 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
8667 * size of the field as well as its presentation. In addition, these widgets can be configured
8668 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
8669 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
8670 * which modifies incoming values rather than validating them.
8671 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
8673 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
8675 * @example
8676 * // Example of a text input widget
8677 * var textInput = new OO.ui.TextInputWidget( {
8678 * value: 'Text input'
8679 * } )
8680 * $( 'body' ).append( textInput.$element );
8682 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8684 * @class
8685 * @extends OO.ui.InputWidget
8686 * @mixins OO.ui.mixin.IconElement
8687 * @mixins OO.ui.mixin.IndicatorElement
8688 * @mixins OO.ui.mixin.PendingElement
8689 * @mixins OO.ui.mixin.LabelElement
8691 * @constructor
8692 * @param {Object} [config] Configuration options
8693 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
8694 * 'email', 'url', 'date', 'month' or 'number'. Ignored if `multiline` is true.
8696 * Some values of `type` result in additional behaviors:
8698 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
8699 * empties the text field
8700 * @cfg {string} [placeholder] Placeholder text
8701 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
8702 * instruct the browser to focus this widget.
8703 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
8704 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
8705 * @cfg {boolean} [multiline=false] Allow multiple lines of text
8706 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
8707 * specifies minimum number of rows to display.
8708 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
8709 * Use the #maxRows config to specify a maximum number of displayed rows.
8710 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
8711 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
8712 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
8713 * the value or placeholder text: `'before'` or `'after'`
8714 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
8715 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
8716 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
8717 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
8718 * (the value must contain only numbers); when RegExp, a regular expression that must match the
8719 * value for it to be considered valid; when Function, a function receiving the value as parameter
8720 * that must return true, or promise resolving to true, for it to be considered valid.
8722 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
8723 // Configuration initialization
8724 config = $.extend( {
8725 type: 'text',
8726 labelPosition: 'after'
8727 }, config );
8729 if ( config.type === 'search' ) {
8730 OO.ui.warnDeprecation( 'TextInputWidget: config.type=\'search\' is deprecated. Use the SearchInputWidget instead. See T148471 for details.' );
8731 if ( config.icon === undefined ) {
8732 config.icon = 'search';
8734 // indicator: 'clear' is set dynamically later, depending on value
8737 // Parent constructor
8738 OO.ui.TextInputWidget.parent.call( this, config );
8740 // Mixin constructors
8741 OO.ui.mixin.IconElement.call( this, config );
8742 OO.ui.mixin.IndicatorElement.call( this, config );
8743 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$input } ) );
8744 OO.ui.mixin.LabelElement.call( this, config );
8746 // Properties
8747 this.type = this.getSaneType( config );
8748 this.readOnly = false;
8749 this.required = false;
8750 this.multiline = !!config.multiline;
8751 this.autosize = !!config.autosize;
8752 this.minRows = config.rows !== undefined ? config.rows : '';
8753 this.maxRows = config.maxRows || Math.max( 2 * ( this.minRows || 0 ), 10 );
8754 this.validate = null;
8755 this.styleHeight = null;
8756 this.scrollWidth = null;
8758 // Clone for resizing
8759 if ( this.autosize ) {
8760 this.$clone = this.$input
8761 .clone()
8762 .insertAfter( this.$input )
8763 .attr( 'aria-hidden', 'true' )
8764 .addClass( 'oo-ui-element-hidden' );
8767 this.setValidation( config.validate );
8768 this.setLabelPosition( config.labelPosition );
8770 // Events
8771 this.$input.on( {
8772 keypress: this.onKeyPress.bind( this ),
8773 blur: this.onBlur.bind( this ),
8774 focus: this.onFocus.bind( this )
8775 } );
8776 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
8777 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
8778 this.on( 'labelChange', this.updatePosition.bind( this ) );
8779 this.connect( this, {
8780 change: 'onChange',
8781 disable: 'onDisable'
8782 } );
8783 this.on( 'change', OO.ui.debounce( this.onDebouncedChange.bind( this ), 250 ) );
8785 // Initialization
8786 this.$element
8787 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type )
8788 .append( this.$icon, this.$indicator );
8789 this.setReadOnly( !!config.readOnly );
8790 this.setRequired( !!config.required );
8791 this.updateSearchIndicator();
8792 if ( config.placeholder !== undefined ) {
8793 this.$input.attr( 'placeholder', config.placeholder );
8795 if ( config.maxLength !== undefined ) {
8796 this.$input.attr( 'maxlength', config.maxLength );
8798 if ( config.autofocus ) {
8799 this.$input.attr( 'autofocus', 'autofocus' );
8801 if ( config.autocomplete === false ) {
8802 this.$input.attr( 'autocomplete', 'off' );
8803 // Turning off autocompletion also disables "form caching" when the user navigates to a
8804 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
8805 $( window ).on( {
8806 beforeunload: function () {
8807 this.$input.removeAttr( 'autocomplete' );
8808 }.bind( this ),
8809 pageshow: function () {
8810 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
8811 // whole page... it shouldn't hurt, though.
8812 this.$input.attr( 'autocomplete', 'off' );
8813 }.bind( this )
8814 } );
8816 if ( this.multiline && config.rows ) {
8817 this.$input.attr( 'rows', config.rows );
8819 if ( this.label || config.autosize ) {
8820 this.isWaitingToBeAttached = true;
8821 this.installParentChangeDetector();
8825 /* Setup */
8827 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
8828 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IconElement );
8829 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IndicatorElement );
8830 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.PendingElement );
8831 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.LabelElement );
8833 /* Static Properties */
8835 OO.ui.TextInputWidget.static.validationPatterns = {
8836 'non-empty': /.+/,
8837 integer: /^\d+$/
8840 /* Static Methods */
8843 * @inheritdoc
8845 OO.ui.TextInputWidget.static.gatherPreInfuseState = function ( node, config ) {
8846 var state = OO.ui.TextInputWidget.parent.static.gatherPreInfuseState( node, config );
8847 if ( config.multiline ) {
8848 state.scrollTop = config.$input.scrollTop();
8850 return state;
8853 /* Events */
8856 * An `enter` event is emitted when the user presses 'enter' inside the text box.
8858 * Not emitted if the input is multiline.
8860 * @event enter
8864 * A `resize` event is emitted when autosize is set and the widget resizes
8866 * @event resize
8869 /* Methods */
8872 * Handle icon mouse down events.
8874 * @private
8875 * @param {jQuery.Event} e Mouse down event
8877 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
8878 if ( e.which === OO.ui.MouseButtons.LEFT ) {
8879 this.$input[ 0 ].focus();
8880 return false;
8885 * Handle indicator mouse down events.
8887 * @private
8888 * @param {jQuery.Event} e Mouse down event
8890 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
8891 if ( e.which === OO.ui.MouseButtons.LEFT ) {
8892 if ( this.type === 'search' ) {
8893 // Clear the text field
8894 this.setValue( '' );
8896 this.$input[ 0 ].focus();
8897 return false;
8902 * Handle key press events.
8904 * @private
8905 * @param {jQuery.Event} e Key press event
8906 * @fires enter If enter key is pressed and input is not multiline
8908 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
8909 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
8910 this.emit( 'enter', e );
8915 * Handle blur events.
8917 * @private
8918 * @param {jQuery.Event} e Blur event
8920 OO.ui.TextInputWidget.prototype.onBlur = function () {
8921 this.setValidityFlag();
8925 * Handle focus events.
8927 * @private
8928 * @param {jQuery.Event} e Focus event
8930 OO.ui.TextInputWidget.prototype.onFocus = function () {
8931 if ( this.isWaitingToBeAttached ) {
8932 // If we've received focus, then we must be attached to the document, and if
8933 // isWaitingToBeAttached is still true, that means the handler never fired. Fire it now.
8934 this.onElementAttach();
8936 this.setValidityFlag( true );
8940 * Handle element attach events.
8942 * @private
8943 * @param {jQuery.Event} e Element attach event
8945 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
8946 this.isWaitingToBeAttached = false;
8947 // Any previously calculated size is now probably invalid if we reattached elsewhere
8948 this.valCache = null;
8949 this.adjustSize();
8950 this.positionLabel();
8954 * Handle change events.
8956 * @param {string} value
8957 * @private
8959 OO.ui.TextInputWidget.prototype.onChange = function () {
8960 this.updateSearchIndicator();
8961 this.adjustSize();
8965 * Handle debounced change events.
8967 * @param {string} value
8968 * @private
8970 OO.ui.TextInputWidget.prototype.onDebouncedChange = function () {
8971 this.setValidityFlag();
8975 * Handle disable events.
8977 * @param {boolean} disabled Element is disabled
8978 * @private
8980 OO.ui.TextInputWidget.prototype.onDisable = function () {
8981 this.updateSearchIndicator();
8985 * Check if the input is {@link #readOnly read-only}.
8987 * @return {boolean}
8989 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
8990 return this.readOnly;
8994 * Set the {@link #readOnly read-only} state of the input.
8996 * @param {boolean} state Make input read-only
8997 * @chainable
8999 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
9000 this.readOnly = !!state;
9001 this.$input.prop( 'readOnly', this.readOnly );
9002 this.updateSearchIndicator();
9003 return this;
9007 * Check if the input is {@link #required required}.
9009 * @return {boolean}
9011 OO.ui.TextInputWidget.prototype.isRequired = function () {
9012 return this.required;
9016 * Set the {@link #required required} state of the input.
9018 * @param {boolean} state Make input required
9019 * @chainable
9021 OO.ui.TextInputWidget.prototype.setRequired = function ( state ) {
9022 this.required = !!state;
9023 if ( this.required ) {
9024 this.$input
9025 .attr( 'required', 'required' )
9026 .attr( 'aria-required', 'true' );
9027 if ( this.getIndicator() === null ) {
9028 this.setIndicator( 'required' );
9030 } else {
9031 this.$input
9032 .removeAttr( 'required' )
9033 .removeAttr( 'aria-required' );
9034 if ( this.getIndicator() === 'required' ) {
9035 this.setIndicator( null );
9038 this.updateSearchIndicator();
9039 return this;
9043 * Support function for making #onElementAttach work across browsers.
9045 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
9046 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
9048 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
9049 * first time that the element gets attached to the documented.
9051 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
9052 var mutationObserver, onRemove, topmostNode, fakeParentNode,
9053 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
9054 widget = this;
9056 if ( MutationObserver ) {
9057 // The new way. If only it wasn't so ugly.
9059 if ( this.isElementAttached() ) {
9060 // Widget is attached already, do nothing. This breaks the functionality of this function when
9061 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
9062 // would require observation of the whole document, which would hurt performance of other,
9063 // more important code.
9064 return;
9067 // Find topmost node in the tree
9068 topmostNode = this.$element[ 0 ];
9069 while ( topmostNode.parentNode ) {
9070 topmostNode = topmostNode.parentNode;
9073 // We have no way to detect the $element being attached somewhere without observing the entire
9074 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
9075 // parent node of $element, and instead detect when $element is removed from it (and thus
9076 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
9077 // doesn't get attached, we end up back here and create the parent.
9079 mutationObserver = new MutationObserver( function ( mutations ) {
9080 var i, j, removedNodes;
9081 for ( i = 0; i < mutations.length; i++ ) {
9082 removedNodes = mutations[ i ].removedNodes;
9083 for ( j = 0; j < removedNodes.length; j++ ) {
9084 if ( removedNodes[ j ] === topmostNode ) {
9085 setTimeout( onRemove, 0 );
9086 return;
9090 } );
9092 onRemove = function () {
9093 // If the node was attached somewhere else, report it
9094 if ( widget.isElementAttached() ) {
9095 widget.onElementAttach();
9097 mutationObserver.disconnect();
9098 widget.installParentChangeDetector();
9101 // Create a fake parent and observe it
9102 fakeParentNode = $( '<div>' ).append( topmostNode )[ 0 ];
9103 mutationObserver.observe( fakeParentNode, { childList: true } );
9104 } else {
9105 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
9106 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
9107 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
9112 * Automatically adjust the size of the text input.
9114 * This only affects #multiline inputs that are {@link #autosize autosized}.
9116 * @chainable
9117 * @fires resize
9119 OO.ui.TextInputWidget.prototype.adjustSize = function () {
9120 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError,
9121 idealHeight, newHeight, scrollWidth, property;
9123 if ( this.isWaitingToBeAttached ) {
9124 // #onElementAttach will be called soon, which calls this method
9125 return this;
9128 if ( this.multiline && this.$input.val() !== this.valCache ) {
9129 if ( this.autosize ) {
9130 this.$clone
9131 .val( this.$input.val() )
9132 .attr( 'rows', this.minRows )
9133 // Set inline height property to 0 to measure scroll height
9134 .css( 'height', 0 );
9136 this.$clone.removeClass( 'oo-ui-element-hidden' );
9138 this.valCache = this.$input.val();
9140 scrollHeight = this.$clone[ 0 ].scrollHeight;
9142 // Remove inline height property to measure natural heights
9143 this.$clone.css( 'height', '' );
9144 innerHeight = this.$clone.innerHeight();
9145 outerHeight = this.$clone.outerHeight();
9147 // Measure max rows height
9148 this.$clone
9149 .attr( 'rows', this.maxRows )
9150 .css( 'height', 'auto' )
9151 .val( '' );
9152 maxInnerHeight = this.$clone.innerHeight();
9154 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
9155 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
9156 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
9157 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
9159 this.$clone.addClass( 'oo-ui-element-hidden' );
9161 // Only apply inline height when expansion beyond natural height is needed
9162 // Use the difference between the inner and outer height as a buffer
9163 newHeight = idealHeight > innerHeight ? idealHeight + ( outerHeight - innerHeight ) : '';
9164 if ( newHeight !== this.styleHeight ) {
9165 this.$input.css( 'height', newHeight );
9166 this.styleHeight = newHeight;
9167 this.emit( 'resize' );
9170 scrollWidth = this.$input[ 0 ].offsetWidth - this.$input[ 0 ].clientWidth;
9171 if ( scrollWidth !== this.scrollWidth ) {
9172 property = this.$element.css( 'direction' ) === 'rtl' ? 'left' : 'right';
9173 // Reset
9174 this.$label.css( { right: '', left: '' } );
9175 this.$indicator.css( { right: '', left: '' } );
9177 if ( scrollWidth ) {
9178 this.$indicator.css( property, scrollWidth );
9179 if ( this.labelPosition === 'after' ) {
9180 this.$label.css( property, scrollWidth );
9184 this.scrollWidth = scrollWidth;
9185 this.positionLabel();
9188 return this;
9192 * @inheritdoc
9193 * @protected
9195 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
9196 if ( config.multiline ) {
9197 return $( '<textarea>' );
9198 } else if ( this.getSaneType( config ) === 'number' ) {
9199 return $( '<input>' )
9200 .attr( 'step', 'any' )
9201 .attr( 'type', 'number' );
9202 } else {
9203 return $( '<input>' ).attr( 'type', this.getSaneType( config ) );
9208 * Get sanitized value for 'type' for given config.
9210 * @param {Object} config Configuration options
9211 * @return {string|null}
9212 * @private
9214 OO.ui.TextInputWidget.prototype.getSaneType = function ( config ) {
9215 var allowedTypes = [
9216 'text',
9217 'password',
9218 'search',
9219 'email',
9220 'url',
9221 'date',
9222 'month',
9223 'number'
9225 return allowedTypes.indexOf( config.type ) !== -1 ? config.type : 'text';
9229 * Check if the input supports multiple lines.
9231 * @return {boolean}
9233 OO.ui.TextInputWidget.prototype.isMultiline = function () {
9234 return !!this.multiline;
9238 * Check if the input automatically adjusts its size.
9240 * @return {boolean}
9242 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
9243 return !!this.autosize;
9247 * Focus the input and select a specified range within the text.
9249 * @param {number} from Select from offset
9250 * @param {number} [to] Select to offset, defaults to from
9251 * @chainable
9253 OO.ui.TextInputWidget.prototype.selectRange = function ( from, to ) {
9254 var isBackwards, start, end,
9255 input = this.$input[ 0 ];
9257 to = to || from;
9259 isBackwards = to < from;
9260 start = isBackwards ? to : from;
9261 end = isBackwards ? from : to;
9263 this.focus();
9265 try {
9266 input.setSelectionRange( start, end, isBackwards ? 'backward' : 'forward' );
9267 } catch ( e ) {
9268 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
9269 // Rather than expensively check if the input is attached every time, just check
9270 // if it was the cause of an error being thrown. If not, rethrow the error.
9271 if ( this.getElementDocument().body.contains( input ) ) {
9272 throw e;
9275 return this;
9279 * Get an object describing the current selection range in a directional manner
9281 * @return {Object} Object containing 'from' and 'to' offsets
9283 OO.ui.TextInputWidget.prototype.getRange = function () {
9284 var input = this.$input[ 0 ],
9285 start = input.selectionStart,
9286 end = input.selectionEnd,
9287 isBackwards = input.selectionDirection === 'backward';
9289 return {
9290 from: isBackwards ? end : start,
9291 to: isBackwards ? start : end
9296 * Get the length of the text input value.
9298 * This could differ from the length of #getValue if the
9299 * value gets filtered
9301 * @return {number} Input length
9303 OO.ui.TextInputWidget.prototype.getInputLength = function () {
9304 return this.$input[ 0 ].value.length;
9308 * Focus the input and select the entire text.
9310 * @chainable
9312 OO.ui.TextInputWidget.prototype.select = function () {
9313 return this.selectRange( 0, this.getInputLength() );
9317 * Focus the input and move the cursor to the start.
9319 * @chainable
9321 OO.ui.TextInputWidget.prototype.moveCursorToStart = function () {
9322 return this.selectRange( 0 );
9326 * Focus the input and move the cursor to the end.
9328 * @chainable
9330 OO.ui.TextInputWidget.prototype.moveCursorToEnd = function () {
9331 return this.selectRange( this.getInputLength() );
9335 * Insert new content into the input.
9337 * @param {string} content Content to be inserted
9338 * @chainable
9340 OO.ui.TextInputWidget.prototype.insertContent = function ( content ) {
9341 var start, end,
9342 range = this.getRange(),
9343 value = this.getValue();
9345 start = Math.min( range.from, range.to );
9346 end = Math.max( range.from, range.to );
9348 this.setValue( value.slice( 0, start ) + content + value.slice( end ) );
9349 this.selectRange( start + content.length );
9350 return this;
9354 * Insert new content either side of a selection.
9356 * @param {string} pre Content to be inserted before the selection
9357 * @param {string} post Content to be inserted after the selection
9358 * @chainable
9360 OO.ui.TextInputWidget.prototype.encapsulateContent = function ( pre, post ) {
9361 var start, end,
9362 range = this.getRange(),
9363 offset = pre.length;
9365 start = Math.min( range.from, range.to );
9366 end = Math.max( range.from, range.to );
9368 this.selectRange( start ).insertContent( pre );
9369 this.selectRange( offset + end ).insertContent( post );
9371 this.selectRange( offset + start, offset + end );
9372 return this;
9376 * Set the validation pattern.
9378 * The validation pattern is either a regular expression, a function, or the symbolic name of a
9379 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
9380 * value must contain only numbers).
9382 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
9383 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
9385 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
9386 if ( validate instanceof RegExp || validate instanceof Function ) {
9387 this.validate = validate;
9388 } else {
9389 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
9394 * Sets the 'invalid' flag appropriately.
9396 * @param {boolean} [isValid] Optionally override validation result
9398 OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) {
9399 var widget = this,
9400 setFlag = function ( valid ) {
9401 if ( !valid ) {
9402 widget.$input.attr( 'aria-invalid', 'true' );
9403 } else {
9404 widget.$input.removeAttr( 'aria-invalid' );
9406 widget.setFlags( { invalid: !valid } );
9409 if ( isValid !== undefined ) {
9410 setFlag( isValid );
9411 } else {
9412 this.getValidity().then( function () {
9413 setFlag( true );
9414 }, function () {
9415 setFlag( false );
9416 } );
9421 * Get the validity of current value.
9423 * This method returns a promise that resolves if the value is valid and rejects if
9424 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
9426 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
9428 OO.ui.TextInputWidget.prototype.getValidity = function () {
9429 var result;
9431 function rejectOrResolve( valid ) {
9432 if ( valid ) {
9433 return $.Deferred().resolve().promise();
9434 } else {
9435 return $.Deferred().reject().promise();
9439 if ( this.validate instanceof Function ) {
9440 result = this.validate( this.getValue() );
9441 if ( result && $.isFunction( result.promise ) ) {
9442 return result.promise().then( function ( valid ) {
9443 return rejectOrResolve( valid );
9444 } );
9445 } else {
9446 return rejectOrResolve( result );
9448 } else {
9449 return rejectOrResolve( this.getValue().match( this.validate ) );
9454 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
9456 * @param {string} labelPosition Label position, 'before' or 'after'
9457 * @chainable
9459 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
9460 this.labelPosition = labelPosition;
9461 if ( this.label ) {
9462 // If there is no label and we only change the position, #updatePosition is a no-op,
9463 // but it takes really a lot of work to do nothing.
9464 this.updatePosition();
9466 return this;
9470 * Update the position of the inline label.
9472 * This method is called by #setLabelPosition, and can also be called on its own if
9473 * something causes the label to be mispositioned.
9475 * @chainable
9477 OO.ui.TextInputWidget.prototype.updatePosition = function () {
9478 var after = this.labelPosition === 'after';
9480 this.$element
9481 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
9482 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
9484 this.valCache = null;
9485 this.scrollWidth = null;
9486 this.adjustSize();
9487 this.positionLabel();
9489 return this;
9493 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
9494 * already empty or when it's not editable.
9496 OO.ui.TextInputWidget.prototype.updateSearchIndicator = function () {
9497 if ( this.type === 'search' ) {
9498 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
9499 this.setIndicator( null );
9500 } else {
9501 this.setIndicator( 'clear' );
9507 * Position the label by setting the correct padding on the input.
9509 * @private
9510 * @chainable
9512 OO.ui.TextInputWidget.prototype.positionLabel = function () {
9513 var after, rtl, property;
9515 if ( this.isWaitingToBeAttached ) {
9516 // #onElementAttach will be called soon, which calls this method
9517 return this;
9520 // Clear old values
9521 this.$input
9522 // Clear old values if present
9523 .css( {
9524 'padding-right': '',
9525 'padding-left': ''
9526 } );
9528 if ( this.label ) {
9529 this.$element.append( this.$label );
9530 } else {
9531 this.$label.detach();
9532 return;
9535 after = this.labelPosition === 'after';
9536 rtl = this.$element.css( 'direction' ) === 'rtl';
9537 property = after === rtl ? 'padding-left' : 'padding-right';
9539 this.$input.css( property, this.$label.outerWidth( true ) + ( after ? this.scrollWidth : 0 ) );
9541 return this;
9545 * @inheritdoc
9547 OO.ui.TextInputWidget.prototype.restorePreInfuseState = function ( state ) {
9548 OO.ui.TextInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
9549 if ( state.scrollTop !== undefined ) {
9550 this.$input.scrollTop( state.scrollTop );
9555 * @class
9556 * @extends OO.ui.TextInputWidget
9558 * @constructor
9559 * @param {Object} [config] Configuration options
9561 OO.ui.SearchInputWidget = function OoUiSearchInputWidget( config ) {
9562 config = $.extend( {
9563 icon: 'search'
9564 }, config );
9566 // Set type to text so that TextInputWidget doesn't
9567 // get stuck in an infinite loop.
9568 config.type = 'text';
9570 // Parent constructor
9571 OO.ui.SearchInputWidget.parent.call( this, config );
9573 // Initialization
9574 this.$element.addClass( 'oo-ui-textInputWidget-type-search' );
9575 this.updateSearchIndicator();
9576 this.connect( this, {
9577 disable: 'onDisable'
9578 } );
9581 /* Setup */
9583 OO.inheritClass( OO.ui.SearchInputWidget, OO.ui.TextInputWidget );
9585 /* Methods */
9588 * @inheritdoc
9589 * @protected
9591 OO.ui.SearchInputWidget.prototype.getInputElement = function () {
9592 return $( '<input>' ).attr( 'type', 'search' );
9596 * @inheritdoc
9598 OO.ui.SearchInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
9599 if ( e.which === OO.ui.MouseButtons.LEFT ) {
9600 // Clear the text field
9601 this.setValue( '' );
9602 this.$input[ 0 ].focus();
9603 return false;
9608 * Update the 'clear' indicator displayed on type: 'search' text
9609 * fields, hiding it when the field is already empty or when it's not
9610 * editable.
9612 OO.ui.SearchInputWidget.prototype.updateSearchIndicator = function () {
9613 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
9614 this.setIndicator( null );
9615 } else {
9616 this.setIndicator( 'clear' );
9621 * @inheritdoc
9623 OO.ui.SearchInputWidget.prototype.onChange = function () {
9624 OO.ui.SearchInputWidget.parent.prototype.onChange.call( this );
9625 this.updateSearchIndicator();
9629 * Handle disable events.
9631 * @param {boolean} disabled Element is disabled
9632 * @private
9634 OO.ui.SearchInputWidget.prototype.onDisable = function () {
9635 this.updateSearchIndicator();
9639 * @inheritdoc
9641 OO.ui.SearchInputWidget.prototype.setReadOnly = function ( state ) {
9642 OO.ui.SearchInputWidget.parent.prototype.setReadOnly.call( this, state );
9643 this.updateSearchIndicator();
9644 return this;
9648 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
9649 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
9650 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
9652 * - by typing a value in the text input field. If the value exactly matches the value of a menu
9653 * option, that option will appear to be selected.
9654 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
9655 * input field.
9657 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9659 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
9661 * @example
9662 * // Example: A ComboBoxInputWidget.
9663 * var comboBox = new OO.ui.ComboBoxInputWidget( {
9664 * label: 'ComboBoxInputWidget',
9665 * value: 'Option 1',
9666 * menu: {
9667 * items: [
9668 * new OO.ui.MenuOptionWidget( {
9669 * data: 'Option 1',
9670 * label: 'Option One'
9671 * } ),
9672 * new OO.ui.MenuOptionWidget( {
9673 * data: 'Option 2',
9674 * label: 'Option Two'
9675 * } ),
9676 * new OO.ui.MenuOptionWidget( {
9677 * data: 'Option 3',
9678 * label: 'Option Three'
9679 * } ),
9680 * new OO.ui.MenuOptionWidget( {
9681 * data: 'Option 4',
9682 * label: 'Option Four'
9683 * } ),
9684 * new OO.ui.MenuOptionWidget( {
9685 * data: 'Option 5',
9686 * label: 'Option Five'
9687 * } )
9690 * } );
9691 * $( 'body' ).append( comboBox.$element );
9693 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
9695 * @class
9696 * @extends OO.ui.TextInputWidget
9698 * @constructor
9699 * @param {Object} [config] Configuration options
9700 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9701 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
9702 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
9703 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
9704 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
9706 OO.ui.ComboBoxInputWidget = function OoUiComboBoxInputWidget( config ) {
9707 // Configuration initialization
9708 config = $.extend( {
9709 autocomplete: false
9710 }, config );
9712 // ComboBoxInputWidget shouldn't support multiline
9713 config.multiline = false;
9715 // Parent constructor
9716 OO.ui.ComboBoxInputWidget.parent.call( this, config );
9718 // Properties
9719 this.$overlay = config.$overlay || this.$element;
9720 this.dropdownButton = new OO.ui.ButtonWidget( {
9721 classes: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ],
9722 indicator: 'down',
9723 disabled: this.disabled
9724 } );
9725 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
9727 widget: this,
9728 input: this,
9729 $container: this.$element,
9730 disabled: this.isDisabled()
9732 config.menu
9733 ) );
9735 // Events
9736 this.connect( this, {
9737 change: 'onInputChange',
9738 enter: 'onInputEnter'
9739 } );
9740 this.dropdownButton.connect( this, {
9741 click: 'onDropdownButtonClick'
9742 } );
9743 this.menu.connect( this, {
9744 choose: 'onMenuChoose',
9745 add: 'onMenuItemsChange',
9746 remove: 'onMenuItemsChange'
9747 } );
9749 // Initialization
9750 this.$input.attr( {
9751 role: 'combobox',
9752 'aria-autocomplete': 'list'
9753 } );
9754 // Do not override options set via config.menu.items
9755 if ( config.options !== undefined ) {
9756 this.setOptions( config.options );
9758 this.$field = $( '<div>' )
9759 .addClass( 'oo-ui-comboBoxInputWidget-field' )
9760 .append( this.$input, this.dropdownButton.$element );
9761 this.$element
9762 .addClass( 'oo-ui-comboBoxInputWidget' )
9763 .append( this.$field );
9764 this.$overlay.append( this.menu.$element );
9765 this.onMenuItemsChange();
9768 /* Setup */
9770 OO.inheritClass( OO.ui.ComboBoxInputWidget, OO.ui.TextInputWidget );
9772 /* Methods */
9775 * Get the combobox's menu.
9777 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
9779 OO.ui.ComboBoxInputWidget.prototype.getMenu = function () {
9780 return this.menu;
9784 * Get the combobox's text input widget.
9786 * @return {OO.ui.TextInputWidget} Text input widget
9788 OO.ui.ComboBoxInputWidget.prototype.getInput = function () {
9789 return this;
9793 * Handle input change events.
9795 * @private
9796 * @param {string} value New value
9798 OO.ui.ComboBoxInputWidget.prototype.onInputChange = function ( value ) {
9799 var match = this.menu.getItemFromData( value );
9801 this.menu.selectItem( match );
9802 if ( this.menu.getHighlightedItem() ) {
9803 this.menu.highlightItem( match );
9806 if ( !this.isDisabled() ) {
9807 this.menu.toggle( true );
9812 * Handle input enter events.
9814 * @private
9816 OO.ui.ComboBoxInputWidget.prototype.onInputEnter = function () {
9817 if ( !this.isDisabled() ) {
9818 this.menu.toggle( false );
9823 * Handle button click events.
9825 * @private
9827 OO.ui.ComboBoxInputWidget.prototype.onDropdownButtonClick = function () {
9828 this.menu.toggle();
9829 this.$input[ 0 ].focus();
9833 * Handle menu choose events.
9835 * @private
9836 * @param {OO.ui.OptionWidget} item Chosen item
9838 OO.ui.ComboBoxInputWidget.prototype.onMenuChoose = function ( item ) {
9839 this.setValue( item.getData() );
9843 * Handle menu item change events.
9845 * @private
9847 OO.ui.ComboBoxInputWidget.prototype.onMenuItemsChange = function () {
9848 var match = this.menu.getItemFromData( this.getValue() );
9849 this.menu.selectItem( match );
9850 if ( this.menu.getHighlightedItem() ) {
9851 this.menu.highlightItem( match );
9853 this.$element.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu.isEmpty() );
9857 * @inheritdoc
9859 OO.ui.ComboBoxInputWidget.prototype.setDisabled = function ( disabled ) {
9860 // Parent method
9861 OO.ui.ComboBoxInputWidget.parent.prototype.setDisabled.call( this, disabled );
9863 if ( this.dropdownButton ) {
9864 this.dropdownButton.setDisabled( this.isDisabled() );
9866 if ( this.menu ) {
9867 this.menu.setDisabled( this.isDisabled() );
9870 return this;
9874 * Set the options available for this input.
9876 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9877 * @chainable
9879 OO.ui.ComboBoxInputWidget.prototype.setOptions = function ( options ) {
9880 this.getMenu()
9881 .clearItems()
9882 .addItems( options.map( function ( opt ) {
9883 return new OO.ui.MenuOptionWidget( {
9884 data: opt.data,
9885 label: opt.label !== undefined ? opt.label : opt.data
9886 } );
9887 } ) );
9889 return this;
9893 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
9894 * which is a widget that is specified by reference before any optional configuration settings.
9896 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
9898 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9899 * A left-alignment is used for forms with many fields.
9900 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9901 * A right-alignment is used for long but familiar forms which users tab through,
9902 * verifying the current field with a quick glance at the label.
9903 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9904 * that users fill out from top to bottom.
9905 * - **inline**: The label is placed after the field-widget and aligned to the left.
9906 * An inline-alignment is best used with checkboxes or radio buttons.
9908 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
9909 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
9911 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9913 * @class
9914 * @extends OO.ui.Layout
9915 * @mixins OO.ui.mixin.LabelElement
9916 * @mixins OO.ui.mixin.TitledElement
9918 * @constructor
9919 * @param {OO.ui.Widget} fieldWidget Field widget
9920 * @param {Object} [config] Configuration options
9921 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
9922 * @cfg {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.
9924 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
9925 * The array may contain strings or OO.ui.HtmlSnippet instances.
9926 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
9927 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
9928 * For important messages, you are advised to use `notices`, as they are always shown.
9930 * @throws {Error} An error is thrown if no widget is specified
9932 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
9933 var hasInputWidget, $div;
9935 // Allow passing positional parameters inside the config object
9936 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
9937 config = fieldWidget;
9938 fieldWidget = config.fieldWidget;
9941 // Make sure we have required constructor arguments
9942 if ( fieldWidget === undefined ) {
9943 throw new Error( 'Widget not found' );
9946 hasInputWidget = fieldWidget.constructor.static.supportsSimpleLabel;
9948 // Configuration initialization
9949 config = $.extend( { align: 'left' }, config );
9951 // Parent constructor
9952 OO.ui.FieldLayout.parent.call( this, config );
9954 // Mixin constructors
9955 OO.ui.mixin.LabelElement.call( this, config );
9956 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
9958 // Properties
9959 this.fieldWidget = fieldWidget;
9960 this.errors = [];
9961 this.notices = [];
9962 this.$field = $( '<div>' );
9963 this.$messages = $( '<ul>' );
9964 this.$header = $( '<div>' );
9965 this.$body = $( '<' + ( hasInputWidget ? 'label' : 'div' ) + '>' );
9966 this.align = null;
9967 if ( config.help ) {
9968 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
9969 classes: [ 'oo-ui-fieldLayout-help' ],
9970 framed: false,
9971 icon: 'info'
9972 } );
9974 $div = $( '<div>' );
9975 if ( config.help instanceof OO.ui.HtmlSnippet ) {
9976 $div.html( config.help.toString() );
9977 } else {
9978 $div.text( config.help );
9980 this.popupButtonWidget.getPopup().$body.append(
9981 $div.addClass( 'oo-ui-fieldLayout-help-content' )
9983 this.$help = this.popupButtonWidget.$element;
9984 } else {
9985 this.$help = $( [] );
9988 // Events
9989 if ( hasInputWidget ) {
9990 this.$label.on( 'click', this.onLabelClick.bind( this ) );
9992 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
9994 // Initialization
9995 this.$element
9996 .addClass( 'oo-ui-fieldLayout' )
9997 .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget.isDisabled() )
9998 .append( this.$body );
9999 this.$body.addClass( 'oo-ui-fieldLayout-body' );
10000 this.$header.addClass( 'oo-ui-fieldLayout-header' );
10001 this.$messages.addClass( 'oo-ui-fieldLayout-messages' );
10002 this.$field
10003 .addClass( 'oo-ui-fieldLayout-field' )
10004 .append( this.fieldWidget.$element );
10006 this.setErrors( config.errors || [] );
10007 this.setNotices( config.notices || [] );
10008 this.setAlignment( config.align );
10011 /* Setup */
10013 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
10014 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.LabelElement );
10015 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.TitledElement );
10017 /* Methods */
10020 * Handle field disable events.
10022 * @private
10023 * @param {boolean} value Field is disabled
10025 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
10026 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
10030 * Handle label mouse click events.
10032 * @private
10033 * @param {jQuery.Event} e Mouse click event
10035 OO.ui.FieldLayout.prototype.onLabelClick = function () {
10036 this.fieldWidget.simulateLabelClick();
10037 return false;
10041 * Get the widget contained by the field.
10043 * @return {OO.ui.Widget} Field widget
10045 OO.ui.FieldLayout.prototype.getField = function () {
10046 return this.fieldWidget;
10050 * @protected
10051 * @param {string} kind 'error' or 'notice'
10052 * @param {string|OO.ui.HtmlSnippet} text
10053 * @return {jQuery}
10055 OO.ui.FieldLayout.prototype.makeMessage = function ( kind, text ) {
10056 var $listItem, $icon, message;
10057 $listItem = $( '<li>' );
10058 if ( kind === 'error' ) {
10059 $icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'warning' ] } ).$element;
10060 } else if ( kind === 'notice' ) {
10061 $icon = new OO.ui.IconWidget( { icon: 'info' } ).$element;
10062 } else {
10063 $icon = '';
10065 message = new OO.ui.LabelWidget( { label: text } );
10066 $listItem
10067 .append( $icon, message.$element )
10068 .addClass( 'oo-ui-fieldLayout-messages-' + kind );
10069 return $listItem;
10073 * Set the field alignment mode.
10075 * @private
10076 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
10077 * @chainable
10079 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
10080 if ( value !== this.align ) {
10081 // Default to 'left'
10082 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
10083 value = 'left';
10085 // Reorder elements
10086 if ( value === 'top' ) {
10087 this.$header.append( this.$label, this.$help );
10088 this.$body.append( this.$header, this.$field );
10089 } else if ( value === 'inline' ) {
10090 this.$header.append( this.$label, this.$help );
10091 this.$body.append( this.$field, this.$header );
10092 } else {
10093 this.$header.append( this.$label );
10094 this.$body.append( this.$header, this.$help, this.$field );
10096 // Set classes. The following classes can be used here:
10097 // * oo-ui-fieldLayout-align-left
10098 // * oo-ui-fieldLayout-align-right
10099 // * oo-ui-fieldLayout-align-top
10100 // * oo-ui-fieldLayout-align-inline
10101 if ( this.align ) {
10102 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
10104 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
10105 this.align = value;
10108 return this;
10112 * Set the list of error messages.
10114 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
10115 * The array may contain strings or OO.ui.HtmlSnippet instances.
10116 * @chainable
10118 OO.ui.FieldLayout.prototype.setErrors = function ( errors ) {
10119 this.errors = errors.slice();
10120 this.updateMessages();
10121 return this;
10125 * Set the list of notice messages.
10127 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
10128 * The array may contain strings or OO.ui.HtmlSnippet instances.
10129 * @chainable
10131 OO.ui.FieldLayout.prototype.setNotices = function ( notices ) {
10132 this.notices = notices.slice();
10133 this.updateMessages();
10134 return this;
10138 * Update the rendering of error and notice messages.
10140 * @private
10142 OO.ui.FieldLayout.prototype.updateMessages = function () {
10143 var i;
10144 this.$messages.empty();
10146 if ( this.errors.length || this.notices.length ) {
10147 this.$body.after( this.$messages );
10148 } else {
10149 this.$messages.remove();
10150 return;
10153 for ( i = 0; i < this.notices.length; i++ ) {
10154 this.$messages.append( this.makeMessage( 'notice', this.notices[ i ] ) );
10156 for ( i = 0; i < this.errors.length; i++ ) {
10157 this.$messages.append( this.makeMessage( 'error', this.errors[ i ] ) );
10162 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
10163 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
10164 * is required and is specified before any optional configuration settings.
10166 * Labels can be aligned in one of four ways:
10168 * - **left**: The label is placed before the field-widget and aligned with the left margin.
10169 * A left-alignment is used for forms with many fields.
10170 * - **right**: The label is placed before the field-widget and aligned to the right margin.
10171 * A right-alignment is used for long but familiar forms which users tab through,
10172 * verifying the current field with a quick glance at the label.
10173 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
10174 * that users fill out from top to bottom.
10175 * - **inline**: The label is placed after the field-widget and aligned to the left.
10176 * An inline-alignment is best used with checkboxes or radio buttons.
10178 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
10179 * text is specified.
10181 * @example
10182 * // Example of an ActionFieldLayout
10183 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
10184 * new OO.ui.TextInputWidget( {
10185 * placeholder: 'Field widget'
10186 * } ),
10187 * new OO.ui.ButtonWidget( {
10188 * label: 'Button'
10189 * } ),
10191 * label: 'An ActionFieldLayout. This label is aligned top',
10192 * align: 'top',
10193 * help: 'This is help text'
10195 * );
10197 * $( 'body' ).append( actionFieldLayout.$element );
10199 * @class
10200 * @extends OO.ui.FieldLayout
10202 * @constructor
10203 * @param {OO.ui.Widget} fieldWidget Field widget
10204 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
10205 * @param {Object} config
10207 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
10208 // Allow passing positional parameters inside the config object
10209 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
10210 config = fieldWidget;
10211 fieldWidget = config.fieldWidget;
10212 buttonWidget = config.buttonWidget;
10215 // Parent constructor
10216 OO.ui.ActionFieldLayout.parent.call( this, fieldWidget, config );
10218 // Properties
10219 this.buttonWidget = buttonWidget;
10220 this.$button = $( '<div>' );
10221 this.$input = $( '<div>' );
10223 // Initialization
10224 this.$element
10225 .addClass( 'oo-ui-actionFieldLayout' );
10226 this.$button
10227 .addClass( 'oo-ui-actionFieldLayout-button' )
10228 .append( this.buttonWidget.$element );
10229 this.$input
10230 .addClass( 'oo-ui-actionFieldLayout-input' )
10231 .append( this.fieldWidget.$element );
10232 this.$field
10233 .append( this.$input, this.$button );
10236 /* Setup */
10238 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
10241 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
10242 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
10243 * configured with a label as well. For more information and examples,
10244 * please see the [OOjs UI documentation on MediaWiki][1].
10246 * @example
10247 * // Example of a fieldset layout
10248 * var input1 = new OO.ui.TextInputWidget( {
10249 * placeholder: 'A text input field'
10250 * } );
10252 * var input2 = new OO.ui.TextInputWidget( {
10253 * placeholder: 'A text input field'
10254 * } );
10256 * var fieldset = new OO.ui.FieldsetLayout( {
10257 * label: 'Example of a fieldset layout'
10258 * } );
10260 * fieldset.addItems( [
10261 * new OO.ui.FieldLayout( input1, {
10262 * label: 'Field One'
10263 * } ),
10264 * new OO.ui.FieldLayout( input2, {
10265 * label: 'Field Two'
10266 * } )
10267 * ] );
10268 * $( 'body' ).append( fieldset.$element );
10270 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
10272 * @class
10273 * @extends OO.ui.Layout
10274 * @mixins OO.ui.mixin.IconElement
10275 * @mixins OO.ui.mixin.LabelElement
10276 * @mixins OO.ui.mixin.GroupElement
10278 * @constructor
10279 * @param {Object} [config] Configuration options
10280 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
10281 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
10282 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
10283 * For important messages, you are advised to use `notices`, as they are always shown.
10285 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
10286 var $div;
10288 // Configuration initialization
10289 config = config || {};
10291 // Parent constructor
10292 OO.ui.FieldsetLayout.parent.call( this, config );
10294 // Mixin constructors
10295 OO.ui.mixin.IconElement.call( this, config );
10296 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: $( '<div>' ) } ) );
10297 OO.ui.mixin.GroupElement.call( this, config );
10299 // Properties
10300 this.$header = $( '<div>' );
10301 if ( config.help ) {
10302 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
10303 classes: [ 'oo-ui-fieldsetLayout-help' ],
10304 framed: false,
10305 icon: 'info'
10306 } );
10308 $div = $( '<div>' );
10309 if ( config.help instanceof OO.ui.HtmlSnippet ) {
10310 $div.html( config.help.toString() );
10311 } else {
10312 $div.text( config.help );
10314 this.popupButtonWidget.getPopup().$body.append(
10315 $div.addClass( 'oo-ui-fieldsetLayout-help-content' )
10317 this.$help = this.popupButtonWidget.$element;
10318 } else {
10319 this.$help = $( [] );
10322 // Initialization
10323 this.$header
10324 .addClass( 'oo-ui-fieldsetLayout-header' )
10325 .append( this.$icon, this.$label, this.$help );
10326 this.$group.addClass( 'oo-ui-fieldsetLayout-group' );
10327 this.$element
10328 .addClass( 'oo-ui-fieldsetLayout' )
10329 .prepend( this.$header, this.$group );
10330 if ( Array.isArray( config.items ) ) {
10331 this.addItems( config.items );
10335 /* Setup */
10337 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
10338 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.IconElement );
10339 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.LabelElement );
10340 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.GroupElement );
10342 /* Static Properties */
10344 OO.ui.FieldsetLayout.static.tagName = 'fieldset';
10347 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
10348 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
10349 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
10350 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
10352 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
10353 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
10354 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
10355 * some fancier controls. Some controls have both regular and InputWidget variants, for example
10356 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
10357 * often have simplified APIs to match the capabilities of HTML forms.
10358 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
10360 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
10361 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
10363 * @example
10364 * // Example of a form layout that wraps a fieldset layout
10365 * var input1 = new OO.ui.TextInputWidget( {
10366 * placeholder: 'Username'
10367 * } );
10368 * var input2 = new OO.ui.TextInputWidget( {
10369 * placeholder: 'Password',
10370 * type: 'password'
10371 * } );
10372 * var submit = new OO.ui.ButtonInputWidget( {
10373 * label: 'Submit'
10374 * } );
10376 * var fieldset = new OO.ui.FieldsetLayout( {
10377 * label: 'A form layout'
10378 * } );
10379 * fieldset.addItems( [
10380 * new OO.ui.FieldLayout( input1, {
10381 * label: 'Username',
10382 * align: 'top'
10383 * } ),
10384 * new OO.ui.FieldLayout( input2, {
10385 * label: 'Password',
10386 * align: 'top'
10387 * } ),
10388 * new OO.ui.FieldLayout( submit )
10389 * ] );
10390 * var form = new OO.ui.FormLayout( {
10391 * items: [ fieldset ],
10392 * action: '/api/formhandler',
10393 * method: 'get'
10394 * } )
10395 * $( 'body' ).append( form.$element );
10397 * @class
10398 * @extends OO.ui.Layout
10399 * @mixins OO.ui.mixin.GroupElement
10401 * @constructor
10402 * @param {Object} [config] Configuration options
10403 * @cfg {string} [method] HTML form `method` attribute
10404 * @cfg {string} [action] HTML form `action` attribute
10405 * @cfg {string} [enctype] HTML form `enctype` attribute
10406 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
10408 OO.ui.FormLayout = function OoUiFormLayout( config ) {
10409 var action;
10411 // Configuration initialization
10412 config = config || {};
10414 // Parent constructor
10415 OO.ui.FormLayout.parent.call( this, config );
10417 // Mixin constructors
10418 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
10420 // Events
10421 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
10423 // Make sure the action is safe
10424 action = config.action;
10425 if ( action !== undefined && !OO.ui.isSafeUrl( action ) ) {
10426 action = './' + action;
10429 // Initialization
10430 this.$element
10431 .addClass( 'oo-ui-formLayout' )
10432 .attr( {
10433 method: config.method,
10434 action: action,
10435 enctype: config.enctype
10436 } );
10437 if ( Array.isArray( config.items ) ) {
10438 this.addItems( config.items );
10442 /* Setup */
10444 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
10445 OO.mixinClass( OO.ui.FormLayout, OO.ui.mixin.GroupElement );
10447 /* Events */
10450 * A 'submit' event is emitted when the form is submitted.
10452 * @event submit
10455 /* Static Properties */
10457 OO.ui.FormLayout.static.tagName = 'form';
10459 /* Methods */
10462 * Handle form submit events.
10464 * @private
10465 * @param {jQuery.Event} e Submit event
10466 * @fires submit
10468 OO.ui.FormLayout.prototype.onFormSubmit = function () {
10469 if ( this.emit( 'submit' ) ) {
10470 return false;
10475 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
10476 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
10478 * @example
10479 * // Example of a panel layout
10480 * var panel = new OO.ui.PanelLayout( {
10481 * expanded: false,
10482 * framed: true,
10483 * padded: true,
10484 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
10485 * } );
10486 * $( 'body' ).append( panel.$element );
10488 * @class
10489 * @extends OO.ui.Layout
10491 * @constructor
10492 * @param {Object} [config] Configuration options
10493 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
10494 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10495 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10496 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10498 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
10499 // Configuration initialization
10500 config = $.extend( {
10501 scrollable: false,
10502 padded: false,
10503 expanded: true,
10504 framed: false
10505 }, config );
10507 // Parent constructor
10508 OO.ui.PanelLayout.parent.call( this, config );
10510 // Initialization
10511 this.$element.addClass( 'oo-ui-panelLayout' );
10512 if ( config.scrollable ) {
10513 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
10515 if ( config.padded ) {
10516 this.$element.addClass( 'oo-ui-panelLayout-padded' );
10518 if ( config.expanded ) {
10519 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
10521 if ( config.framed ) {
10522 this.$element.addClass( 'oo-ui-panelLayout-framed' );
10526 /* Setup */
10528 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
10530 /* Methods */
10533 * Focus the panel layout
10535 * The default implementation just focuses the first focusable element in the panel
10537 OO.ui.PanelLayout.prototype.focus = function () {
10538 OO.ui.findFocusable( this.$element ).focus();
10542 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
10543 * items), with small margins between them. Convenient when you need to put a number of block-level
10544 * widgets on a single line next to each other.
10546 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
10548 * @example
10549 * // HorizontalLayout with a text input and a label
10550 * var layout = new OO.ui.HorizontalLayout( {
10551 * items: [
10552 * new OO.ui.LabelWidget( { label: 'Label' } ),
10553 * new OO.ui.TextInputWidget( { value: 'Text' } )
10555 * } );
10556 * $( 'body' ).append( layout.$element );
10558 * @class
10559 * @extends OO.ui.Layout
10560 * @mixins OO.ui.mixin.GroupElement
10562 * @constructor
10563 * @param {Object} [config] Configuration options
10564 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
10566 OO.ui.HorizontalLayout = function OoUiHorizontalLayout( config ) {
10567 // Configuration initialization
10568 config = config || {};
10570 // Parent constructor
10571 OO.ui.HorizontalLayout.parent.call( this, config );
10573 // Mixin constructors
10574 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
10576 // Initialization
10577 this.$element.addClass( 'oo-ui-horizontalLayout' );
10578 if ( Array.isArray( config.items ) ) {
10579 this.addItems( config.items );
10583 /* Setup */
10585 OO.inheritClass( OO.ui.HorizontalLayout, OO.ui.Layout );
10586 OO.mixinClass( OO.ui.HorizontalLayout, OO.ui.mixin.GroupElement );
10588 }( OO ) );
10590 //# sourceMappingURL=oojs-ui-core.js.map