Merge "mediawiki.js: Fix eslint valid-jsdoc"
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui-core.js
1 /*!
2 * OOUI v0.27.2
3 * https://www.mediawiki.org/wiki/OOUI
4 *
5 * Copyright 2011–2018 OOUI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
8 *
9 * Date: 2018-06-06T16:16:10Z
10 */
11 ( function ( OO ) {
12
13 'use strict';
14
15 /**
16 * Namespace for all classes, static methods and static properties.
17 *
18 * @class
19 * @singleton
20 */
21 OO.ui = {};
22
23 OO.ui.bind = $.proxy;
24
25 /**
26 * @property {Object}
27 */
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
45 };
46
47 /**
48 * Constants for MouseEvent.which
49 *
50 * @property {Object}
51 */
52 OO.ui.MouseButtons = {
53 LEFT: 1,
54 MIDDLE: 2,
55 RIGHT: 3
56 };
57
58 /**
59 * @property {number}
60 * @private
61 */
62 OO.ui.elementId = 0;
63
64 /**
65 * Generate a unique ID for element
66 *
67 * @return {string} ID
68 */
69 OO.ui.generateElementId = function () {
70 OO.ui.elementId++;
71 return 'ooui-' + OO.ui.elementId;
72 };
73
74 /**
75 * Check if an element is focusable.
76 * Inspired by :focusable in jQueryUI v1.11.4 - 2015-04-14
77 *
78 * @param {jQuery} $element Element to test
79 * @return {boolean} Element is focusable
80 */
81 OO.ui.isFocusableElement = function ( $element ) {
82 var nodeName,
83 element = $element[ 0 ];
84
85 // Anything disabled is not focusable
86 if ( element.disabled ) {
87 return false;
88 }
89
90 // Check if the element is visible
91 if ( !(
92 // This is quicker than calling $element.is( ':visible' )
93 $.expr.pseudos.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;
100 }
101
102 // Check if the element is ContentEditable, which is the string 'true'
103 if ( element.contentEditable === 'true' ) {
104 return true;
105 }
106
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;
111 }
112
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;
119 }
120
121 // Links and areas are focusable if they have an href
122 if ( ( nodeName === 'a' || nodeName === 'area' ) && $element.attr( 'href' ) !== undefined ) {
123 return true;
124 }
125
126 return false;
127 };
128
129 /**
130 * Find a focusable child
131 *
132 * @param {jQuery} $container Container to search in
133 * @param {boolean} [backwards] Search backwards
134 * @return {jQuery} Focusable child, or an empty jQuery object if none found
135 */
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]' );
142
143 if ( backwards ) {
144 $focusableCandidates = Array.prototype.reverse.call( $focusableCandidates );
145 }
146
147 $focusableCandidates.each( function () {
148 var $this = $( this );
149 if ( OO.ui.isFocusableElement( $this ) ) {
150 $focusable = $this;
151 return false;
152 }
153 } );
154 return $focusable;
155 };
156
157 /**
158 * Get the user's language and any fallback languages.
159 *
160 * These language codes are used to localize user interface elements in the user's language.
161 *
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.
164 *
165 * @return {string[]} Language codes, in descending order of priority
166 */
167 OO.ui.getUserLanguages = function () {
168 return [ 'en' ];
169 };
170
171 /**
172 * Get a value in an object keyed by language code.
173 *
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
178 */
179 OO.ui.getLocalValue = function ( obj, lang, fallback ) {
180 var i, len, langs;
181
182 // Requested language
183 if ( obj[ lang ] ) {
184 return obj[ lang ];
185 }
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 ];
192 }
193 }
194 // Fallback language
195 if ( obj[ fallback ] ) {
196 return obj[ fallback ];
197 }
198 // First existing language
199 for ( lang in obj ) {
200 return obj[ lang ];
201 }
202
203 return undefined;
204 };
205
206 /**
207 * Check if a node is contained within another node
208 *
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
211 *
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
216 */
217 OO.ui.contains = function ( containers, contained, matchContainers ) {
218 var i;
219 if ( !Array.isArray( containers ) ) {
220 containers = [ containers ];
221 }
222 for ( i = containers.length - 1; i >= 0; i-- ) {
223 if ( ( matchContainers && contained === containers[ i ] ) || $.contains( containers[ i ], contained ) ) {
224 return true;
225 }
226 }
227 return false;
228 };
229
230 /**
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.
235 *
236 * Ported from: http://underscorejs.org/underscore.js
237 *
238 * @param {Function} func Function to debounce
239 * @param {number} [wait=0] Wait period in milliseconds
240 * @param {boolean} [immediate] Trigger on leading edge
241 * @return {Function} Debounced function
242 */
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 );
252 }
253 };
254 if ( immediate && !timeout ) {
255 func.apply( context, args );
256 }
257 if ( !timeout || wait ) {
258 clearTimeout( timeout );
259 timeout = setTimeout( later, wait );
260 }
261 };
262 };
263
264 /**
265 * Puts a console warning with provided message.
266 *
267 * @param {string} message Message
268 */
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 );
273 }
274 };
275
276 /**
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.
280 *
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.
284 *
285 * @param {Function} func Function to throttle
286 * @param {number} wait Throttle window length, in milliseconds
287 * @return {Function} Throttled function
288 */
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 );
296 };
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 );
315 }
316 };
317 };
318
319 /**
320 * A (possibly faster) way to get the current timestamp as an integer
321 *
322 * @return {number} Current timestamp, in milliseconds since the Unix epoch
323 */
324 OO.ui.now = Date.now || function () {
325 return new Date().getTime();
326 };
327
328 /**
329 * Reconstitute a JavaScript object corresponding to a widget created by
330 * the PHP implementation.
331 *
332 * This is an alias for `OO.ui.Element.static.infuse()`.
333 *
334 * @param {string|HTMLElement|jQuery} idOrNode
335 * A DOM id (if a string) or node for the widget to infuse.
336 * @param {Object} [config] Configuration options
337 * @return {OO.ui.Element}
338 * The `OO.ui.Element` corresponding to this (infusable) document node.
339 */
340 OO.ui.infuse = function ( idOrNode, config ) {
341 return OO.ui.Element.static.infuse( idOrNode, config );
342 };
343
344 ( function () {
345 /**
346 * Message store for the default implementation of OO.ui.msg
347 *
348 * Environments that provide a localization system should not use this, but should override
349 * OO.ui.msg altogether.
350 *
351 * @private
352 */
353 var messages = {
354 // Tool tip for a button that moves items in a list down one place
355 'ooui-outline-control-move-down': 'Move item down',
356 // Tool tip for a button that moves items in a list up one place
357 'ooui-outline-control-move-up': 'Move item up',
358 // Tool tip for a button that removes items from a list
359 'ooui-outline-control-remove': 'Remove item',
360 // Label for the toolbar group that contains a list of all other available tools
361 'ooui-toolbar-more': 'More',
362 // Label for the fake tool that expands the full list of tools in a toolbar group
363 'ooui-toolgroup-expand': 'More',
364 // Label for the fake tool that collapses the full list of tools in a toolbar group
365 'ooui-toolgroup-collapse': 'Fewer',
366 // Default label for the tooltip for the button that removes a tag item
367 'ooui-item-remove': 'Remove',
368 // Default label for the accept button of a confirmation dialog
369 'ooui-dialog-message-accept': 'OK',
370 // Default label for the reject button of a confirmation dialog
371 'ooui-dialog-message-reject': 'Cancel',
372 // Title for process dialog error description
373 'ooui-dialog-process-error': 'Something went wrong',
374 // Label for process dialog dismiss error button, visible when describing errors
375 'ooui-dialog-process-dismiss': 'Dismiss',
376 // Label for process dialog retry action button, visible when describing only recoverable errors
377 'ooui-dialog-process-retry': 'Try again',
378 // Label for process dialog retry action button, visible when describing only warnings
379 'ooui-dialog-process-continue': 'Continue',
380 // Label for the file selection widget's select file button
381 'ooui-selectfile-button-select': 'Select a file',
382 // Label for the file selection widget if file selection is not supported
383 'ooui-selectfile-not-supported': 'File selection is not supported',
384 // Label for the file selection widget when no file is currently selected
385 'ooui-selectfile-placeholder': 'No file is selected',
386 // Label for the file selection widget's drop target
387 'ooui-selectfile-dragdrop-placeholder': 'Drop file here'
388 };
389
390 /**
391 * Get a localized message.
392 *
393 * After the message key, message parameters may optionally be passed. In the default implementation,
394 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
395 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
396 * they support unnamed, ordered message parameters.
397 *
398 * In environments that provide a localization system, this function should be overridden to
399 * return the message translated in the user's language. The default implementation always returns
400 * English messages. An example of doing this with [jQuery.i18n](https://github.com/wikimedia/jquery.i18n)
401 * follows.
402 *
403 * @example
404 * var i, iLen, button,
405 * messagePath = 'oojs-ui/dist/i18n/',
406 * languages = [ $.i18n().locale, 'ur', 'en' ],
407 * languageMap = {};
408 *
409 * for ( i = 0, iLen = languages.length; i < iLen; i++ ) {
410 * languageMap[ languages[ i ] ] = messagePath + languages[ i ].toLowerCase() + '.json';
411 * }
412 *
413 * $.i18n().load( languageMap ).done( function() {
414 * // Replace the built-in `msg` only once we've loaded the internationalization.
415 * // OOUI uses `OO.ui.deferMsg` for all initially-loaded messages. So long as
416 * // you put off creating any widgets until this promise is complete, no English
417 * // will be displayed.
418 * OO.ui.msg = $.i18n;
419 *
420 * // A button displaying "OK" in the default locale
421 * button = new OO.ui.ButtonWidget( {
422 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
423 * icon: 'check'
424 * } );
425 * $( 'body' ).append( button.$element );
426 *
427 * // A button displaying "OK" in Urdu
428 * $.i18n().locale = 'ur';
429 * button = new OO.ui.ButtonWidget( {
430 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
431 * icon: 'check'
432 * } );
433 * $( 'body' ).append( button.$element );
434 * } );
435 *
436 * @param {string} key Message key
437 * @param {...Mixed} [params] Message parameters
438 * @return {string} Translated message with parameters substituted
439 */
440 OO.ui.msg = function ( key ) {
441 var message = messages[ key ],
442 params = Array.prototype.slice.call( arguments, 1 );
443 if ( typeof message === 'string' ) {
444 // Perform $1 substitution
445 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
446 var i = parseInt( n, 10 );
447 return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n;
448 } );
449 } else {
450 // Return placeholder if message not found
451 message = '[' + key + ']';
452 }
453 return message;
454 };
455 }() );
456
457 /**
458 * Package a message and arguments for deferred resolution.
459 *
460 * Use this when you are statically specifying a message and the message may not yet be present.
461 *
462 * @param {string} key Message key
463 * @param {...Mixed} [params] Message parameters
464 * @return {Function} Function that returns the resolved message when executed
465 */
466 OO.ui.deferMsg = function () {
467 var args = arguments;
468 return function () {
469 return OO.ui.msg.apply( OO.ui, args );
470 };
471 };
472
473 /**
474 * Resolve a message.
475 *
476 * If the message is a function it will be executed, otherwise it will pass through directly.
477 *
478 * @param {Function|string} msg Deferred message, or message text
479 * @return {string} Resolved message
480 */
481 OO.ui.resolveMsg = function ( msg ) {
482 if ( $.isFunction( msg ) ) {
483 return msg();
484 }
485 return msg;
486 };
487
488 /**
489 * @param {string} url
490 * @return {boolean}
491 */
492 OO.ui.isSafeUrl = function ( url ) {
493 // Keep this function in sync with php/Tag.php
494 var i, protocolWhitelist;
495
496 function stringStartsWith( haystack, needle ) {
497 return haystack.substr( 0, needle.length ) === needle;
498 }
499
500 protocolWhitelist = [
501 'bitcoin', 'ftp', 'ftps', 'geo', 'git', 'gopher', 'http', 'https', 'irc', 'ircs',
502 'magnet', 'mailto', 'mms', 'news', 'nntp', 'redis', 'sftp', 'sip', 'sips', 'sms', 'ssh',
503 'svn', 'tel', 'telnet', 'urn', 'worldwind', 'xmpp'
504 ];
505
506 if ( url === '' ) {
507 return true;
508 }
509
510 for ( i = 0; i < protocolWhitelist.length; i++ ) {
511 if ( stringStartsWith( url, protocolWhitelist[ i ] + ':' ) ) {
512 return true;
513 }
514 }
515
516 // This matches '//' too
517 if ( stringStartsWith( url, '/' ) || stringStartsWith( url, './' ) ) {
518 return true;
519 }
520 if ( stringStartsWith( url, '?' ) || stringStartsWith( url, '#' ) ) {
521 return true;
522 }
523
524 return false;
525 };
526
527 /**
528 * Check if the user has a 'mobile' device.
529 *
530 * For our purposes this means the user is primarily using an
531 * on-screen keyboard, touch input instead of a mouse and may
532 * have a physically small display.
533 *
534 * It is left up to implementors to decide how to compute this
535 * so the default implementation always returns false.
536 *
537 * @return {boolean} User is on a mobile device
538 */
539 OO.ui.isMobile = function () {
540 return false;
541 };
542
543 /**
544 * Get the additional spacing that should be taken into account when displaying elements that are
545 * clipped to the viewport, e.g. dropdown menus and popups. This is meant to be overridden to avoid
546 * such menus overlapping any fixed headers/toolbars/navigation used by the site.
547 *
548 * @return {Object} Object with the properties 'top', 'right', 'bottom', 'left', each representing
549 * the extra spacing from that edge of viewport (in pixels)
550 */
551 OO.ui.getViewportSpacing = function () {
552 return {
553 top: 0,
554 right: 0,
555 bottom: 0,
556 left: 0
557 };
558 };
559
560 /**
561 * Get the default overlay, which is used by various widgets when they are passed `$overlay: true`.
562 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
563 *
564 * @return {jQuery} Default overlay node
565 */
566 OO.ui.getDefaultOverlay = function () {
567 if ( !OO.ui.$defaultOverlay ) {
568 OO.ui.$defaultOverlay = $( '<div>' ).addClass( 'oo-ui-defaultOverlay' );
569 $( 'body' ).append( OO.ui.$defaultOverlay );
570 }
571 return OO.ui.$defaultOverlay;
572 };
573
574 /*!
575 * Mixin namespace.
576 */
577
578 /**
579 * Namespace for OOUI mixins.
580 *
581 * Mixins are named according to the type of object they are intended to
582 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
583 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
584 * is intended to be mixed in to an instance of OO.ui.Widget.
585 *
586 * @class
587 * @singleton
588 */
589 OO.ui.mixin = {};
590
591 /**
592 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
593 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
594 * connected to them and can't be interacted with.
595 *
596 * @abstract
597 * @class
598 *
599 * @constructor
600 * @param {Object} [config] Configuration options
601 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
602 * to the top level (e.g., the outermost div) of the element. See the [OOUI documentation on MediaWiki][2]
603 * for an example.
604 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches#cssExample
605 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
606 * @cfg {string} [text] Text to insert
607 * @cfg {Array} [content] An array of content elements to append (after #text).
608 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
609 * Instances of OO.ui.Element will have their $element appended.
610 * @cfg {jQuery} [$content] Content elements to append (after #text).
611 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
612 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
613 * Data can also be specified with the #setData method.
614 */
615 OO.ui.Element = function OoUiElement( config ) {
616 if ( OO.ui.isDemo ) {
617 this.initialConfig = config;
618 }
619 // Configuration initialization
620 config = config || {};
621
622 // Properties
623 this.$ = $;
624 this.elementId = null;
625 this.visible = true;
626 this.data = config.data;
627 this.$element = config.$element ||
628 $( document.createElement( this.getTagName() ) );
629 this.elementGroup = null;
630
631 // Initialization
632 if ( Array.isArray( config.classes ) ) {
633 this.$element.addClass( config.classes.join( ' ' ) );
634 }
635 if ( config.id ) {
636 this.setElementId( config.id );
637 }
638 if ( config.text ) {
639 this.$element.text( config.text );
640 }
641 if ( config.content ) {
642 // The `content` property treats plain strings as text; use an
643 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
644 // appropriate $element appended.
645 this.$element.append( config.content.map( function ( v ) {
646 if ( typeof v === 'string' ) {
647 // Escape string so it is properly represented in HTML.
648 return document.createTextNode( v );
649 } else if ( v instanceof OO.ui.HtmlSnippet ) {
650 // Bypass escaping.
651 return v.toString();
652 } else if ( v instanceof OO.ui.Element ) {
653 return v.$element;
654 }
655 return v;
656 } ) );
657 }
658 if ( config.$content ) {
659 // The `$content` property treats plain strings as HTML.
660 this.$element.append( config.$content );
661 }
662 };
663
664 /* Setup */
665
666 OO.initClass( OO.ui.Element );
667
668 /* Static Properties */
669
670 /**
671 * The name of the HTML tag used by the element.
672 *
673 * The static value may be ignored if the #getTagName method is overridden.
674 *
675 * @static
676 * @inheritable
677 * @property {string}
678 */
679 OO.ui.Element.static.tagName = 'div';
680
681 /* Static Methods */
682
683 /**
684 * Reconstitute a JavaScript object corresponding to a widget created
685 * by the PHP implementation.
686 *
687 * @param {string|HTMLElement|jQuery} idOrNode
688 * A DOM id (if a string) or node for the widget to infuse.
689 * @param {Object} [config] Configuration options
690 * @return {OO.ui.Element}
691 * The `OO.ui.Element` corresponding to this (infusable) document node.
692 * For `Tag` objects emitted on the HTML side (used occasionally for content)
693 * the value returned is a newly-created Element wrapping around the existing
694 * DOM node.
695 */
696 OO.ui.Element.static.infuse = function ( idOrNode, config ) {
697 var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, config, false );
698 // Verify that the type matches up.
699 // FIXME: uncomment after T89721 is fixed, see T90929.
700 /*
701 if ( !( obj instanceof this['class'] ) ) {
702 throw new Error( 'Infusion type mismatch!' );
703 }
704 */
705 return obj;
706 };
707
708 /**
709 * Implementation helper for `infuse`; skips the type check and has an
710 * extra property so that only the top-level invocation touches the DOM.
711 *
712 * @private
713 * @param {string|HTMLElement|jQuery} idOrNode
714 * @param {Object} [config] Configuration options
715 * @param {jQuery.Promise} [domPromise] A promise that will be resolved
716 * when the top-level widget of this infusion is inserted into DOM,
717 * replacing the original node; only used internally.
718 * @return {OO.ui.Element}
719 */
720 OO.ui.Element.static.unsafeInfuse = function ( idOrNode, config, domPromise ) {
721 // look for a cached result of a previous infusion.
722 var id, $elem, error, data, cls, parts, parent, obj, top, state, infusedChildren;
723 if ( typeof idOrNode === 'string' ) {
724 id = idOrNode;
725 $elem = $( document.getElementById( id ) );
726 } else {
727 $elem = $( idOrNode );
728 id = $elem.attr( 'id' );
729 }
730 if ( !$elem.length ) {
731 if ( typeof idOrNode === 'string' ) {
732 error = 'Widget not found: ' + idOrNode;
733 } else if ( idOrNode && idOrNode.selector ) {
734 error = 'Widget not found: ' + idOrNode.selector;
735 } else {
736 error = 'Widget not found';
737 }
738 throw new Error( error );
739 }
740 if ( $elem[ 0 ].oouiInfused ) {
741 $elem = $elem[ 0 ].oouiInfused;
742 }
743 data = $elem.data( 'ooui-infused' );
744 if ( data ) {
745 // cached!
746 if ( data === true ) {
747 throw new Error( 'Circular dependency! ' + id );
748 }
749 if ( domPromise ) {
750 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
751 state = data.constructor.static.gatherPreInfuseState( $elem, data );
752 // restore dynamic state after the new element is re-inserted into DOM under infused parent
753 domPromise.done( data.restorePreInfuseState.bind( data, state ) );
754 infusedChildren = $elem.data( 'ooui-infused-children' );
755 if ( infusedChildren && infusedChildren.length ) {
756 infusedChildren.forEach( function ( data ) {
757 var state = data.constructor.static.gatherPreInfuseState( $elem, data );
758 domPromise.done( data.restorePreInfuseState.bind( data, state ) );
759 } );
760 }
761 }
762 return data;
763 }
764 data = $elem.attr( 'data-ooui' );
765 if ( !data ) {
766 throw new Error( 'No infusion data found: ' + id );
767 }
768 try {
769 data = JSON.parse( data );
770 } catch ( _ ) {
771 data = null;
772 }
773 if ( !( data && data._ ) ) {
774 throw new Error( 'No valid infusion data found: ' + id );
775 }
776 if ( data._ === 'Tag' ) {
777 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
778 return new OO.ui.Element( $.extend( {}, config, { $element: $elem } ) );
779 }
780 parts = data._.split( '.' );
781 cls = OO.getProp.apply( OO, [ window ].concat( parts ) );
782 if ( cls === undefined ) {
783 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
784 }
785
786 // Verify that we're creating an OO.ui.Element instance
787 parent = cls.parent;
788
789 while ( parent !== undefined ) {
790 if ( parent === OO.ui.Element ) {
791 // Safe
792 break;
793 }
794
795 parent = parent.parent;
796 }
797
798 if ( parent !== OO.ui.Element ) {
799 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
800 }
801
802 if ( !domPromise ) {
803 top = $.Deferred();
804 domPromise = top.promise();
805 }
806 $elem.data( 'ooui-infused', true ); // prevent loops
807 data.id = id; // implicit
808 infusedChildren = [];
809 data = OO.copy( data, null, function deserialize( value ) {
810 var infused;
811 if ( OO.isPlainObject( value ) ) {
812 if ( value.tag ) {
813 infused = OO.ui.Element.static.unsafeInfuse( value.tag, config, domPromise );
814 infusedChildren.push( infused );
815 // Flatten the structure
816 infusedChildren.push.apply( infusedChildren, infused.$element.data( 'ooui-infused-children' ) || [] );
817 infused.$element.removeData( 'ooui-infused-children' );
818 return infused;
819 }
820 if ( value.html !== undefined ) {
821 return new OO.ui.HtmlSnippet( value.html );
822 }
823 }
824 } );
825 // allow widgets to reuse parts of the DOM
826 data = cls.static.reusePreInfuseDOM( $elem[ 0 ], data );
827 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
828 state = cls.static.gatherPreInfuseState( $elem[ 0 ], data );
829 // rebuild widget
830 // eslint-disable-next-line new-cap
831 obj = new cls( $.extend( {}, config, data ) );
832 // If anyone is holding a reference to the old DOM element,
833 // let's allow them to OO.ui.infuse() it and do what they expect, see T105828.
834 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
835 $elem[ 0 ].oouiInfused = obj.$element;
836 // now replace old DOM with this new DOM.
837 if ( top ) {
838 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
839 // so only mutate the DOM if we need to.
840 if ( $elem[ 0 ] !== obj.$element[ 0 ] ) {
841 $elem.replaceWith( obj.$element );
842 }
843 top.resolve();
844 }
845 obj.$element.data( 'ooui-infused', obj );
846 obj.$element.data( 'ooui-infused-children', infusedChildren );
847 // set the 'data-ooui' attribute so we can identify infused widgets
848 obj.$element.attr( 'data-ooui', '' );
849 // restore dynamic state after the new element is inserted into DOM
850 domPromise.done( obj.restorePreInfuseState.bind( obj, state ) );
851 return obj;
852 };
853
854 /**
855 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
856 *
857 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
858 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
859 * constructor, which will be given the enhanced config.
860 *
861 * @protected
862 * @param {HTMLElement} node
863 * @param {Object} config
864 * @return {Object}
865 */
866 OO.ui.Element.static.reusePreInfuseDOM = function ( node, config ) {
867 return config;
868 };
869
870 /**
871 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of an HTML DOM node
872 * (and its children) that represent an Element of the same class and the given configuration,
873 * generated by the PHP implementation.
874 *
875 * This method is called just before `node` is detached from the DOM. The return value of this
876 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
877 * is inserted into DOM to replace `node`.
878 *
879 * @protected
880 * @param {HTMLElement} node
881 * @param {Object} config
882 * @return {Object}
883 */
884 OO.ui.Element.static.gatherPreInfuseState = function () {
885 return {};
886 };
887
888 /**
889 * Get a jQuery function within a specific document.
890 *
891 * @static
892 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
893 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
894 * not in an iframe
895 * @return {Function} Bound jQuery function
896 */
897 OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
898 function wrapper( selector ) {
899 return $( selector, wrapper.context );
900 }
901
902 wrapper.context = this.getDocument( context );
903
904 if ( $iframe ) {
905 wrapper.$iframe = $iframe;
906 }
907
908 return wrapper;
909 };
910
911 /**
912 * Get the document of an element.
913 *
914 * @static
915 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
916 * @return {HTMLDocument|null} Document object
917 */
918 OO.ui.Element.static.getDocument = function ( obj ) {
919 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
920 return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
921 // Empty jQuery selections might have a context
922 obj.context ||
923 // HTMLElement
924 obj.ownerDocument ||
925 // Window
926 obj.document ||
927 // HTMLDocument
928 ( obj.nodeType === Node.DOCUMENT_NODE && obj ) ||
929 null;
930 };
931
932 /**
933 * Get the window of an element or document.
934 *
935 * @static
936 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
937 * @return {Window} Window object
938 */
939 OO.ui.Element.static.getWindow = function ( obj ) {
940 var doc = this.getDocument( obj );
941 return doc.defaultView;
942 };
943
944 /**
945 * Get the direction of an element or document.
946 *
947 * @static
948 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
949 * @return {string} Text direction, either 'ltr' or 'rtl'
950 */
951 OO.ui.Element.static.getDir = function ( obj ) {
952 var isDoc, isWin;
953
954 if ( obj instanceof jQuery ) {
955 obj = obj[ 0 ];
956 }
957 isDoc = obj.nodeType === Node.DOCUMENT_NODE;
958 isWin = obj.document !== undefined;
959 if ( isDoc || isWin ) {
960 if ( isWin ) {
961 obj = obj.document;
962 }
963 obj = obj.body;
964 }
965 return $( obj ).css( 'direction' );
966 };
967
968 /**
969 * Get the offset between two frames.
970 *
971 * TODO: Make this function not use recursion.
972 *
973 * @static
974 * @param {Window} from Window of the child frame
975 * @param {Window} [to=window] Window of the parent frame
976 * @param {Object} [offset] Offset to start with, used internally
977 * @return {Object} Offset object, containing left and top properties
978 */
979 OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
980 var i, len, frames, frame, rect;
981
982 if ( !to ) {
983 to = window;
984 }
985 if ( !offset ) {
986 offset = { top: 0, left: 0 };
987 }
988 if ( from.parent === from ) {
989 return offset;
990 }
991
992 // Get iframe element
993 frames = from.parent.document.getElementsByTagName( 'iframe' );
994 for ( i = 0, len = frames.length; i < len; i++ ) {
995 if ( frames[ i ].contentWindow === from ) {
996 frame = frames[ i ];
997 break;
998 }
999 }
1000
1001 // Recursively accumulate offset values
1002 if ( frame ) {
1003 rect = frame.getBoundingClientRect();
1004 offset.left += rect.left;
1005 offset.top += rect.top;
1006 if ( from !== to ) {
1007 this.getFrameOffset( from.parent, offset );
1008 }
1009 }
1010 return offset;
1011 };
1012
1013 /**
1014 * Get the offset between two elements.
1015 *
1016 * The two elements may be in a different frame, but in that case the frame $element is in must
1017 * be contained in the frame $anchor is in.
1018 *
1019 * @static
1020 * @param {jQuery} $element Element whose position to get
1021 * @param {jQuery} $anchor Element to get $element's position relative to
1022 * @return {Object} Translated position coordinates, containing top and left properties
1023 */
1024 OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
1025 var iframe, iframePos,
1026 pos = $element.offset(),
1027 anchorPos = $anchor.offset(),
1028 elementDocument = this.getDocument( $element ),
1029 anchorDocument = this.getDocument( $anchor );
1030
1031 // If $element isn't in the same document as $anchor, traverse up
1032 while ( elementDocument !== anchorDocument ) {
1033 iframe = elementDocument.defaultView.frameElement;
1034 if ( !iframe ) {
1035 throw new Error( '$element frame is not contained in $anchor frame' );
1036 }
1037 iframePos = $( iframe ).offset();
1038 pos.left += iframePos.left;
1039 pos.top += iframePos.top;
1040 elementDocument = iframe.ownerDocument;
1041 }
1042 pos.left -= anchorPos.left;
1043 pos.top -= anchorPos.top;
1044 return pos;
1045 };
1046
1047 /**
1048 * Get element border sizes.
1049 *
1050 * @static
1051 * @param {HTMLElement} el Element to measure
1052 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1053 */
1054 OO.ui.Element.static.getBorders = function ( el ) {
1055 var doc = el.ownerDocument,
1056 win = doc.defaultView,
1057 style = win.getComputedStyle( el, null ),
1058 $el = $( el ),
1059 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
1060 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
1061 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
1062 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
1063
1064 return {
1065 top: top,
1066 left: left,
1067 bottom: bottom,
1068 right: right
1069 };
1070 };
1071
1072 /**
1073 * Get dimensions of an element or window.
1074 *
1075 * @static
1076 * @param {HTMLElement|Window} el Element to measure
1077 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1078 */
1079 OO.ui.Element.static.getDimensions = function ( el ) {
1080 var $el, $win,
1081 doc = el.ownerDocument || el.document,
1082 win = doc.defaultView;
1083
1084 if ( win === el || el === doc.documentElement ) {
1085 $win = $( win );
1086 return {
1087 borders: { top: 0, left: 0, bottom: 0, right: 0 },
1088 scroll: {
1089 top: $win.scrollTop(),
1090 left: $win.scrollLeft()
1091 },
1092 scrollbar: { right: 0, bottom: 0 },
1093 rect: {
1094 top: 0,
1095 left: 0,
1096 bottom: $win.innerHeight(),
1097 right: $win.innerWidth()
1098 }
1099 };
1100 } else {
1101 $el = $( el );
1102 return {
1103 borders: this.getBorders( el ),
1104 scroll: {
1105 top: $el.scrollTop(),
1106 left: $el.scrollLeft()
1107 },
1108 scrollbar: {
1109 right: $el.innerWidth() - el.clientWidth,
1110 bottom: $el.innerHeight() - el.clientHeight
1111 },
1112 rect: el.getBoundingClientRect()
1113 };
1114 }
1115 };
1116
1117 /**
1118 * Get the number of pixels that an element's content is scrolled to the left.
1119 *
1120 * Adapted from <https://github.com/othree/jquery.rtl-scroll-type>.
1121 * Original code copyright 2012 Wei-Ko Kao, licensed under the MIT License.
1122 *
1123 * This function smooths out browser inconsistencies (nicely described in the README at
1124 * <https://github.com/othree/jquery.rtl-scroll-type>) and produces a result consistent
1125 * with Firefox's 'scrollLeft', which seems the sanest.
1126 *
1127 * @static
1128 * @method
1129 * @param {HTMLElement|Window} el Element to measure
1130 * @return {number} Scroll position from the left.
1131 * If the element's direction is LTR, this is a positive number between `0` (initial scroll position)
1132 * and `el.scrollWidth - el.clientWidth` (furthest possible scroll position).
1133 * If the element's direction is RTL, this is a negative number between `0` (initial scroll position)
1134 * and `-el.scrollWidth + el.clientWidth` (furthest possible scroll position).
1135 */
1136 OO.ui.Element.static.getScrollLeft = ( function () {
1137 var rtlScrollType = null;
1138
1139 function test() {
1140 var $definer = $( '<div dir="rtl" style="font-size: 14px; width: 1px; height: 1px; position: absolute; top: -1000px; overflow: scroll">A</div>' ),
1141 definer = $definer[ 0 ];
1142
1143 $definer.appendTo( 'body' );
1144 if ( definer.scrollLeft > 0 ) {
1145 // Safari, Chrome
1146 rtlScrollType = 'default';
1147 } else {
1148 definer.scrollLeft = 1;
1149 if ( definer.scrollLeft === 0 ) {
1150 // Firefox, old Opera
1151 rtlScrollType = 'negative';
1152 } else {
1153 // Internet Explorer, Edge
1154 rtlScrollType = 'reverse';
1155 }
1156 }
1157 $definer.remove();
1158 }
1159
1160 return function getScrollLeft( el ) {
1161 var isRoot = el.window === el ||
1162 el === el.ownerDocument.body ||
1163 el === el.ownerDocument.documentElement,
1164 scrollLeft = isRoot ? $( window ).scrollLeft() : el.scrollLeft,
1165 // All browsers use the correct scroll type ('negative') on the root, so don't
1166 // do any fixups when looking at the root element
1167 direction = isRoot ? 'ltr' : $( el ).css( 'direction' );
1168
1169 if ( direction === 'rtl' ) {
1170 if ( rtlScrollType === null ) {
1171 test();
1172 }
1173 if ( rtlScrollType === 'reverse' ) {
1174 scrollLeft = -scrollLeft;
1175 } else if ( rtlScrollType === 'default' ) {
1176 scrollLeft = scrollLeft - el.scrollWidth + el.clientWidth;
1177 }
1178 }
1179
1180 return scrollLeft;
1181 };
1182 }() );
1183
1184 /**
1185 * Get the root scrollable element of given element's document.
1186 *
1187 * On Blink-based browsers (Chrome etc.), `document.documentElement` can't be used to get or set
1188 * the scrollTop property; instead we have to use `document.body`. Changing and testing the value
1189 * lets us use 'body' or 'documentElement' based on what is working.
1190 *
1191 * https://code.google.com/p/chromium/issues/detail?id=303131
1192 *
1193 * @static
1194 * @param {HTMLElement} el Element to find root scrollable parent for
1195 * @return {HTMLElement} Scrollable parent, `document.body` or `document.documentElement`
1196 * depending on browser
1197 */
1198 OO.ui.Element.static.getRootScrollableElement = function ( el ) {
1199 var scrollTop, body;
1200
1201 if ( OO.ui.scrollableElement === undefined ) {
1202 body = el.ownerDocument.body;
1203 scrollTop = body.scrollTop;
1204 body.scrollTop = 1;
1205
1206 // In some browsers (observed in Chrome 56 on Linux Mint 18.1),
1207 // body.scrollTop doesn't become exactly 1, but a fractional value like 0.76
1208 if ( Math.round( body.scrollTop ) === 1 ) {
1209 body.scrollTop = scrollTop;
1210 OO.ui.scrollableElement = 'body';
1211 } else {
1212 OO.ui.scrollableElement = 'documentElement';
1213 }
1214 }
1215
1216 return el.ownerDocument[ OO.ui.scrollableElement ];
1217 };
1218
1219 /**
1220 * Get closest scrollable container.
1221 *
1222 * Traverses up until either a scrollable element or the root is reached, in which case the root
1223 * scrollable element will be returned (see #getRootScrollableElement).
1224 *
1225 * @static
1226 * @param {HTMLElement} el Element to find scrollable container for
1227 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1228 * @return {HTMLElement} Closest scrollable container
1229 */
1230 OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
1231 var i, val,
1232 // Browsers do not correctly return the computed value of 'overflow' when 'overflow-x' and
1233 // 'overflow-y' have different values, so we need to check the separate properties.
1234 props = [ 'overflow-x', 'overflow-y' ],
1235 $parent = $( el ).parent();
1236
1237 if ( dimension === 'x' || dimension === 'y' ) {
1238 props = [ 'overflow-' + dimension ];
1239 }
1240
1241 // Special case for the document root (which doesn't really have any scrollable container, since
1242 // it is the ultimate scrollable container, but this is probably saner than null or exception)
1243 if ( $( el ).is( 'html, body' ) ) {
1244 return this.getRootScrollableElement( el );
1245 }
1246
1247 while ( $parent.length ) {
1248 if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
1249 return $parent[ 0 ];
1250 }
1251 i = props.length;
1252 while ( i-- ) {
1253 val = $parent.css( props[ i ] );
1254 // We assume that elements with 'overflow' (in any direction) set to 'hidden' will never be
1255 // scrolled in that direction, but they can actually be scrolled programatically. The user can
1256 // unintentionally perform a scroll in such case even if the application doesn't scroll
1257 // programatically, e.g. when jumping to an anchor, or when using built-in find functionality.
1258 // This could cause funny issues...
1259 if ( val === 'auto' || val === 'scroll' ) {
1260 return $parent[ 0 ];
1261 }
1262 }
1263 $parent = $parent.parent();
1264 }
1265 // The element is unattached... return something mostly sane
1266 return this.getRootScrollableElement( el );
1267 };
1268
1269 /**
1270 * Scroll element into view.
1271 *
1272 * @static
1273 * @param {HTMLElement} el Element to scroll into view
1274 * @param {Object} [config] Configuration options
1275 * @param {string} [config.duration='fast'] jQuery animation duration value
1276 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1277 * to scroll in both directions
1278 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1279 */
1280 OO.ui.Element.static.scrollIntoView = function ( el, config ) {
1281 var position, animations, container, $container, elementDimensions, containerDimensions, $window,
1282 deferred = $.Deferred();
1283
1284 // Configuration initialization
1285 config = config || {};
1286
1287 animations = {};
1288 container = this.getClosestScrollableContainer( el, config.direction );
1289 $container = $( container );
1290 elementDimensions = this.getDimensions( el );
1291 containerDimensions = this.getDimensions( container );
1292 $window = $( this.getWindow( el ) );
1293
1294 // Compute the element's position relative to the container
1295 if ( $container.is( 'html, body' ) ) {
1296 // If the scrollable container is the root, this is easy
1297 position = {
1298 top: elementDimensions.rect.top,
1299 bottom: $window.innerHeight() - elementDimensions.rect.bottom,
1300 left: elementDimensions.rect.left,
1301 right: $window.innerWidth() - elementDimensions.rect.right
1302 };
1303 } else {
1304 // Otherwise, we have to subtract el's coordinates from container's coordinates
1305 position = {
1306 top: elementDimensions.rect.top - ( containerDimensions.rect.top + containerDimensions.borders.top ),
1307 bottom: containerDimensions.rect.bottom - containerDimensions.borders.bottom - containerDimensions.scrollbar.bottom - elementDimensions.rect.bottom,
1308 left: elementDimensions.rect.left - ( containerDimensions.rect.left + containerDimensions.borders.left ),
1309 right: containerDimensions.rect.right - containerDimensions.borders.right - containerDimensions.scrollbar.right - elementDimensions.rect.right
1310 };
1311 }
1312
1313 if ( !config.direction || config.direction === 'y' ) {
1314 if ( position.top < 0 ) {
1315 animations.scrollTop = containerDimensions.scroll.top + position.top;
1316 } else if ( position.top > 0 && position.bottom < 0 ) {
1317 animations.scrollTop = containerDimensions.scroll.top + Math.min( position.top, -position.bottom );
1318 }
1319 }
1320 if ( !config.direction || config.direction === 'x' ) {
1321 if ( position.left < 0 ) {
1322 animations.scrollLeft = containerDimensions.scroll.left + position.left;
1323 } else if ( position.left > 0 && position.right < 0 ) {
1324 animations.scrollLeft = containerDimensions.scroll.left + Math.min( position.left, -position.right );
1325 }
1326 }
1327 if ( !$.isEmptyObject( animations ) ) {
1328 $container.stop( true ).animate( animations, config.duration === undefined ? 'fast' : config.duration );
1329 $container.queue( function ( next ) {
1330 deferred.resolve();
1331 next();
1332 } );
1333 } else {
1334 deferred.resolve();
1335 }
1336 return deferred.promise();
1337 };
1338
1339 /**
1340 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1341 * and reserve space for them, because it probably doesn't.
1342 *
1343 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1344 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1345 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1346 * and then reattach (or show) them back.
1347 *
1348 * @static
1349 * @param {HTMLElement} el Element to reconsider the scrollbars on
1350 */
1351 OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
1352 var i, len, scrollLeft, scrollTop, nodes = [];
1353 // Save scroll position
1354 scrollLeft = el.scrollLeft;
1355 scrollTop = el.scrollTop;
1356 // Detach all children
1357 while ( el.firstChild ) {
1358 nodes.push( el.firstChild );
1359 el.removeChild( el.firstChild );
1360 }
1361 // Force reflow
1362 void el.offsetHeight;
1363 // Reattach all children
1364 for ( i = 0, len = nodes.length; i < len; i++ ) {
1365 el.appendChild( nodes[ i ] );
1366 }
1367 // Restore scroll position (no-op if scrollbars disappeared)
1368 el.scrollLeft = scrollLeft;
1369 el.scrollTop = scrollTop;
1370 };
1371
1372 /* Methods */
1373
1374 /**
1375 * Toggle visibility of an element.
1376 *
1377 * @param {boolean} [show] Make element visible, omit to toggle visibility
1378 * @fires visible
1379 * @chainable
1380 */
1381 OO.ui.Element.prototype.toggle = function ( show ) {
1382 show = show === undefined ? !this.visible : !!show;
1383
1384 if ( show !== this.isVisible() ) {
1385 this.visible = show;
1386 this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
1387 this.emit( 'toggle', show );
1388 }
1389
1390 return this;
1391 };
1392
1393 /**
1394 * Check if element is visible.
1395 *
1396 * @return {boolean} element is visible
1397 */
1398 OO.ui.Element.prototype.isVisible = function () {
1399 return this.visible;
1400 };
1401
1402 /**
1403 * Get element data.
1404 *
1405 * @return {Mixed} Element data
1406 */
1407 OO.ui.Element.prototype.getData = function () {
1408 return this.data;
1409 };
1410
1411 /**
1412 * Set element data.
1413 *
1414 * @param {Mixed} data Element data
1415 * @chainable
1416 */
1417 OO.ui.Element.prototype.setData = function ( data ) {
1418 this.data = data;
1419 return this;
1420 };
1421
1422 /**
1423 * Set the element has an 'id' attribute.
1424 *
1425 * @param {string} id
1426 * @chainable
1427 */
1428 OO.ui.Element.prototype.setElementId = function ( id ) {
1429 this.elementId = id;
1430 this.$element.attr( 'id', id );
1431 return this;
1432 };
1433
1434 /**
1435 * Ensure that the element has an 'id' attribute, setting it to an unique value if it's missing,
1436 * and return its value.
1437 *
1438 * @return {string}
1439 */
1440 OO.ui.Element.prototype.getElementId = function () {
1441 if ( this.elementId === null ) {
1442 this.setElementId( OO.ui.generateElementId() );
1443 }
1444 return this.elementId;
1445 };
1446
1447 /**
1448 * Check if element supports one or more methods.
1449 *
1450 * @param {string|string[]} methods Method or list of methods to check
1451 * @return {boolean} All methods are supported
1452 */
1453 OO.ui.Element.prototype.supports = function ( methods ) {
1454 var i, len,
1455 support = 0;
1456
1457 methods = Array.isArray( methods ) ? methods : [ methods ];
1458 for ( i = 0, len = methods.length; i < len; i++ ) {
1459 if ( $.isFunction( this[ methods[ i ] ] ) ) {
1460 support++;
1461 }
1462 }
1463
1464 return methods.length === support;
1465 };
1466
1467 /**
1468 * Update the theme-provided classes.
1469 *
1470 * @localdoc This is called in element mixins and widget classes any time state changes.
1471 * Updating is debounced, minimizing overhead of changing multiple attributes and
1472 * guaranteeing that theme updates do not occur within an element's constructor
1473 */
1474 OO.ui.Element.prototype.updateThemeClasses = function () {
1475 OO.ui.theme.queueUpdateElementClasses( this );
1476 };
1477
1478 /**
1479 * Get the HTML tag name.
1480 *
1481 * Override this method to base the result on instance information.
1482 *
1483 * @return {string} HTML tag name
1484 */
1485 OO.ui.Element.prototype.getTagName = function () {
1486 return this.constructor.static.tagName;
1487 };
1488
1489 /**
1490 * Check if the element is attached to the DOM
1491 *
1492 * @return {boolean} The element is attached to the DOM
1493 */
1494 OO.ui.Element.prototype.isElementAttached = function () {
1495 return $.contains( this.getElementDocument(), this.$element[ 0 ] );
1496 };
1497
1498 /**
1499 * Get the DOM document.
1500 *
1501 * @return {HTMLDocument} Document object
1502 */
1503 OO.ui.Element.prototype.getElementDocument = function () {
1504 // Don't cache this in other ways either because subclasses could can change this.$element
1505 return OO.ui.Element.static.getDocument( this.$element );
1506 };
1507
1508 /**
1509 * Get the DOM window.
1510 *
1511 * @return {Window} Window object
1512 */
1513 OO.ui.Element.prototype.getElementWindow = function () {
1514 return OO.ui.Element.static.getWindow( this.$element );
1515 };
1516
1517 /**
1518 * Get closest scrollable container.
1519 *
1520 * @return {HTMLElement} Closest scrollable container
1521 */
1522 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1523 return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
1524 };
1525
1526 /**
1527 * Get group element is in.
1528 *
1529 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1530 */
1531 OO.ui.Element.prototype.getElementGroup = function () {
1532 return this.elementGroup;
1533 };
1534
1535 /**
1536 * Set group element is in.
1537 *
1538 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1539 * @chainable
1540 */
1541 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1542 this.elementGroup = group;
1543 return this;
1544 };
1545
1546 /**
1547 * Scroll element into view.
1548 *
1549 * @param {Object} [config] Configuration options
1550 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1551 */
1552 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
1553 if (
1554 !this.isElementAttached() ||
1555 !this.isVisible() ||
1556 ( this.getElementGroup() && !this.getElementGroup().isVisible() )
1557 ) {
1558 return $.Deferred().resolve();
1559 }
1560 return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
1561 };
1562
1563 /**
1564 * Restore the pre-infusion dynamic state for this widget.
1565 *
1566 * This method is called after #$element has been inserted into DOM. The parameter is the return
1567 * value of #gatherPreInfuseState.
1568 *
1569 * @protected
1570 * @param {Object} state
1571 */
1572 OO.ui.Element.prototype.restorePreInfuseState = function () {
1573 };
1574
1575 /**
1576 * Wraps an HTML snippet for use with configuration values which default
1577 * to strings. This bypasses the default html-escaping done to string
1578 * values.
1579 *
1580 * @class
1581 *
1582 * @constructor
1583 * @param {string} [content] HTML content
1584 */
1585 OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
1586 // Properties
1587 this.content = content;
1588 };
1589
1590 /* Setup */
1591
1592 OO.initClass( OO.ui.HtmlSnippet );
1593
1594 /* Methods */
1595
1596 /**
1597 * Render into HTML.
1598 *
1599 * @return {string} Unchanged HTML snippet.
1600 */
1601 OO.ui.HtmlSnippet.prototype.toString = function () {
1602 return this.content;
1603 };
1604
1605 /**
1606 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1607 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1608 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1609 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1610 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1611 *
1612 * @abstract
1613 * @class
1614 * @extends OO.ui.Element
1615 * @mixins OO.EventEmitter
1616 *
1617 * @constructor
1618 * @param {Object} [config] Configuration options
1619 */
1620 OO.ui.Layout = function OoUiLayout( config ) {
1621 // Configuration initialization
1622 config = config || {};
1623
1624 // Parent constructor
1625 OO.ui.Layout.parent.call( this, config );
1626
1627 // Mixin constructors
1628 OO.EventEmitter.call( this );
1629
1630 // Initialization
1631 this.$element.addClass( 'oo-ui-layout' );
1632 };
1633
1634 /* Setup */
1635
1636 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1637 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1638
1639 /**
1640 * Widgets are compositions of one or more OOUI elements that users can both view
1641 * and interact with. All widgets can be configured and modified via a standard API,
1642 * and their state can change dynamically according to a model.
1643 *
1644 * @abstract
1645 * @class
1646 * @extends OO.ui.Element
1647 * @mixins OO.EventEmitter
1648 *
1649 * @constructor
1650 * @param {Object} [config] Configuration options
1651 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1652 * appearance reflects this state.
1653 */
1654 OO.ui.Widget = function OoUiWidget( config ) {
1655 // Initialize config
1656 config = $.extend( { disabled: false }, config );
1657
1658 // Parent constructor
1659 OO.ui.Widget.parent.call( this, config );
1660
1661 // Mixin constructors
1662 OO.EventEmitter.call( this );
1663
1664 // Properties
1665 this.disabled = null;
1666 this.wasDisabled = null;
1667
1668 // Initialization
1669 this.$element.addClass( 'oo-ui-widget' );
1670 this.setDisabled( !!config.disabled );
1671 };
1672
1673 /* Setup */
1674
1675 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
1676 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
1677
1678 /* Events */
1679
1680 /**
1681 * @event disable
1682 *
1683 * A 'disable' event is emitted when the disabled state of the widget changes
1684 * (i.e. on disable **and** enable).
1685 *
1686 * @param {boolean} disabled Widget is disabled
1687 */
1688
1689 /**
1690 * @event toggle
1691 *
1692 * A 'toggle' event is emitted when the visibility of the widget changes.
1693 *
1694 * @param {boolean} visible Widget is visible
1695 */
1696
1697 /* Methods */
1698
1699 /**
1700 * Check if the widget is disabled.
1701 *
1702 * @return {boolean} Widget is disabled
1703 */
1704 OO.ui.Widget.prototype.isDisabled = function () {
1705 return this.disabled;
1706 };
1707
1708 /**
1709 * Set the 'disabled' state of the widget.
1710 *
1711 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1712 *
1713 * @param {boolean} disabled Disable widget
1714 * @chainable
1715 */
1716 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
1717 var isDisabled;
1718
1719 this.disabled = !!disabled;
1720 isDisabled = this.isDisabled();
1721 if ( isDisabled !== this.wasDisabled ) {
1722 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
1723 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
1724 this.$element.attr( 'aria-disabled', isDisabled.toString() );
1725 this.emit( 'disable', isDisabled );
1726 this.updateThemeClasses();
1727 }
1728 this.wasDisabled = isDisabled;
1729
1730 return this;
1731 };
1732
1733 /**
1734 * Update the disabled state, in case of changes in parent widget.
1735 *
1736 * @chainable
1737 */
1738 OO.ui.Widget.prototype.updateDisabled = function () {
1739 this.setDisabled( this.disabled );
1740 return this;
1741 };
1742
1743 /**
1744 * Get an ID of a labelable node which is part of this widget, if any, to be used for `<label for>`
1745 * value.
1746 *
1747 * If this function returns null, the widget should have a meaningful #simulateLabelClick method
1748 * instead.
1749 *
1750 * @return {string|null} The ID of the labelable element
1751 */
1752 OO.ui.Widget.prototype.getInputId = function () {
1753 return null;
1754 };
1755
1756 /**
1757 * Simulate the behavior of clicking on a label (a HTML `<label>` element) bound to this input.
1758 * HTML only allows `<label>` to act on specific "labelable" elements; complex widgets might need to
1759 * override this method to provide intuitive, accessible behavior.
1760 *
1761 * By default, this does nothing. OO.ui.mixin.TabIndexedElement overrides it for focusable widgets.
1762 * Individual widgets may override it too.
1763 *
1764 * This method is called by OO.ui.LabelWidget and OO.ui.FieldLayout. It should not be called
1765 * directly.
1766 */
1767 OO.ui.Widget.prototype.simulateLabelClick = function () {
1768 };
1769
1770 /**
1771 * Theme logic.
1772 *
1773 * @abstract
1774 * @class
1775 *
1776 * @constructor
1777 */
1778 OO.ui.Theme = function OoUiTheme() {
1779 this.elementClassesQueue = [];
1780 this.debouncedUpdateQueuedElementClasses = OO.ui.debounce( this.updateQueuedElementClasses );
1781 };
1782
1783 /* Setup */
1784
1785 OO.initClass( OO.ui.Theme );
1786
1787 /* Methods */
1788
1789 /**
1790 * Get a list of classes to be applied to a widget.
1791 *
1792 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
1793 * otherwise state transitions will not work properly.
1794 *
1795 * @param {OO.ui.Element} element Element for which to get classes
1796 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1797 */
1798 OO.ui.Theme.prototype.getElementClasses = function () {
1799 return { on: [], off: [] };
1800 };
1801
1802 /**
1803 * Update CSS classes provided by the theme.
1804 *
1805 * For elements with theme logic hooks, this should be called any time there's a state change.
1806 *
1807 * @param {OO.ui.Element} element Element for which to update classes
1808 */
1809 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
1810 var $elements = $( [] ),
1811 classes = this.getElementClasses( element );
1812
1813 if ( element.$icon ) {
1814 $elements = $elements.add( element.$icon );
1815 }
1816 if ( element.$indicator ) {
1817 $elements = $elements.add( element.$indicator );
1818 }
1819
1820 $elements
1821 .removeClass( classes.off.join( ' ' ) )
1822 .addClass( classes.on.join( ' ' ) );
1823 };
1824
1825 /**
1826 * @private
1827 */
1828 OO.ui.Theme.prototype.updateQueuedElementClasses = function () {
1829 var i;
1830 for ( i = 0; i < this.elementClassesQueue.length; i++ ) {
1831 this.updateElementClasses( this.elementClassesQueue[ i ] );
1832 }
1833 // Clear the queue
1834 this.elementClassesQueue = [];
1835 };
1836
1837 /**
1838 * Queue #updateElementClasses to be called for this element.
1839 *
1840 * @localdoc QUnit tests override this method to directly call #queueUpdateElementClasses,
1841 * to make them synchronous.
1842 *
1843 * @param {OO.ui.Element} element Element for which to update classes
1844 */
1845 OO.ui.Theme.prototype.queueUpdateElementClasses = function ( element ) {
1846 // Keep items in the queue unique. Use lastIndexOf to start checking from the end because that's
1847 // the most common case (this method is often called repeatedly for the same element).
1848 if ( this.elementClassesQueue.lastIndexOf( element ) !== -1 ) {
1849 return;
1850 }
1851 this.elementClassesQueue.push( element );
1852 this.debouncedUpdateQueuedElementClasses();
1853 };
1854
1855 /**
1856 * Get the transition duration in milliseconds for dialogs opening/closing
1857 *
1858 * The dialog should be fully rendered this many milliseconds after the
1859 * ready process has executed.
1860 *
1861 * @return {number} Transition duration in milliseconds
1862 */
1863 OO.ui.Theme.prototype.getDialogTransitionDuration = function () {
1864 return 0;
1865 };
1866
1867 /**
1868 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
1869 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
1870 * order in which users will navigate through the focusable elements via the "tab" key.
1871 *
1872 * @example
1873 * // TabIndexedElement is mixed into the ButtonWidget class
1874 * // to provide a tabIndex property.
1875 * var button1 = new OO.ui.ButtonWidget( {
1876 * label: 'fourth',
1877 * tabIndex: 4
1878 * } );
1879 * var button2 = new OO.ui.ButtonWidget( {
1880 * label: 'second',
1881 * tabIndex: 2
1882 * } );
1883 * var button3 = new OO.ui.ButtonWidget( {
1884 * label: 'third',
1885 * tabIndex: 3
1886 * } );
1887 * var button4 = new OO.ui.ButtonWidget( {
1888 * label: 'first',
1889 * tabIndex: 1
1890 * } );
1891 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
1892 *
1893 * @abstract
1894 * @class
1895 *
1896 * @constructor
1897 * @param {Object} [config] Configuration options
1898 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
1899 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
1900 * functionality will be applied to it instead.
1901 * @cfg {string|number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
1902 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
1903 * to remove the element from the tab-navigation flow.
1904 */
1905 OO.ui.mixin.TabIndexedElement = function OoUiMixinTabIndexedElement( config ) {
1906 // Configuration initialization
1907 config = $.extend( { tabIndex: 0 }, config );
1908
1909 // Properties
1910 this.$tabIndexed = null;
1911 this.tabIndex = null;
1912
1913 // Events
1914 this.connect( this, { disable: 'onTabIndexedElementDisable' } );
1915
1916 // Initialization
1917 this.setTabIndex( config.tabIndex );
1918 this.setTabIndexedElement( config.$tabIndexed || this.$element );
1919 };
1920
1921 /* Setup */
1922
1923 OO.initClass( OO.ui.mixin.TabIndexedElement );
1924
1925 /* Methods */
1926
1927 /**
1928 * Set the element that should use the tabindex functionality.
1929 *
1930 * This method is used to retarget a tabindex mixin so that its functionality applies
1931 * to the specified element. If an element is currently using the functionality, the mixin’s
1932 * effect on that element is removed before the new element is set up.
1933 *
1934 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
1935 * @chainable
1936 */
1937 OO.ui.mixin.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
1938 var tabIndex = this.tabIndex;
1939 // Remove attributes from old $tabIndexed
1940 this.setTabIndex( null );
1941 // Force update of new $tabIndexed
1942 this.$tabIndexed = $tabIndexed;
1943 this.tabIndex = tabIndex;
1944 return this.updateTabIndex();
1945 };
1946
1947 /**
1948 * Set the value of the tabindex.
1949 *
1950 * @param {string|number|null} tabIndex Tabindex value, or `null` for no tabindex
1951 * @chainable
1952 */
1953 OO.ui.mixin.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
1954 tabIndex = /^-?\d+$/.test( tabIndex ) ? Number( tabIndex ) : null;
1955
1956 if ( this.tabIndex !== tabIndex ) {
1957 this.tabIndex = tabIndex;
1958 this.updateTabIndex();
1959 }
1960
1961 return this;
1962 };
1963
1964 /**
1965 * Update the `tabindex` attribute, in case of changes to tab index or
1966 * disabled state.
1967 *
1968 * @private
1969 * @chainable
1970 */
1971 OO.ui.mixin.TabIndexedElement.prototype.updateTabIndex = function () {
1972 if ( this.$tabIndexed ) {
1973 if ( this.tabIndex !== null ) {
1974 // Do not index over disabled elements
1975 this.$tabIndexed.attr( {
1976 tabindex: this.isDisabled() ? -1 : this.tabIndex,
1977 // Support: ChromeVox and NVDA
1978 // These do not seem to inherit aria-disabled from parent elements
1979 'aria-disabled': this.isDisabled().toString()
1980 } );
1981 } else {
1982 this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
1983 }
1984 }
1985 return this;
1986 };
1987
1988 /**
1989 * Handle disable events.
1990 *
1991 * @private
1992 * @param {boolean} disabled Element is disabled
1993 */
1994 OO.ui.mixin.TabIndexedElement.prototype.onTabIndexedElementDisable = function () {
1995 this.updateTabIndex();
1996 };
1997
1998 /**
1999 * Get the value of the tabindex.
2000 *
2001 * @return {number|null} Tabindex value
2002 */
2003 OO.ui.mixin.TabIndexedElement.prototype.getTabIndex = function () {
2004 return this.tabIndex;
2005 };
2006
2007 /**
2008 * Get an ID of a focusable element of this widget, if any, to be used for `<label for>` value.
2009 *
2010 * If the element already has an ID then that is returned, otherwise unique ID is
2011 * generated, set on the element, and returned.
2012 *
2013 * @return {string|null} The ID of the focusable element
2014 */
2015 OO.ui.mixin.TabIndexedElement.prototype.getInputId = function () {
2016 var id;
2017
2018 if ( !this.$tabIndexed ) {
2019 return null;
2020 }
2021 if ( !this.isLabelableNode( this.$tabIndexed ) ) {
2022 return null;
2023 }
2024
2025 id = this.$tabIndexed.attr( 'id' );
2026 if ( id === undefined ) {
2027 id = OO.ui.generateElementId();
2028 this.$tabIndexed.attr( 'id', id );
2029 }
2030
2031 return id;
2032 };
2033
2034 /**
2035 * Whether the node is 'labelable' according to the HTML spec
2036 * (i.e., whether it can be interacted with through a `<label for="…">`).
2037 * See: <https://html.spec.whatwg.org/multipage/forms.html#category-label>.
2038 *
2039 * @private
2040 * @param {jQuery} $node
2041 * @return {boolean}
2042 */
2043 OO.ui.mixin.TabIndexedElement.prototype.isLabelableNode = function ( $node ) {
2044 var
2045 labelableTags = [ 'button', 'meter', 'output', 'progress', 'select', 'textarea' ],
2046 tagName = $node.prop( 'tagName' ).toLowerCase();
2047
2048 if ( tagName === 'input' && $node.attr( 'type' ) !== 'hidden' ) {
2049 return true;
2050 }
2051 if ( labelableTags.indexOf( tagName ) !== -1 ) {
2052 return true;
2053 }
2054 return false;
2055 };
2056
2057 /**
2058 * Focus this element.
2059 *
2060 * @chainable
2061 */
2062 OO.ui.mixin.TabIndexedElement.prototype.focus = function () {
2063 if ( !this.isDisabled() ) {
2064 this.$tabIndexed.focus();
2065 }
2066 return this;
2067 };
2068
2069 /**
2070 * Blur this element.
2071 *
2072 * @chainable
2073 */
2074 OO.ui.mixin.TabIndexedElement.prototype.blur = function () {
2075 this.$tabIndexed.blur();
2076 return this;
2077 };
2078
2079 /**
2080 * @inheritdoc OO.ui.Widget
2081 */
2082 OO.ui.mixin.TabIndexedElement.prototype.simulateLabelClick = function () {
2083 this.focus();
2084 };
2085
2086 /**
2087 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
2088 * interface element that can be configured with access keys for accessibility.
2089 * See the [OOUI documentation on MediaWiki] [1] for examples.
2090 *
2091 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches#Buttons
2092 *
2093 * @abstract
2094 * @class
2095 *
2096 * @constructor
2097 * @param {Object} [config] Configuration options
2098 * @cfg {jQuery} [$button] The button element created by the class.
2099 * If this configuration is omitted, the button element will use a generated `<a>`.
2100 * @cfg {boolean} [framed=true] Render the button with a frame
2101 */
2102 OO.ui.mixin.ButtonElement = function OoUiMixinButtonElement( config ) {
2103 // Configuration initialization
2104 config = config || {};
2105
2106 // Properties
2107 this.$button = null;
2108 this.framed = null;
2109 this.active = config.active !== undefined && config.active;
2110 this.onMouseUpHandler = this.onMouseUp.bind( this );
2111 this.onMouseDownHandler = this.onMouseDown.bind( this );
2112 this.onKeyDownHandler = this.onKeyDown.bind( this );
2113 this.onKeyUpHandler = this.onKeyUp.bind( this );
2114 this.onClickHandler = this.onClick.bind( this );
2115 this.onKeyPressHandler = this.onKeyPress.bind( this );
2116
2117 // Initialization
2118 this.$element.addClass( 'oo-ui-buttonElement' );
2119 this.toggleFramed( config.framed === undefined || config.framed );
2120 this.setButtonElement( config.$button || $( '<a>' ) );
2121 };
2122
2123 /* Setup */
2124
2125 OO.initClass( OO.ui.mixin.ButtonElement );
2126
2127 /* Static Properties */
2128
2129 /**
2130 * Cancel mouse down events.
2131 *
2132 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
2133 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
2134 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
2135 * parent widget.
2136 *
2137 * @static
2138 * @inheritable
2139 * @property {boolean}
2140 */
2141 OO.ui.mixin.ButtonElement.static.cancelButtonMouseDownEvents = true;
2142
2143 /* Events */
2144
2145 /**
2146 * A 'click' event is emitted when the button element is clicked.
2147 *
2148 * @event click
2149 */
2150
2151 /* Methods */
2152
2153 /**
2154 * Set the button element.
2155 *
2156 * This method is used to retarget a button mixin so that its functionality applies to
2157 * the specified button element instead of the one created by the class. If a button element
2158 * is already set, the method will remove the mixin’s effect on that element.
2159 *
2160 * @param {jQuery} $button Element to use as button
2161 */
2162 OO.ui.mixin.ButtonElement.prototype.setButtonElement = function ( $button ) {
2163 if ( this.$button ) {
2164 this.$button
2165 .removeClass( 'oo-ui-buttonElement-button' )
2166 .removeAttr( 'role accesskey' )
2167 .off( {
2168 mousedown: this.onMouseDownHandler,
2169 keydown: this.onKeyDownHandler,
2170 click: this.onClickHandler,
2171 keypress: this.onKeyPressHandler
2172 } );
2173 }
2174
2175 this.$button = $button
2176 .addClass( 'oo-ui-buttonElement-button' )
2177 .on( {
2178 mousedown: this.onMouseDownHandler,
2179 keydown: this.onKeyDownHandler,
2180 click: this.onClickHandler,
2181 keypress: this.onKeyPressHandler
2182 } );
2183
2184 // Add `role="button"` on `<a>` elements, where it's needed
2185 // `toUppercase()` is added for XHTML documents
2186 if ( this.$button.prop( 'tagName' ).toUpperCase() === 'A' ) {
2187 this.$button.attr( 'role', 'button' );
2188 }
2189 };
2190
2191 /**
2192 * Handles mouse down events.
2193 *
2194 * @protected
2195 * @param {jQuery.Event} e Mouse down event
2196 */
2197 OO.ui.mixin.ButtonElement.prototype.onMouseDown = function ( e ) {
2198 if ( this.isDisabled() || e.which !== OO.ui.MouseButtons.LEFT ) {
2199 return;
2200 }
2201 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
2202 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
2203 // reliably remove the pressed class
2204 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true );
2205 // Prevent change of focus unless specifically configured otherwise
2206 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
2207 return false;
2208 }
2209 };
2210
2211 /**
2212 * Handles mouse up events.
2213 *
2214 * @protected
2215 * @param {MouseEvent} e Mouse up event
2216 */
2217 OO.ui.mixin.ButtonElement.prototype.onMouseUp = function ( e ) {
2218 if ( this.isDisabled() || e.which !== OO.ui.MouseButtons.LEFT ) {
2219 return;
2220 }
2221 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
2222 // Stop listening for mouseup, since we only needed this once
2223 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true );
2224 };
2225
2226 /**
2227 * Handles mouse click events.
2228 *
2229 * @protected
2230 * @param {jQuery.Event} e Mouse click event
2231 * @fires click
2232 */
2233 OO.ui.mixin.ButtonElement.prototype.onClick = function ( e ) {
2234 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
2235 if ( this.emit( 'click' ) ) {
2236 return false;
2237 }
2238 }
2239 };
2240
2241 /**
2242 * Handles key down events.
2243 *
2244 * @protected
2245 * @param {jQuery.Event} e Key down event
2246 */
2247 OO.ui.mixin.ButtonElement.prototype.onKeyDown = function ( e ) {
2248 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
2249 return;
2250 }
2251 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
2252 // Run the keyup handler no matter where the key is when the button is let go, so we can
2253 // reliably remove the pressed class
2254 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler, true );
2255 };
2256
2257 /**
2258 * Handles key up events.
2259 *
2260 * @protected
2261 * @param {KeyboardEvent} e Key up event
2262 */
2263 OO.ui.mixin.ButtonElement.prototype.onKeyUp = function ( e ) {
2264 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
2265 return;
2266 }
2267 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
2268 // Stop listening for keyup, since we only needed this once
2269 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler, true );
2270 };
2271
2272 /**
2273 * Handles key press events.
2274 *
2275 * @protected
2276 * @param {jQuery.Event} e Key press event
2277 * @fires click
2278 */
2279 OO.ui.mixin.ButtonElement.prototype.onKeyPress = function ( e ) {
2280 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
2281 if ( this.emit( 'click' ) ) {
2282 return false;
2283 }
2284 }
2285 };
2286
2287 /**
2288 * Check if button has a frame.
2289 *
2290 * @return {boolean} Button is framed
2291 */
2292 OO.ui.mixin.ButtonElement.prototype.isFramed = function () {
2293 return this.framed;
2294 };
2295
2296 /**
2297 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
2298 *
2299 * @param {boolean} [framed] Make button framed, omit to toggle
2300 * @chainable
2301 */
2302 OO.ui.mixin.ButtonElement.prototype.toggleFramed = function ( framed ) {
2303 framed = framed === undefined ? !this.framed : !!framed;
2304 if ( framed !== this.framed ) {
2305 this.framed = framed;
2306 this.$element
2307 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
2308 .toggleClass( 'oo-ui-buttonElement-framed', framed );
2309 this.updateThemeClasses();
2310 }
2311
2312 return this;
2313 };
2314
2315 /**
2316 * Set the button's active state.
2317 *
2318 * The active state can be set on:
2319 *
2320 * - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected
2321 * - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on
2322 * - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page
2323 *
2324 * @protected
2325 * @param {boolean} value Make button active
2326 * @chainable
2327 */
2328 OO.ui.mixin.ButtonElement.prototype.setActive = function ( value ) {
2329 this.active = !!value;
2330 this.$element.toggleClass( 'oo-ui-buttonElement-active', this.active );
2331 this.updateThemeClasses();
2332 return this;
2333 };
2334
2335 /**
2336 * Check if the button is active
2337 *
2338 * @protected
2339 * @return {boolean} The button is active
2340 */
2341 OO.ui.mixin.ButtonElement.prototype.isActive = function () {
2342 return this.active;
2343 };
2344
2345 /**
2346 * Any OOUI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
2347 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
2348 * items from the group is done through the interface the class provides.
2349 * For more information, please see the [OOUI documentation on MediaWiki] [1].
2350 *
2351 * [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Groups
2352 *
2353 * @abstract
2354 * @mixins OO.EmitterList
2355 * @class
2356 *
2357 * @constructor
2358 * @param {Object} [config] Configuration options
2359 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
2360 * is omitted, the group element will use a generated `<div>`.
2361 */
2362 OO.ui.mixin.GroupElement = function OoUiMixinGroupElement( config ) {
2363 // Configuration initialization
2364 config = config || {};
2365
2366 // Mixin constructors
2367 OO.EmitterList.call( this, config );
2368
2369 // Properties
2370 this.$group = null;
2371
2372 // Initialization
2373 this.setGroupElement( config.$group || $( '<div>' ) );
2374 };
2375
2376 /* Setup */
2377
2378 OO.mixinClass( OO.ui.mixin.GroupElement, OO.EmitterList );
2379
2380 /* Events */
2381
2382 /**
2383 * @event change
2384 *
2385 * A change event is emitted when the set of selected items changes.
2386 *
2387 * @param {OO.ui.Element[]} items Items currently in the group
2388 */
2389
2390 /* Methods */
2391
2392 /**
2393 * Set the group element.
2394 *
2395 * If an element is already set, items will be moved to the new element.
2396 *
2397 * @param {jQuery} $group Element to use as group
2398 */
2399 OO.ui.mixin.GroupElement.prototype.setGroupElement = function ( $group ) {
2400 var i, len;
2401
2402 this.$group = $group;
2403 for ( i = 0, len = this.items.length; i < len; i++ ) {
2404 this.$group.append( this.items[ i ].$element );
2405 }
2406 };
2407
2408 /**
2409 * Find an item by its data.
2410 *
2411 * Only the first item with matching data will be returned. To return all matching items,
2412 * use the #findItemsFromData method.
2413 *
2414 * @param {Object} data Item data to search for
2415 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2416 */
2417 OO.ui.mixin.GroupElement.prototype.findItemFromData = function ( data ) {
2418 var i, len, item,
2419 hash = OO.getHash( data );
2420
2421 for ( i = 0, len = this.items.length; i < len; i++ ) {
2422 item = this.items[ i ];
2423 if ( hash === OO.getHash( item.getData() ) ) {
2424 return item;
2425 }
2426 }
2427
2428 return null;
2429 };
2430
2431 /**
2432 * Find items by their data.
2433 *
2434 * All items with matching data will be returned. To return only the first match, use the #findItemFromData method instead.
2435 *
2436 * @param {Object} data Item data to search for
2437 * @return {OO.ui.Element[]} Items with equivalent data
2438 */
2439 OO.ui.mixin.GroupElement.prototype.findItemsFromData = function ( data ) {
2440 var i, len, item,
2441 hash = OO.getHash( data ),
2442 items = [];
2443
2444 for ( i = 0, len = this.items.length; i < len; i++ ) {
2445 item = this.items[ i ];
2446 if ( hash === OO.getHash( item.getData() ) ) {
2447 items.push( item );
2448 }
2449 }
2450
2451 return items;
2452 };
2453
2454 /**
2455 * Add items to the group.
2456 *
2457 * Items will be added to the end of the group array unless the optional `index` parameter specifies
2458 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
2459 *
2460 * @param {OO.ui.Element[]} items An array of items to add to the group
2461 * @param {number} [index] Index of the insertion point
2462 * @chainable
2463 */
2464 OO.ui.mixin.GroupElement.prototype.addItems = function ( items, index ) {
2465 // Mixin method
2466 OO.EmitterList.prototype.addItems.call( this, items, index );
2467
2468 this.emit( 'change', this.getItems() );
2469 return this;
2470 };
2471
2472 /**
2473 * @inheritdoc
2474 */
2475 OO.ui.mixin.GroupElement.prototype.moveItem = function ( items, newIndex ) {
2476 // insertItemElements expects this.items to not have been modified yet, so call before the mixin
2477 this.insertItemElements( items, newIndex );
2478
2479 // Mixin method
2480 newIndex = OO.EmitterList.prototype.moveItem.call( this, items, newIndex );
2481
2482 return newIndex;
2483 };
2484
2485 /**
2486 * @inheritdoc
2487 */
2488 OO.ui.mixin.GroupElement.prototype.insertItem = function ( item, index ) {
2489 item.setElementGroup( this );
2490 this.insertItemElements( item, index );
2491
2492 // Mixin method
2493 index = OO.EmitterList.prototype.insertItem.call( this, item, index );
2494
2495 return index;
2496 };
2497
2498 /**
2499 * Insert elements into the group
2500 *
2501 * @private
2502 * @param {OO.ui.Element} itemWidget Item to insert
2503 * @param {number} index Insertion index
2504 */
2505 OO.ui.mixin.GroupElement.prototype.insertItemElements = function ( itemWidget, index ) {
2506 if ( index === undefined || index < 0 || index >= this.items.length ) {
2507 this.$group.append( itemWidget.$element );
2508 } else if ( index === 0 ) {
2509 this.$group.prepend( itemWidget.$element );
2510 } else {
2511 this.items[ index ].$element.before( itemWidget.$element );
2512 }
2513 };
2514
2515 /**
2516 * Remove the specified items from a group.
2517 *
2518 * Removed items are detached (not removed) from the DOM so that they may be reused.
2519 * To remove all items from a group, you may wish to use the #clearItems method instead.
2520 *
2521 * @param {OO.ui.Element[]} items An array of items to remove
2522 * @chainable
2523 */
2524 OO.ui.mixin.GroupElement.prototype.removeItems = function ( items ) {
2525 var i, len, item, index;
2526
2527 // Remove specific items elements
2528 for ( i = 0, len = items.length; i < len; i++ ) {
2529 item = items[ i ];
2530 index = this.items.indexOf( item );
2531 if ( index !== -1 ) {
2532 item.setElementGroup( null );
2533 item.$element.detach();
2534 }
2535 }
2536
2537 // Mixin method
2538 OO.EmitterList.prototype.removeItems.call( this, items );
2539
2540 this.emit( 'change', this.getItems() );
2541 return this;
2542 };
2543
2544 /**
2545 * Clear all items from the group.
2546 *
2547 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2548 * To remove only a subset of items from a group, use the #removeItems method.
2549 *
2550 * @chainable
2551 */
2552 OO.ui.mixin.GroupElement.prototype.clearItems = function () {
2553 var i, len;
2554
2555 // Remove all item elements
2556 for ( i = 0, len = this.items.length; i < len; i++ ) {
2557 this.items[ i ].setElementGroup( null );
2558 this.items[ i ].$element.detach();
2559 }
2560
2561 // Mixin method
2562 OO.EmitterList.prototype.clearItems.call( this );
2563
2564 this.emit( 'change', this.getItems() );
2565 return this;
2566 };
2567
2568 /**
2569 * IconElement is often mixed into other classes to generate an icon.
2570 * Icons are graphics, about the size of normal text. They are used to aid the user
2571 * in locating a control or to convey information in a space-efficient way. See the
2572 * [OOUI documentation on MediaWiki] [1] for a list of icons
2573 * included in the library.
2574 *
2575 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
2576 *
2577 * @abstract
2578 * @class
2579 *
2580 * @constructor
2581 * @param {Object} [config] Configuration options
2582 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2583 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2584 * the icon element be set to an existing icon instead of the one generated by this class, set a
2585 * value using a jQuery selection. For example:
2586 *
2587 * // Use a <div> tag instead of a <span>
2588 * $icon: $("<div>")
2589 * // Use an existing icon element instead of the one generated by the class
2590 * $icon: this.$element
2591 * // Use an icon element from a child widget
2592 * $icon: this.childwidget.$element
2593 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
2594 * symbolic names. A map is used for i18n purposes and contains a `default` icon
2595 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
2596 * by the user's language.
2597 *
2598 * Example of an i18n map:
2599 *
2600 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2601 * See the [OOUI documentation on MediaWiki] [2] for a list of icons included in the library.
2602 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
2603 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
2604 * text. The icon title is displayed when users move the mouse over the icon.
2605 */
2606 OO.ui.mixin.IconElement = function OoUiMixinIconElement( config ) {
2607 // Configuration initialization
2608 config = config || {};
2609
2610 // Properties
2611 this.$icon = null;
2612 this.icon = null;
2613 this.iconTitle = null;
2614
2615 // Initialization
2616 this.setIcon( config.icon || this.constructor.static.icon );
2617 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
2618 this.setIconElement( config.$icon || $( '<span>' ) );
2619 };
2620
2621 /* Setup */
2622
2623 OO.initClass( OO.ui.mixin.IconElement );
2624
2625 /* Static Properties */
2626
2627 /**
2628 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
2629 * for i18n purposes and contains a `default` icon name and additional names keyed by
2630 * language code. The `default` name is used when no icon is keyed by the user's language.
2631 *
2632 * Example of an i18n map:
2633 *
2634 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2635 *
2636 * Note: the static property will be overridden if the #icon configuration is used.
2637 *
2638 * @static
2639 * @inheritable
2640 * @property {Object|string}
2641 */
2642 OO.ui.mixin.IconElement.static.icon = null;
2643
2644 /**
2645 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2646 * function that returns title text, or `null` for no title.
2647 *
2648 * The static property will be overridden if the #iconTitle configuration is used.
2649 *
2650 * @static
2651 * @inheritable
2652 * @property {string|Function|null}
2653 */
2654 OO.ui.mixin.IconElement.static.iconTitle = null;
2655
2656 /* Methods */
2657
2658 /**
2659 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2660 * applies to the specified icon element instead of the one created by the class. If an icon
2661 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2662 * and mixin methods will no longer affect the element.
2663 *
2664 * @param {jQuery} $icon Element to use as icon
2665 */
2666 OO.ui.mixin.IconElement.prototype.setIconElement = function ( $icon ) {
2667 if ( this.$icon ) {
2668 this.$icon
2669 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
2670 .removeAttr( 'title' );
2671 }
2672
2673 this.$icon = $icon
2674 .addClass( 'oo-ui-iconElement-icon' )
2675 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
2676 if ( this.iconTitle !== null ) {
2677 this.$icon.attr( 'title', this.iconTitle );
2678 }
2679
2680 this.updateThemeClasses();
2681 };
2682
2683 /**
2684 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
2685 * The icon parameter can also be set to a map of icon names. See the #icon config setting
2686 * for an example.
2687 *
2688 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
2689 * by language code, or `null` to remove the icon.
2690 * @chainable
2691 */
2692 OO.ui.mixin.IconElement.prototype.setIcon = function ( icon ) {
2693 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
2694 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
2695
2696 if ( this.icon !== icon ) {
2697 if ( this.$icon ) {
2698 if ( this.icon !== null ) {
2699 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
2700 }
2701 if ( icon !== null ) {
2702 this.$icon.addClass( 'oo-ui-icon-' + icon );
2703 }
2704 }
2705 this.icon = icon;
2706 }
2707
2708 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
2709 this.updateThemeClasses();
2710
2711 return this;
2712 };
2713
2714 /**
2715 * Set the icon title. Use `null` to remove the title.
2716 *
2717 * @param {string|Function|null} iconTitle A text string used as the icon title,
2718 * a function that returns title text, or `null` for no title.
2719 * @chainable
2720 */
2721 OO.ui.mixin.IconElement.prototype.setIconTitle = function ( iconTitle ) {
2722 iconTitle =
2723 ( typeof iconTitle === 'function' || ( typeof iconTitle === 'string' && iconTitle.length ) ) ?
2724 OO.ui.resolveMsg( iconTitle ) : null;
2725
2726 if ( this.iconTitle !== iconTitle ) {
2727 this.iconTitle = iconTitle;
2728 if ( this.$icon ) {
2729 if ( this.iconTitle !== null ) {
2730 this.$icon.attr( 'title', iconTitle );
2731 } else {
2732 this.$icon.removeAttr( 'title' );
2733 }
2734 }
2735 }
2736
2737 return this;
2738 };
2739
2740 /**
2741 * Get the symbolic name of the icon.
2742 *
2743 * @return {string} Icon name
2744 */
2745 OO.ui.mixin.IconElement.prototype.getIcon = function () {
2746 return this.icon;
2747 };
2748
2749 /**
2750 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
2751 *
2752 * @return {string} Icon title text
2753 */
2754 OO.ui.mixin.IconElement.prototype.getIconTitle = function () {
2755 return this.iconTitle;
2756 };
2757
2758 /**
2759 * IndicatorElement is often mixed into other classes to generate an indicator.
2760 * Indicators are small graphics that are generally used in two ways:
2761 *
2762 * - To draw attention to the status of an item. For example, an indicator might be
2763 * used to show that an item in a list has errors that need to be resolved.
2764 * - To clarify the function of a control that acts in an exceptional way (a button
2765 * that opens a menu instead of performing an action directly, for example).
2766 *
2767 * For a list of indicators included in the library, please see the
2768 * [OOUI documentation on MediaWiki] [1].
2769 *
2770 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2771 *
2772 * @abstract
2773 * @class
2774 *
2775 * @constructor
2776 * @param {Object} [config] Configuration options
2777 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
2778 * configuration is omitted, the indicator element will use a generated `<span>`.
2779 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
2780 * See the [OOUI documentation on MediaWiki][2] for a list of indicators included
2781 * in the library.
2782 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2783 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
2784 * or a function that returns title text. The indicator title is displayed when users move
2785 * the mouse over the indicator.
2786 */
2787 OO.ui.mixin.IndicatorElement = function OoUiMixinIndicatorElement( config ) {
2788 // Configuration initialization
2789 config = config || {};
2790
2791 // Properties
2792 this.$indicator = null;
2793 this.indicator = null;
2794 this.indicatorTitle = null;
2795
2796 // Initialization
2797 this.setIndicator( config.indicator || this.constructor.static.indicator );
2798 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
2799 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
2800 };
2801
2802 /* Setup */
2803
2804 OO.initClass( OO.ui.mixin.IndicatorElement );
2805
2806 /* Static Properties */
2807
2808 /**
2809 * Symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
2810 * The static property will be overridden if the #indicator configuration is used.
2811 *
2812 * @static
2813 * @inheritable
2814 * @property {string|null}
2815 */
2816 OO.ui.mixin.IndicatorElement.static.indicator = null;
2817
2818 /**
2819 * A text string used as the indicator title, a function that returns title text, or `null`
2820 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
2821 *
2822 * @static
2823 * @inheritable
2824 * @property {string|Function|null}
2825 */
2826 OO.ui.mixin.IndicatorElement.static.indicatorTitle = null;
2827
2828 /* Methods */
2829
2830 /**
2831 * Set the indicator element.
2832 *
2833 * If an element is already set, it will be cleaned up before setting up the new element.
2834 *
2835 * @param {jQuery} $indicator Element to use as indicator
2836 */
2837 OO.ui.mixin.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
2838 if ( this.$indicator ) {
2839 this.$indicator
2840 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
2841 .removeAttr( 'title' );
2842 }
2843
2844 this.$indicator = $indicator
2845 .addClass( 'oo-ui-indicatorElement-indicator' )
2846 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
2847 if ( this.indicatorTitle !== null ) {
2848 this.$indicator.attr( 'title', this.indicatorTitle );
2849 }
2850
2851 this.updateThemeClasses();
2852 };
2853
2854 /**
2855 * Set the indicator by its symbolic name: ‘clear’, ‘down’, ‘required’, ‘search’, ‘up’. Use `null` to remove the indicator.
2856 *
2857 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
2858 * @chainable
2859 */
2860 OO.ui.mixin.IndicatorElement.prototype.setIndicator = function ( indicator ) {
2861 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
2862
2863 if ( this.indicator !== indicator ) {
2864 if ( this.$indicator ) {
2865 if ( this.indicator !== null ) {
2866 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
2867 }
2868 if ( indicator !== null ) {
2869 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
2870 }
2871 }
2872 this.indicator = indicator;
2873 }
2874
2875 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
2876 this.updateThemeClasses();
2877
2878 return this;
2879 };
2880
2881 /**
2882 * Set the indicator title.
2883 *
2884 * The title is displayed when a user moves the mouse over the indicator.
2885 *
2886 * @param {string|Function|null} indicatorTitle Indicator title text, a function that returns text, or
2887 * `null` for no indicator title
2888 * @chainable
2889 */
2890 OO.ui.mixin.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
2891 indicatorTitle =
2892 ( typeof indicatorTitle === 'function' || ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ) ?
2893 OO.ui.resolveMsg( indicatorTitle ) : null;
2894
2895 if ( this.indicatorTitle !== indicatorTitle ) {
2896 this.indicatorTitle = indicatorTitle;
2897 if ( this.$indicator ) {
2898 if ( this.indicatorTitle !== null ) {
2899 this.$indicator.attr( 'title', indicatorTitle );
2900 } else {
2901 this.$indicator.removeAttr( 'title' );
2902 }
2903 }
2904 }
2905
2906 return this;
2907 };
2908
2909 /**
2910 * Get the symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
2911 *
2912 * @return {string} Symbolic name of indicator
2913 */
2914 OO.ui.mixin.IndicatorElement.prototype.getIndicator = function () {
2915 return this.indicator;
2916 };
2917
2918 /**
2919 * Get the indicator title.
2920 *
2921 * The title is displayed when a user moves the mouse over the indicator.
2922 *
2923 * @return {string} Indicator title text
2924 */
2925 OO.ui.mixin.IndicatorElement.prototype.getIndicatorTitle = function () {
2926 return this.indicatorTitle;
2927 };
2928
2929 /**
2930 * LabelElement is often mixed into other classes to generate a label, which
2931 * helps identify the function of an interface element.
2932 * See the [OOUI documentation on MediaWiki] [1] for more information.
2933 *
2934 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
2935 *
2936 * @abstract
2937 * @class
2938 *
2939 * @constructor
2940 * @param {Object} [config] Configuration options
2941 * @cfg {jQuery} [$label] The label element created by the class. If this
2942 * configuration is omitted, the label element will use a generated `<span>`.
2943 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
2944 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
2945 * in the future. See the [OOUI documentation on MediaWiki] [2] for examples.
2946 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
2947 */
2948 OO.ui.mixin.LabelElement = function OoUiMixinLabelElement( config ) {
2949 // Configuration initialization
2950 config = config || {};
2951
2952 // Properties
2953 this.$label = null;
2954 this.label = null;
2955
2956 // Initialization
2957 this.setLabel( config.label || this.constructor.static.label );
2958 this.setLabelElement( config.$label || $( '<span>' ) );
2959 };
2960
2961 /* Setup */
2962
2963 OO.initClass( OO.ui.mixin.LabelElement );
2964
2965 /* Events */
2966
2967 /**
2968 * @event labelChange
2969 * @param {string} value
2970 */
2971
2972 /* Static Properties */
2973
2974 /**
2975 * The label text. The label can be specified as a plaintext string, a function that will
2976 * produce a string in the future, or `null` for no label. The static value will
2977 * be overridden if a label is specified with the #label config option.
2978 *
2979 * @static
2980 * @inheritable
2981 * @property {string|Function|null}
2982 */
2983 OO.ui.mixin.LabelElement.static.label = null;
2984
2985 /* Static methods */
2986
2987 /**
2988 * Highlight the first occurrence of the query in the given text
2989 *
2990 * @param {string} text Text
2991 * @param {string} query Query to find
2992 * @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
2993 * @return {jQuery} Text with the first match of the query
2994 * sub-string wrapped in highlighted span
2995 */
2996 OO.ui.mixin.LabelElement.static.highlightQuery = function ( text, query, compare ) {
2997 var i, tLen, qLen,
2998 offset = -1,
2999 $result = $( '<span>' );
3000
3001 if ( compare ) {
3002 tLen = text.length;
3003 qLen = query.length;
3004 for ( i = 0; offset === -1 && i <= tLen - qLen; i++ ) {
3005 if ( compare( query, text.slice( i, i + qLen ) ) === 0 ) {
3006 offset = i;
3007 }
3008 }
3009 } else {
3010 offset = text.toLowerCase().indexOf( query.toLowerCase() );
3011 }
3012
3013 if ( !query.length || offset === -1 ) {
3014 $result.text( text );
3015 } else {
3016 $result.append(
3017 document.createTextNode( text.slice( 0, offset ) ),
3018 $( '<span>' )
3019 .addClass( 'oo-ui-labelElement-label-highlight' )
3020 .text( text.slice( offset, offset + query.length ) ),
3021 document.createTextNode( text.slice( offset + query.length ) )
3022 );
3023 }
3024 return $result.contents();
3025 };
3026
3027 /* Methods */
3028
3029 /**
3030 * Set the label element.
3031 *
3032 * If an element is already set, it will be cleaned up before setting up the new element.
3033 *
3034 * @param {jQuery} $label Element to use as label
3035 */
3036 OO.ui.mixin.LabelElement.prototype.setLabelElement = function ( $label ) {
3037 if ( this.$label ) {
3038 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
3039 }
3040
3041 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
3042 this.setLabelContent( this.label );
3043 };
3044
3045 /**
3046 * Set the label.
3047 *
3048 * An empty string will result in the label being hidden. A string containing only whitespace will
3049 * be converted to a single `&nbsp;`.
3050 *
3051 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
3052 * text; or null for no label
3053 * @chainable
3054 */
3055 OO.ui.mixin.LabelElement.prototype.setLabel = function ( label ) {
3056 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
3057 label = ( ( typeof label === 'string' || label instanceof jQuery ) && label.length ) || ( label instanceof OO.ui.HtmlSnippet && label.toString().length ) ? label : null;
3058
3059 if ( this.label !== label ) {
3060 if ( this.$label ) {
3061 this.setLabelContent( label );
3062 }
3063 this.label = label;
3064 this.emit( 'labelChange' );
3065 }
3066
3067 this.$element.toggleClass( 'oo-ui-labelElement', !!this.label );
3068
3069 return this;
3070 };
3071
3072 /**
3073 * Set the label as plain text with a highlighted query
3074 *
3075 * @param {string} text Text label to set
3076 * @param {string} query Substring of text to highlight
3077 * @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
3078 * @chainable
3079 */
3080 OO.ui.mixin.LabelElement.prototype.setHighlightedQuery = function ( text, query, compare ) {
3081 return this.setLabel( this.constructor.static.highlightQuery( text, query, compare ) );
3082 };
3083
3084 /**
3085 * Get the label.
3086 *
3087 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
3088 * text; or null for no label
3089 */
3090 OO.ui.mixin.LabelElement.prototype.getLabel = function () {
3091 return this.label;
3092 };
3093
3094 /**
3095 * Set the content of the label.
3096 *
3097 * Do not call this method until after the label element has been set by #setLabelElement.
3098 *
3099 * @private
3100 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
3101 * text; or null for no label
3102 */
3103 OO.ui.mixin.LabelElement.prototype.setLabelContent = function ( label ) {
3104 if ( typeof label === 'string' ) {
3105 if ( label.match( /^\s*$/ ) ) {
3106 // Convert whitespace only string to a single non-breaking space
3107 this.$label.html( '&nbsp;' );
3108 } else {
3109 this.$label.text( label );
3110 }
3111 } else if ( label instanceof OO.ui.HtmlSnippet ) {
3112 this.$label.html( label.toString() );
3113 } else if ( label instanceof jQuery ) {
3114 this.$label.empty().append( label );
3115 } else {
3116 this.$label.empty();
3117 }
3118 };
3119
3120 /**
3121 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
3122 * additional functionality to an element created by another class. The class provides
3123 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
3124 * which are used to customize the look and feel of a widget to better describe its
3125 * importance and functionality.
3126 *
3127 * The library currently contains the following styling flags for general use:
3128 *
3129 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
3130 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
3131 *
3132 * The flags affect the appearance of the buttons:
3133 *
3134 * @example
3135 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
3136 * var button1 = new OO.ui.ButtonWidget( {
3137 * label: 'Progressive',
3138 * flags: 'progressive'
3139 * } );
3140 * var button2 = new OO.ui.ButtonWidget( {
3141 * label: 'Destructive',
3142 * flags: 'destructive'
3143 * } );
3144 * $( 'body' ).append( button1.$element, button2.$element );
3145 *
3146 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
3147 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
3148 *
3149 * [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
3150 *
3151 * @abstract
3152 * @class
3153 *
3154 * @constructor
3155 * @param {Object} [config] Configuration options
3156 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'progressive' or 'primary') to apply.
3157 * Please see the [OOUI documentation on MediaWiki] [2] for more information about available flags.
3158 * [2]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
3159 * @cfg {jQuery} [$flagged] The flagged element. By default,
3160 * the flagged functionality is applied to the element created by the class ($element).
3161 * If a different element is specified, the flagged functionality will be applied to it instead.
3162 */
3163 OO.ui.mixin.FlaggedElement = function OoUiMixinFlaggedElement( config ) {
3164 // Configuration initialization
3165 config = config || {};
3166
3167 // Properties
3168 this.flags = {};
3169 this.$flagged = null;
3170
3171 // Initialization
3172 this.setFlags( config.flags );
3173 this.setFlaggedElement( config.$flagged || this.$element );
3174 };
3175
3176 /* Events */
3177
3178 /**
3179 * @event flag
3180 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
3181 * parameter contains the name of each modified flag and indicates whether it was
3182 * added or removed.
3183 *
3184 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
3185 * that the flag was added, `false` that the flag was removed.
3186 */
3187
3188 /* Methods */
3189
3190 /**
3191 * Set the flagged element.
3192 *
3193 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
3194 * If an element is already set, the method will remove the mixin’s effect on that element.
3195 *
3196 * @param {jQuery} $flagged Element that should be flagged
3197 */
3198 OO.ui.mixin.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
3199 var classNames = Object.keys( this.flags ).map( function ( flag ) {
3200 return 'oo-ui-flaggedElement-' + flag;
3201 } ).join( ' ' );
3202
3203 if ( this.$flagged ) {
3204 this.$flagged.removeClass( classNames );
3205 }
3206
3207 this.$flagged = $flagged.addClass( classNames );
3208 };
3209
3210 /**
3211 * Check if the specified flag is set.
3212 *
3213 * @param {string} flag Name of flag
3214 * @return {boolean} The flag is set
3215 */
3216 OO.ui.mixin.FlaggedElement.prototype.hasFlag = function ( flag ) {
3217 // This may be called before the constructor, thus before this.flags is set
3218 return this.flags && ( flag in this.flags );
3219 };
3220
3221 /**
3222 * Get the names of all flags set.
3223 *
3224 * @return {string[]} Flag names
3225 */
3226 OO.ui.mixin.FlaggedElement.prototype.getFlags = function () {
3227 // This may be called before the constructor, thus before this.flags is set
3228 return Object.keys( this.flags || {} );
3229 };
3230
3231 /**
3232 * Clear all flags.
3233 *
3234 * @chainable
3235 * @fires flag
3236 */
3237 OO.ui.mixin.FlaggedElement.prototype.clearFlags = function () {
3238 var flag, className,
3239 changes = {},
3240 remove = [],
3241 classPrefix = 'oo-ui-flaggedElement-';
3242
3243 for ( flag in this.flags ) {
3244 className = classPrefix + flag;
3245 changes[ flag ] = false;
3246 delete this.flags[ flag ];
3247 remove.push( className );
3248 }
3249
3250 if ( this.$flagged ) {
3251 this.$flagged.removeClass( remove.join( ' ' ) );
3252 }
3253
3254 this.updateThemeClasses();
3255 this.emit( 'flag', changes );
3256
3257 return this;
3258 };
3259
3260 /**
3261 * Add one or more flags.
3262 *
3263 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
3264 * or an object keyed by flag name with a boolean value that indicates whether the flag should
3265 * be added (`true`) or removed (`false`).
3266 * @chainable
3267 * @fires flag
3268 */
3269 OO.ui.mixin.FlaggedElement.prototype.setFlags = function ( flags ) {
3270 var i, len, flag, className,
3271 changes = {},
3272 add = [],
3273 remove = [],
3274 classPrefix = 'oo-ui-flaggedElement-';
3275
3276 if ( typeof flags === 'string' ) {
3277 className = classPrefix + flags;
3278 // Set
3279 if ( !this.flags[ flags ] ) {
3280 this.flags[ flags ] = true;
3281 add.push( className );
3282 }
3283 } else if ( Array.isArray( flags ) ) {
3284 for ( i = 0, len = flags.length; i < len; i++ ) {
3285 flag = flags[ i ];
3286 className = classPrefix + flag;
3287 // Set
3288 if ( !this.flags[ flag ] ) {
3289 changes[ flag ] = true;
3290 this.flags[ flag ] = true;
3291 add.push( className );
3292 }
3293 }
3294 } else if ( OO.isPlainObject( flags ) ) {
3295 for ( flag in flags ) {
3296 className = classPrefix + flag;
3297 if ( flags[ flag ] ) {
3298 // Set
3299 if ( !this.flags[ flag ] ) {
3300 changes[ flag ] = true;
3301 this.flags[ flag ] = true;
3302 add.push( className );
3303 }
3304 } else {
3305 // Remove
3306 if ( this.flags[ flag ] ) {
3307 changes[ flag ] = false;
3308 delete this.flags[ flag ];
3309 remove.push( className );
3310 }
3311 }
3312 }
3313 }
3314
3315 if ( this.$flagged ) {
3316 this.$flagged
3317 .addClass( add.join( ' ' ) )
3318 .removeClass( remove.join( ' ' ) );
3319 }
3320
3321 this.updateThemeClasses();
3322 this.emit( 'flag', changes );
3323
3324 return this;
3325 };
3326
3327 /**
3328 * TitledElement is mixed into other classes to provide a `title` attribute.
3329 * Titles are rendered by the browser and are made visible when the user moves
3330 * the mouse over the element. Titles are not visible on touch devices.
3331 *
3332 * @example
3333 * // TitledElement provides a 'title' attribute to the
3334 * // ButtonWidget class
3335 * var button = new OO.ui.ButtonWidget( {
3336 * label: 'Button with Title',
3337 * title: 'I am a button'
3338 * } );
3339 * $( 'body' ).append( button.$element );
3340 *
3341 * @abstract
3342 * @class
3343 *
3344 * @constructor
3345 * @param {Object} [config] Configuration options
3346 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
3347 * If this config is omitted, the title functionality is applied to $element, the
3348 * element created by the class.
3349 * @cfg {string|Function} [title] The title text or a function that returns text. If
3350 * this config is omitted, the value of the {@link #static-title static title} property is used.
3351 */
3352 OO.ui.mixin.TitledElement = function OoUiMixinTitledElement( config ) {
3353 // Configuration initialization
3354 config = config || {};
3355
3356 // Properties
3357 this.$titled = null;
3358 this.title = null;
3359
3360 // Initialization
3361 this.setTitle( config.title !== undefined ? config.title : this.constructor.static.title );
3362 this.setTitledElement( config.$titled || this.$element );
3363 };
3364
3365 /* Setup */
3366
3367 OO.initClass( OO.ui.mixin.TitledElement );
3368
3369 /* Static Properties */
3370
3371 /**
3372 * The title text, a function that returns text, or `null` for no title. The value of the static property
3373 * is overridden if the #title config option is used.
3374 *
3375 * @static
3376 * @inheritable
3377 * @property {string|Function|null}
3378 */
3379 OO.ui.mixin.TitledElement.static.title = null;
3380
3381 /* Methods */
3382
3383 /**
3384 * Set the titled element.
3385 *
3386 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
3387 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
3388 *
3389 * @param {jQuery} $titled Element that should use the 'titled' functionality
3390 */
3391 OO.ui.mixin.TitledElement.prototype.setTitledElement = function ( $titled ) {
3392 if ( this.$titled ) {
3393 this.$titled.removeAttr( 'title' );
3394 }
3395
3396 this.$titled = $titled;
3397 if ( this.title ) {
3398 this.updateTitle();
3399 }
3400 };
3401
3402 /**
3403 * Set title.
3404 *
3405 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
3406 * @chainable
3407 */
3408 OO.ui.mixin.TitledElement.prototype.setTitle = function ( title ) {
3409 title = typeof title === 'function' ? OO.ui.resolveMsg( title ) : title;
3410 title = ( typeof title === 'string' && title.length ) ? title : null;
3411
3412 if ( this.title !== title ) {
3413 this.title = title;
3414 this.updateTitle();
3415 }
3416
3417 return this;
3418 };
3419
3420 /**
3421 * Update the title attribute, in case of changes to title or accessKey.
3422 *
3423 * @protected
3424 * @chainable
3425 */
3426 OO.ui.mixin.TitledElement.prototype.updateTitle = function () {
3427 var title = this.getTitle();
3428 if ( this.$titled ) {
3429 if ( title !== null ) {
3430 // Only if this is an AccessKeyedElement
3431 if ( this.formatTitleWithAccessKey ) {
3432 title = this.formatTitleWithAccessKey( title );
3433 }
3434 this.$titled.attr( 'title', title );
3435 } else {
3436 this.$titled.removeAttr( 'title' );
3437 }
3438 }
3439 return this;
3440 };
3441
3442 /**
3443 * Get title.
3444 *
3445 * @return {string} Title string
3446 */
3447 OO.ui.mixin.TitledElement.prototype.getTitle = function () {
3448 return this.title;
3449 };
3450
3451 /**
3452 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
3453 * Accesskeys allow an user to go to a specific element by using
3454 * a shortcut combination of a browser specific keys + the key
3455 * set to the field.
3456 *
3457 * @example
3458 * // AccessKeyedElement provides an 'accesskey' attribute to the
3459 * // ButtonWidget class
3460 * var button = new OO.ui.ButtonWidget( {
3461 * label: 'Button with Accesskey',
3462 * accessKey: 'k'
3463 * } );
3464 * $( 'body' ).append( button.$element );
3465 *
3466 * @abstract
3467 * @class
3468 *
3469 * @constructor
3470 * @param {Object} [config] Configuration options
3471 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3472 * If this config is omitted, the accesskey functionality is applied to $element, the
3473 * element created by the class.
3474 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3475 * this config is omitted, no accesskey will be added.
3476 */
3477 OO.ui.mixin.AccessKeyedElement = function OoUiMixinAccessKeyedElement( config ) {
3478 // Configuration initialization
3479 config = config || {};
3480
3481 // Properties
3482 this.$accessKeyed = null;
3483 this.accessKey = null;
3484
3485 // Initialization
3486 this.setAccessKey( config.accessKey || null );
3487 this.setAccessKeyedElement( config.$accessKeyed || this.$element );
3488
3489 // If this is also a TitledElement and it initialized before we did, we may have
3490 // to update the title with the access key
3491 if ( this.updateTitle ) {
3492 this.updateTitle();
3493 }
3494 };
3495
3496 /* Setup */
3497
3498 OO.initClass( OO.ui.mixin.AccessKeyedElement );
3499
3500 /* Static Properties */
3501
3502 /**
3503 * The access key, a function that returns a key, or `null` for no accesskey.
3504 *
3505 * @static
3506 * @inheritable
3507 * @property {string|Function|null}
3508 */
3509 OO.ui.mixin.AccessKeyedElement.static.accessKey = null;
3510
3511 /* Methods */
3512
3513 /**
3514 * Set the accesskeyed element.
3515 *
3516 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
3517 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
3518 *
3519 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
3520 */
3521 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKeyedElement = function ( $accessKeyed ) {
3522 if ( this.$accessKeyed ) {
3523 this.$accessKeyed.removeAttr( 'accesskey' );
3524 }
3525
3526 this.$accessKeyed = $accessKeyed;
3527 if ( this.accessKey ) {
3528 this.$accessKeyed.attr( 'accesskey', this.accessKey );
3529 }
3530 };
3531
3532 /**
3533 * Set accesskey.
3534 *
3535 * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no accesskey
3536 * @chainable
3537 */
3538 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKey = function ( accessKey ) {
3539 accessKey = typeof accessKey === 'string' ? OO.ui.resolveMsg( accessKey ) : null;
3540
3541 if ( this.accessKey !== accessKey ) {
3542 if ( this.$accessKeyed ) {
3543 if ( accessKey !== null ) {
3544 this.$accessKeyed.attr( 'accesskey', accessKey );
3545 } else {
3546 this.$accessKeyed.removeAttr( 'accesskey' );
3547 }
3548 }
3549 this.accessKey = accessKey;
3550
3551 // Only if this is a TitledElement
3552 if ( this.updateTitle ) {
3553 this.updateTitle();
3554 }
3555 }
3556
3557 return this;
3558 };
3559
3560 /**
3561 * Get accesskey.
3562 *
3563 * @return {string} accessKey string
3564 */
3565 OO.ui.mixin.AccessKeyedElement.prototype.getAccessKey = function () {
3566 return this.accessKey;
3567 };
3568
3569 /**
3570 * Add information about the access key to the element's tooltip label.
3571 * (This is only public for hacky usage in FieldLayout.)
3572 *
3573 * @param {string} title Tooltip label for `title` attribute
3574 * @return {string}
3575 */
3576 OO.ui.mixin.AccessKeyedElement.prototype.formatTitleWithAccessKey = function ( title ) {
3577 var accessKey;
3578
3579 if ( !this.$accessKeyed ) {
3580 // Not initialized yet; the constructor will call updateTitle() which will rerun this function
3581 return title;
3582 }
3583 // Use jquery.accessKeyLabel if available to show modifiers, otherwise just display the single key
3584 if ( $.fn.updateTooltipAccessKeys && $.fn.updateTooltipAccessKeys.getAccessKeyLabel ) {
3585 accessKey = $.fn.updateTooltipAccessKeys.getAccessKeyLabel( this.$accessKeyed[ 0 ] );
3586 } else {
3587 accessKey = this.getAccessKey();
3588 }
3589 if ( accessKey ) {
3590 title += ' [' + accessKey + ']';
3591 }
3592 return title;
3593 };
3594
3595 /**
3596 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3597 * feels, and functionality can be customized via the class’s configuration options
3598 * and methods. Please see the [OOUI documentation on MediaWiki] [1] for more information
3599 * and examples.
3600 *
3601 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches
3602 *
3603 * @example
3604 * // A button widget
3605 * var button = new OO.ui.ButtonWidget( {
3606 * label: 'Button with Icon',
3607 * icon: 'trash',
3608 * iconTitle: 'Remove'
3609 * } );
3610 * $( 'body' ).append( button.$element );
3611 *
3612 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3613 *
3614 * @class
3615 * @extends OO.ui.Widget
3616 * @mixins OO.ui.mixin.ButtonElement
3617 * @mixins OO.ui.mixin.IconElement
3618 * @mixins OO.ui.mixin.IndicatorElement
3619 * @mixins OO.ui.mixin.LabelElement
3620 * @mixins OO.ui.mixin.TitledElement
3621 * @mixins OO.ui.mixin.FlaggedElement
3622 * @mixins OO.ui.mixin.TabIndexedElement
3623 * @mixins OO.ui.mixin.AccessKeyedElement
3624 *
3625 * @constructor
3626 * @param {Object} [config] Configuration options
3627 * @cfg {boolean} [active=false] Whether button should be shown as active
3628 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3629 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3630 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3631 */
3632 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
3633 // Configuration initialization
3634 config = config || {};
3635
3636 // Parent constructor
3637 OO.ui.ButtonWidget.parent.call( this, config );
3638
3639 // Mixin constructors
3640 OO.ui.mixin.ButtonElement.call( this, config );
3641 OO.ui.mixin.IconElement.call( this, config );
3642 OO.ui.mixin.IndicatorElement.call( this, config );
3643 OO.ui.mixin.LabelElement.call( this, config );
3644 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
3645 OO.ui.mixin.FlaggedElement.call( this, config );
3646 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
3647 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$button } ) );
3648
3649 // Properties
3650 this.href = null;
3651 this.target = null;
3652 this.noFollow = false;
3653
3654 // Events
3655 this.connect( this, { disable: 'onDisable' } );
3656
3657 // Initialization
3658 this.$button.append( this.$icon, this.$label, this.$indicator );
3659 this.$element
3660 .addClass( 'oo-ui-buttonWidget' )
3661 .append( this.$button );
3662 this.setActive( config.active );
3663 this.setHref( config.href );
3664 this.setTarget( config.target );
3665 this.setNoFollow( config.noFollow );
3666 };
3667
3668 /* Setup */
3669
3670 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
3671 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.ButtonElement );
3672 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IconElement );
3673 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IndicatorElement );
3674 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.LabelElement );
3675 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TitledElement );
3676 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.FlaggedElement );
3677 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TabIndexedElement );
3678 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.AccessKeyedElement );
3679
3680 /* Static Properties */
3681
3682 /**
3683 * @static
3684 * @inheritdoc
3685 */
3686 OO.ui.ButtonWidget.static.cancelButtonMouseDownEvents = false;
3687
3688 /**
3689 * @static
3690 * @inheritdoc
3691 */
3692 OO.ui.ButtonWidget.static.tagName = 'span';
3693
3694 /* Methods */
3695
3696 /**
3697 * Get hyperlink location.
3698 *
3699 * @return {string} Hyperlink location
3700 */
3701 OO.ui.ButtonWidget.prototype.getHref = function () {
3702 return this.href;
3703 };
3704
3705 /**
3706 * Get hyperlink target.
3707 *
3708 * @return {string} Hyperlink target
3709 */
3710 OO.ui.ButtonWidget.prototype.getTarget = function () {
3711 return this.target;
3712 };
3713
3714 /**
3715 * Get search engine traversal hint.
3716 *
3717 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3718 */
3719 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
3720 return this.noFollow;
3721 };
3722
3723 /**
3724 * Set hyperlink location.
3725 *
3726 * @param {string|null} href Hyperlink location, null to remove
3727 */
3728 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
3729 href = typeof href === 'string' ? href : null;
3730 if ( href !== null && !OO.ui.isSafeUrl( href ) ) {
3731 href = './' + href;
3732 }
3733
3734 if ( href !== this.href ) {
3735 this.href = href;
3736 this.updateHref();
3737 }
3738
3739 return this;
3740 };
3741
3742 /**
3743 * Update the `href` attribute, in case of changes to href or
3744 * disabled state.
3745 *
3746 * @private
3747 * @chainable
3748 */
3749 OO.ui.ButtonWidget.prototype.updateHref = function () {
3750 if ( this.href !== null && !this.isDisabled() ) {
3751 this.$button.attr( 'href', this.href );
3752 } else {
3753 this.$button.removeAttr( 'href' );
3754 }
3755
3756 return this;
3757 };
3758
3759 /**
3760 * Handle disable events.
3761 *
3762 * @private
3763 * @param {boolean} disabled Element is disabled
3764 */
3765 OO.ui.ButtonWidget.prototype.onDisable = function () {
3766 this.updateHref();
3767 };
3768
3769 /**
3770 * Set hyperlink target.
3771 *
3772 * @param {string|null} target Hyperlink target, null to remove
3773 */
3774 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
3775 target = typeof target === 'string' ? target : null;
3776
3777 if ( target !== this.target ) {
3778 this.target = target;
3779 if ( target !== null ) {
3780 this.$button.attr( 'target', target );
3781 } else {
3782 this.$button.removeAttr( 'target' );
3783 }
3784 }
3785
3786 return this;
3787 };
3788
3789 /**
3790 * Set search engine traversal hint.
3791 *
3792 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3793 */
3794 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
3795 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
3796
3797 if ( noFollow !== this.noFollow ) {
3798 this.noFollow = noFollow;
3799 if ( noFollow ) {
3800 this.$button.attr( 'rel', 'nofollow' );
3801 } else {
3802 this.$button.removeAttr( 'rel' );
3803 }
3804 }
3805
3806 return this;
3807 };
3808
3809 // Override method visibility hints from ButtonElement
3810 /**
3811 * @method setActive
3812 * @inheritdoc
3813 */
3814 /**
3815 * @method isActive
3816 * @inheritdoc
3817 */
3818
3819 /**
3820 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3821 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3822 * removed, and cleared from the group.
3823 *
3824 * @example
3825 * // Example: A ButtonGroupWidget with two buttons
3826 * var button1 = new OO.ui.PopupButtonWidget( {
3827 * label: 'Select a category',
3828 * icon: 'menu',
3829 * popup: {
3830 * $content: $( '<p>List of categories...</p>' ),
3831 * padded: true,
3832 * align: 'left'
3833 * }
3834 * } );
3835 * var button2 = new OO.ui.ButtonWidget( {
3836 * label: 'Add item'
3837 * });
3838 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
3839 * items: [button1, button2]
3840 * } );
3841 * $( 'body' ).append( buttonGroup.$element );
3842 *
3843 * @class
3844 * @extends OO.ui.Widget
3845 * @mixins OO.ui.mixin.GroupElement
3846 *
3847 * @constructor
3848 * @param {Object} [config] Configuration options
3849 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
3850 */
3851 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
3852 // Configuration initialization
3853 config = config || {};
3854
3855 // Parent constructor
3856 OO.ui.ButtonGroupWidget.parent.call( this, config );
3857
3858 // Mixin constructors
3859 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
3860
3861 // Initialization
3862 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
3863 if ( Array.isArray( config.items ) ) {
3864 this.addItems( config.items );
3865 }
3866 };
3867
3868 /* Setup */
3869
3870 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
3871 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.GroupElement );
3872
3873 /* Static Properties */
3874
3875 /**
3876 * @static
3877 * @inheritdoc
3878 */
3879 OO.ui.ButtonGroupWidget.static.tagName = 'span';
3880
3881 /* Methods */
3882
3883 /**
3884 * Focus the widget
3885 *
3886 * @chainable
3887 */
3888 OO.ui.ButtonGroupWidget.prototype.focus = function () {
3889 if ( !this.isDisabled() ) {
3890 if ( this.items[ 0 ] ) {
3891 this.items[ 0 ].focus();
3892 }
3893 }
3894 return this;
3895 };
3896
3897 /**
3898 * @inheritdoc
3899 */
3900 OO.ui.ButtonGroupWidget.prototype.simulateLabelClick = function () {
3901 this.focus();
3902 };
3903
3904 /**
3905 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
3906 * which creates a label that identifies the icon’s function. See the [OOUI documentation on MediaWiki] [1]
3907 * for a list of icons included in the library.
3908 *
3909 * @example
3910 * // An icon widget with a label
3911 * var myIcon = new OO.ui.IconWidget( {
3912 * icon: 'help',
3913 * iconTitle: 'Help'
3914 * } );
3915 * // Create a label.
3916 * var iconLabel = new OO.ui.LabelWidget( {
3917 * label: 'Help'
3918 * } );
3919 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
3920 *
3921 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
3922 *
3923 * @class
3924 * @extends OO.ui.Widget
3925 * @mixins OO.ui.mixin.IconElement
3926 * @mixins OO.ui.mixin.TitledElement
3927 * @mixins OO.ui.mixin.FlaggedElement
3928 *
3929 * @constructor
3930 * @param {Object} [config] Configuration options
3931 */
3932 OO.ui.IconWidget = function OoUiIconWidget( config ) {
3933 // Configuration initialization
3934 config = config || {};
3935
3936 // Parent constructor
3937 OO.ui.IconWidget.parent.call( this, config );
3938
3939 // Mixin constructors
3940 OO.ui.mixin.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
3941 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
3942 OO.ui.mixin.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) );
3943
3944 // Initialization
3945 this.$element.addClass( 'oo-ui-iconWidget' );
3946 };
3947
3948 /* Setup */
3949
3950 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
3951 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.IconElement );
3952 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.TitledElement );
3953 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.FlaggedElement );
3954
3955 /* Static Properties */
3956
3957 /**
3958 * @static
3959 * @inheritdoc
3960 */
3961 OO.ui.IconWidget.static.tagName = 'span';
3962
3963 /**
3964 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
3965 * attention to the status of an item or to clarify the function within a control. For a list of
3966 * indicators included in the library, please see the [OOUI documentation on MediaWiki][1].
3967 *
3968 * @example
3969 * // Example of an indicator widget
3970 * var indicator1 = new OO.ui.IndicatorWidget( {
3971 * indicator: 'required'
3972 * } );
3973 *
3974 * // Create a fieldset layout to add a label
3975 * var fieldset = new OO.ui.FieldsetLayout();
3976 * fieldset.addItems( [
3977 * new OO.ui.FieldLayout( indicator1, { label: 'A required indicator:' } )
3978 * ] );
3979 * $( 'body' ).append( fieldset.$element );
3980 *
3981 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3982 *
3983 * @class
3984 * @extends OO.ui.Widget
3985 * @mixins OO.ui.mixin.IndicatorElement
3986 * @mixins OO.ui.mixin.TitledElement
3987 *
3988 * @constructor
3989 * @param {Object} [config] Configuration options
3990 */
3991 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
3992 // Configuration initialization
3993 config = config || {};
3994
3995 // Parent constructor
3996 OO.ui.IndicatorWidget.parent.call( this, config );
3997
3998 // Mixin constructors
3999 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
4000 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
4001
4002 // Initialization
4003 this.$element.addClass( 'oo-ui-indicatorWidget' );
4004 };
4005
4006 /* Setup */
4007
4008 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
4009 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.IndicatorElement );
4010 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.TitledElement );
4011
4012 /* Static Properties */
4013
4014 /**
4015 * @static
4016 * @inheritdoc
4017 */
4018 OO.ui.IndicatorWidget.static.tagName = 'span';
4019
4020 /**
4021 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
4022 * be configured with a `label` option that is set to a string, a label node, or a function:
4023 *
4024 * - String: a plaintext string
4025 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
4026 * label that includes a link or special styling, such as a gray color or additional graphical elements.
4027 * - Function: a function that will produce a string in the future. Functions are used
4028 * in cases where the value of the label is not currently defined.
4029 *
4030 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
4031 * will come into focus when the label is clicked.
4032 *
4033 * @example
4034 * // Examples of LabelWidgets
4035 * var label1 = new OO.ui.LabelWidget( {
4036 * label: 'plaintext label'
4037 * } );
4038 * var label2 = new OO.ui.LabelWidget( {
4039 * label: $( '<a href="default.html">jQuery label</a>' )
4040 * } );
4041 * // Create a fieldset layout with fields for each example
4042 * var fieldset = new OO.ui.FieldsetLayout();
4043 * fieldset.addItems( [
4044 * new OO.ui.FieldLayout( label1 ),
4045 * new OO.ui.FieldLayout( label2 )
4046 * ] );
4047 * $( 'body' ).append( fieldset.$element );
4048 *
4049 * @class
4050 * @extends OO.ui.Widget
4051 * @mixins OO.ui.mixin.LabelElement
4052 * @mixins OO.ui.mixin.TitledElement
4053 *
4054 * @constructor
4055 * @param {Object} [config] Configuration options
4056 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
4057 * Clicking the label will focus the specified input field.
4058 */
4059 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
4060 // Configuration initialization
4061 config = config || {};
4062
4063 // Parent constructor
4064 OO.ui.LabelWidget.parent.call( this, config );
4065
4066 // Mixin constructors
4067 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
4068 OO.ui.mixin.TitledElement.call( this, config );
4069
4070 // Properties
4071 this.input = config.input;
4072
4073 // Initialization
4074 if ( this.input ) {
4075 if ( this.input.getInputId() ) {
4076 this.$element.attr( 'for', this.input.getInputId() );
4077 } else {
4078 this.$label.on( 'click', function () {
4079 this.input.simulateLabelClick();
4080 }.bind( this ) );
4081 }
4082 }
4083 this.$element.addClass( 'oo-ui-labelWidget' );
4084 };
4085
4086 /* Setup */
4087
4088 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
4089 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.LabelElement );
4090 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.TitledElement );
4091
4092 /* Static Properties */
4093
4094 /**
4095 * @static
4096 * @inheritdoc
4097 */
4098 OO.ui.LabelWidget.static.tagName = 'label';
4099
4100 /**
4101 * PendingElement is a mixin that is used to create elements that notify users that something is happening
4102 * and that they should wait before proceeding. The pending state is visually represented with a pending
4103 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
4104 * field of a {@link OO.ui.TextInputWidget text input widget}.
4105 *
4106 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
4107 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
4108 * in process dialogs.
4109 *
4110 * @example
4111 * function MessageDialog( config ) {
4112 * MessageDialog.parent.call( this, config );
4113 * }
4114 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
4115 *
4116 * MessageDialog.static.name = 'myMessageDialog';
4117 * MessageDialog.static.actions = [
4118 * { action: 'save', label: 'Done', flags: 'primary' },
4119 * { label: 'Cancel', flags: 'safe' }
4120 * ];
4121 *
4122 * MessageDialog.prototype.initialize = function () {
4123 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
4124 * this.content = new OO.ui.PanelLayout( { padded: true } );
4125 * 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>' );
4126 * this.$body.append( this.content.$element );
4127 * };
4128 * MessageDialog.prototype.getBodyHeight = function () {
4129 * return 100;
4130 * }
4131 * MessageDialog.prototype.getActionProcess = function ( action ) {
4132 * var dialog = this;
4133 * if ( action === 'save' ) {
4134 * dialog.getActions().get({actions: 'save'})[0].pushPending();
4135 * return new OO.ui.Process()
4136 * .next( 1000 )
4137 * .next( function () {
4138 * dialog.getActions().get({actions: 'save'})[0].popPending();
4139 * } );
4140 * }
4141 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
4142 * };
4143 *
4144 * var windowManager = new OO.ui.WindowManager();
4145 * $( 'body' ).append( windowManager.$element );
4146 *
4147 * var dialog = new MessageDialog();
4148 * windowManager.addWindows( [ dialog ] );
4149 * windowManager.openWindow( dialog );
4150 *
4151 * @abstract
4152 * @class
4153 *
4154 * @constructor
4155 * @param {Object} [config] Configuration options
4156 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
4157 */
4158 OO.ui.mixin.PendingElement = function OoUiMixinPendingElement( config ) {
4159 // Configuration initialization
4160 config = config || {};
4161
4162 // Properties
4163 this.pending = 0;
4164 this.$pending = null;
4165
4166 // Initialisation
4167 this.setPendingElement( config.$pending || this.$element );
4168 };
4169
4170 /* Setup */
4171
4172 OO.initClass( OO.ui.mixin.PendingElement );
4173
4174 /* Methods */
4175
4176 /**
4177 * Set the pending element (and clean up any existing one).
4178 *
4179 * @param {jQuery} $pending The element to set to pending.
4180 */
4181 OO.ui.mixin.PendingElement.prototype.setPendingElement = function ( $pending ) {
4182 if ( this.$pending ) {
4183 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
4184 }
4185
4186 this.$pending = $pending;
4187 if ( this.pending > 0 ) {
4188 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
4189 }
4190 };
4191
4192 /**
4193 * Check if an element is pending.
4194 *
4195 * @return {boolean} Element is pending
4196 */
4197 OO.ui.mixin.PendingElement.prototype.isPending = function () {
4198 return !!this.pending;
4199 };
4200
4201 /**
4202 * Increase the pending counter. The pending state will remain active until the counter is zero
4203 * (i.e., the number of calls to #pushPending and #popPending is the same).
4204 *
4205 * @chainable
4206 */
4207 OO.ui.mixin.PendingElement.prototype.pushPending = function () {
4208 if ( this.pending === 0 ) {
4209 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
4210 this.updateThemeClasses();
4211 }
4212 this.pending++;
4213
4214 return this;
4215 };
4216
4217 /**
4218 * Decrease the pending counter. The pending state will remain active until the counter is zero
4219 * (i.e., the number of calls to #pushPending and #popPending is the same).
4220 *
4221 * @chainable
4222 */
4223 OO.ui.mixin.PendingElement.prototype.popPending = function () {
4224 if ( this.pending === 1 ) {
4225 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
4226 this.updateThemeClasses();
4227 }
4228 this.pending = Math.max( 0, this.pending - 1 );
4229
4230 return this;
4231 };
4232
4233 /**
4234 * Element that will stick adjacent to a specified container, even when it is inserted elsewhere
4235 * in the document (for example, in an OO.ui.Window's $overlay).
4236 *
4237 * The elements's position is automatically calculated and maintained when window is resized or the
4238 * page is scrolled. If you reposition the container manually, you have to call #position to make
4239 * sure the element is still placed correctly.
4240 *
4241 * As positioning is only possible when both the element and the container are attached to the DOM
4242 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
4243 * the #toggle method to display a floating popup, for example.
4244 *
4245 * @abstract
4246 * @class
4247 *
4248 * @constructor
4249 * @param {Object} [config] Configuration options
4250 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
4251 * @cfg {jQuery} [$floatableContainer] Node to position adjacent to
4252 * @cfg {string} [verticalPosition='below'] Where to position $floatable vertically:
4253 * 'below': Directly below $floatableContainer, aligning f's top edge with fC's bottom edge
4254 * 'above': Directly above $floatableContainer, aligning f's bottom edge with fC's top edge
4255 * 'top': Align the top edge with $floatableContainer's top edge
4256 * 'bottom': Align the bottom edge with $floatableContainer's bottom edge
4257 * 'center': Vertically align the center with $floatableContainer's center
4258 * @cfg {string} [horizontalPosition='start'] Where to position $floatable horizontally:
4259 * 'before': Directly before $floatableContainer, aligning f's end edge with fC's start edge
4260 * 'after': Directly after $floatableContainer, algining f's start edge with fC's end edge
4261 * 'start': Align the start (left in LTR, right in RTL) edge with $floatableContainer's start edge
4262 * 'end': Align the end (right in LTR, left in RTL) edge with $floatableContainer's end edge
4263 * 'center': Horizontally align the center with $floatableContainer's center
4264 * @cfg {boolean} [hideWhenOutOfView=true] Whether to hide the floatable element if the container
4265 * is out of view
4266 */
4267 OO.ui.mixin.FloatableElement = function OoUiMixinFloatableElement( config ) {
4268 // Configuration initialization
4269 config = config || {};
4270
4271 // Properties
4272 this.$floatable = null;
4273 this.$floatableContainer = null;
4274 this.$floatableWindow = null;
4275 this.$floatableClosestScrollable = null;
4276 this.floatableOutOfView = false;
4277 this.onFloatableScrollHandler = this.position.bind( this );
4278 this.onFloatableWindowResizeHandler = this.position.bind( this );
4279
4280 // Initialization
4281 this.setFloatableContainer( config.$floatableContainer );
4282 this.setFloatableElement( config.$floatable || this.$element );
4283 this.setVerticalPosition( config.verticalPosition || 'below' );
4284 this.setHorizontalPosition( config.horizontalPosition || 'start' );
4285 this.hideWhenOutOfView = config.hideWhenOutOfView === undefined ? true : !!config.hideWhenOutOfView;
4286 };
4287
4288 /* Methods */
4289
4290 /**
4291 * Set floatable element.
4292 *
4293 * If an element is already set, it will be cleaned up before setting up the new element.
4294 *
4295 * @param {jQuery} $floatable Element to make floatable
4296 */
4297 OO.ui.mixin.FloatableElement.prototype.setFloatableElement = function ( $floatable ) {
4298 if ( this.$floatable ) {
4299 this.$floatable.removeClass( 'oo-ui-floatableElement-floatable' );
4300 this.$floatable.css( { left: '', top: '' } );
4301 }
4302
4303 this.$floatable = $floatable.addClass( 'oo-ui-floatableElement-floatable' );
4304 this.position();
4305 };
4306
4307 /**
4308 * Set floatable container.
4309 *
4310 * The element will be positioned relative to the specified container.
4311 *
4312 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
4313 */
4314 OO.ui.mixin.FloatableElement.prototype.setFloatableContainer = function ( $floatableContainer ) {
4315 this.$floatableContainer = $floatableContainer;
4316 if ( this.$floatable ) {
4317 this.position();
4318 }
4319 };
4320
4321 /**
4322 * Change how the element is positioned vertically.
4323 *
4324 * @param {string} position 'below', 'above', 'top', 'bottom' or 'center'
4325 */
4326 OO.ui.mixin.FloatableElement.prototype.setVerticalPosition = function ( position ) {
4327 if ( [ 'below', 'above', 'top', 'bottom', 'center' ].indexOf( position ) === -1 ) {
4328 throw new Error( 'Invalid value for vertical position: ' + position );
4329 }
4330 if ( this.verticalPosition !== position ) {
4331 this.verticalPosition = position;
4332 if ( this.$floatable ) {
4333 this.position();
4334 }
4335 }
4336 };
4337
4338 /**
4339 * Change how the element is positioned horizontally.
4340 *
4341 * @param {string} position 'before', 'after', 'start', 'end' or 'center'
4342 */
4343 OO.ui.mixin.FloatableElement.prototype.setHorizontalPosition = function ( position ) {
4344 if ( [ 'before', 'after', 'start', 'end', 'center' ].indexOf( position ) === -1 ) {
4345 throw new Error( 'Invalid value for horizontal position: ' + position );
4346 }
4347 if ( this.horizontalPosition !== position ) {
4348 this.horizontalPosition = position;
4349 if ( this.$floatable ) {
4350 this.position();
4351 }
4352 }
4353 };
4354
4355 /**
4356 * Toggle positioning.
4357 *
4358 * Do not turn positioning on until after the element is attached to the DOM and visible.
4359 *
4360 * @param {boolean} [positioning] Enable positioning, omit to toggle
4361 * @chainable
4362 */
4363 OO.ui.mixin.FloatableElement.prototype.togglePositioning = function ( positioning ) {
4364 var closestScrollableOfContainer;
4365
4366 if ( !this.$floatable || !this.$floatableContainer ) {
4367 return this;
4368 }
4369
4370 positioning = positioning === undefined ? !this.positioning : !!positioning;
4371
4372 if ( positioning && !this.warnedUnattached && !this.isElementAttached() ) {
4373 OO.ui.warnDeprecation( 'FloatableElement#togglePositioning: Before calling this method, the element must be attached to the DOM.' );
4374 this.warnedUnattached = true;
4375 }
4376
4377 if ( this.positioning !== positioning ) {
4378 this.positioning = positioning;
4379
4380 this.needsCustomPosition =
4381 this.verticalPostion !== 'below' ||
4382 this.horizontalPosition !== 'start' ||
4383 !OO.ui.contains( this.$floatableContainer[ 0 ], this.$floatable[ 0 ] );
4384
4385 closestScrollableOfContainer = OO.ui.Element.static.getClosestScrollableContainer( this.$floatableContainer[ 0 ] );
4386 // If the scrollable is the root, we have to listen to scroll events
4387 // on the window because of browser inconsistencies.
4388 if ( $( closestScrollableOfContainer ).is( 'html, body' ) ) {
4389 closestScrollableOfContainer = OO.ui.Element.static.getWindow( closestScrollableOfContainer );
4390 }
4391
4392 if ( positioning ) {
4393 this.$floatableWindow = $( this.getElementWindow() );
4394 this.$floatableWindow.on( 'resize', this.onFloatableWindowResizeHandler );
4395
4396 this.$floatableClosestScrollable = $( closestScrollableOfContainer );
4397 this.$floatableClosestScrollable.on( 'scroll', this.onFloatableScrollHandler );
4398
4399 // Initial position after visible
4400 this.position();
4401 } else {
4402 if ( this.$floatableWindow ) {
4403 this.$floatableWindow.off( 'resize', this.onFloatableWindowResizeHandler );
4404 this.$floatableWindow = null;
4405 }
4406
4407 if ( this.$floatableClosestScrollable ) {
4408 this.$floatableClosestScrollable.off( 'scroll', this.onFloatableScrollHandler );
4409 this.$floatableClosestScrollable = null;
4410 }
4411
4412 this.$floatable.css( { left: '', right: '', top: '' } );
4413 }
4414 }
4415
4416 return this;
4417 };
4418
4419 /**
4420 * Check whether the bottom edge of the given element is within the viewport of the given container.
4421 *
4422 * @private
4423 * @param {jQuery} $element
4424 * @param {jQuery} $container
4425 * @return {boolean}
4426 */
4427 OO.ui.mixin.FloatableElement.prototype.isElementInViewport = function ( $element, $container ) {
4428 var elemRect, contRect, topEdgeInBounds, bottomEdgeInBounds, leftEdgeInBounds, rightEdgeInBounds,
4429 startEdgeInBounds, endEdgeInBounds, viewportSpacing,
4430 direction = $element.css( 'direction' );
4431
4432 elemRect = $element[ 0 ].getBoundingClientRect();
4433 if ( $container[ 0 ] === window ) {
4434 viewportSpacing = OO.ui.getViewportSpacing();
4435 contRect = {
4436 top: 0,
4437 left: 0,
4438 right: document.documentElement.clientWidth,
4439 bottom: document.documentElement.clientHeight
4440 };
4441 contRect.top += viewportSpacing.top;
4442 contRect.left += viewportSpacing.left;
4443 contRect.right -= viewportSpacing.right;
4444 contRect.bottom -= viewportSpacing.bottom;
4445 } else {
4446 contRect = $container[ 0 ].getBoundingClientRect();
4447 }
4448
4449 topEdgeInBounds = elemRect.top >= contRect.top && elemRect.top <= contRect.bottom;
4450 bottomEdgeInBounds = elemRect.bottom >= contRect.top && elemRect.bottom <= contRect.bottom;
4451 leftEdgeInBounds = elemRect.left >= contRect.left && elemRect.left <= contRect.right;
4452 rightEdgeInBounds = elemRect.right >= contRect.left && elemRect.right <= contRect.right;
4453 if ( direction === 'rtl' ) {
4454 startEdgeInBounds = rightEdgeInBounds;
4455 endEdgeInBounds = leftEdgeInBounds;
4456 } else {
4457 startEdgeInBounds = leftEdgeInBounds;
4458 endEdgeInBounds = rightEdgeInBounds;
4459 }
4460
4461 if ( this.verticalPosition === 'below' && !bottomEdgeInBounds ) {
4462 return false;
4463 }
4464 if ( this.verticalPosition === 'above' && !topEdgeInBounds ) {
4465 return false;
4466 }
4467 if ( this.horizontalPosition === 'before' && !startEdgeInBounds ) {
4468 return false;
4469 }
4470 if ( this.horizontalPosition === 'after' && !endEdgeInBounds ) {
4471 return false;
4472 }
4473
4474 // The other positioning values are all about being inside the container,
4475 // so in those cases all we care about is that any part of the container is visible.
4476 return elemRect.top <= contRect.bottom && elemRect.bottom >= contRect.top &&
4477 elemRect.left <= contRect.right && elemRect.right >= contRect.left;
4478 };
4479
4480 /**
4481 * Check if the floatable is hidden to the user because it was offscreen.
4482 *
4483 * @return {boolean} Floatable is out of view
4484 */
4485 OO.ui.mixin.FloatableElement.prototype.isFloatableOutOfView = function () {
4486 return this.floatableOutOfView;
4487 };
4488
4489 /**
4490 * Position the floatable below its container.
4491 *
4492 * This should only be done when both of them are attached to the DOM and visible.
4493 *
4494 * @chainable
4495 */
4496 OO.ui.mixin.FloatableElement.prototype.position = function () {
4497 if ( !this.positioning ) {
4498 return this;
4499 }
4500
4501 if ( !(
4502 // To continue, some things need to be true:
4503 // The element must actually be in the DOM
4504 this.isElementAttached() && (
4505 // The closest scrollable is the current window
4506 this.$floatableClosestScrollable[ 0 ] === this.getElementWindow() ||
4507 // OR is an element in the element's DOM
4508 $.contains( this.getElementDocument(), this.$floatableClosestScrollable[ 0 ] )
4509 )
4510 ) ) {
4511 // Abort early if important parts of the widget are no longer attached to the DOM
4512 return this;
4513 }
4514
4515 this.floatableOutOfView = this.hideWhenOutOfView && !this.isElementInViewport( this.$floatableContainer, this.$floatableClosestScrollable );
4516 if ( this.floatableOutOfView ) {
4517 this.$floatable.addClass( 'oo-ui-element-hidden' );
4518 return this;
4519 } else {
4520 this.$floatable.removeClass( 'oo-ui-element-hidden' );
4521 }
4522
4523 if ( !this.needsCustomPosition ) {
4524 return this;
4525 }
4526
4527 this.$floatable.css( this.computePosition() );
4528
4529 // We updated the position, so re-evaluate the clipping state.
4530 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
4531 // will not notice the need to update itself.)
4532 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
4533 // it not listen to the right events in the right places?
4534 if ( this.clip ) {
4535 this.clip();
4536 }
4537
4538 return this;
4539 };
4540
4541 /**
4542 * Compute how #$floatable should be positioned based on the position of #$floatableContainer
4543 * and the positioning settings. This is a helper for #position that shouldn't be called directly,
4544 * but may be overridden by subclasses if they want to change or add to the positioning logic.
4545 *
4546 * @return {Object} New position to apply with .css(). Keys are 'top', 'left', 'bottom' and 'right'.
4547 */
4548 OO.ui.mixin.FloatableElement.prototype.computePosition = function () {
4549 var isBody, scrollableX, scrollableY, containerPos,
4550 horizScrollbarHeight, vertScrollbarWidth, scrollTop, scrollLeft,
4551 newPos = { top: '', left: '', bottom: '', right: '' },
4552 direction = this.$floatableContainer.css( 'direction' ),
4553 $offsetParent = this.$floatable.offsetParent();
4554
4555 if ( $offsetParent.is( 'html' ) ) {
4556 // The innerHeight/Width and clientHeight/Width calculations don't work well on the
4557 // <html> element, but they do work on the <body>
4558 $offsetParent = $( $offsetParent[ 0 ].ownerDocument.body );
4559 }
4560 isBody = $offsetParent.is( 'body' );
4561 scrollableX = $offsetParent.css( 'overflow-x' ) === 'scroll' || $offsetParent.css( 'overflow-x' ) === 'auto';
4562 scrollableY = $offsetParent.css( 'overflow-y' ) === 'scroll' || $offsetParent.css( 'overflow-y' ) === 'auto';
4563
4564 vertScrollbarWidth = $offsetParent.innerWidth() - $offsetParent.prop( 'clientWidth' );
4565 horizScrollbarHeight = $offsetParent.innerHeight() - $offsetParent.prop( 'clientHeight' );
4566 // We don't need to compute and add scrollTop and scrollLeft if the scrollable container is the body,
4567 // or if it isn't scrollable
4568 scrollTop = scrollableY && !isBody ? $offsetParent.scrollTop() : 0;
4569 scrollLeft = scrollableX && !isBody ? OO.ui.Element.static.getScrollLeft( $offsetParent[ 0 ] ) : 0;
4570
4571 // Avoid passing the <body> to getRelativePosition(), because it won't return what we expect
4572 // if the <body> has a margin
4573 containerPos = isBody ?
4574 this.$floatableContainer.offset() :
4575 OO.ui.Element.static.getRelativePosition( this.$floatableContainer, $offsetParent );
4576 containerPos.bottom = containerPos.top + this.$floatableContainer.outerHeight();
4577 containerPos.right = containerPos.left + this.$floatableContainer.outerWidth();
4578 containerPos.start = direction === 'rtl' ? containerPos.right : containerPos.left;
4579 containerPos.end = direction === 'rtl' ? containerPos.left : containerPos.right;
4580
4581 if ( this.verticalPosition === 'below' ) {
4582 newPos.top = containerPos.bottom;
4583 } else if ( this.verticalPosition === 'above' ) {
4584 newPos.bottom = $offsetParent.outerHeight() - containerPos.top;
4585 } else if ( this.verticalPosition === 'top' ) {
4586 newPos.top = containerPos.top;
4587 } else if ( this.verticalPosition === 'bottom' ) {
4588 newPos.bottom = $offsetParent.outerHeight() - containerPos.bottom;
4589 } else if ( this.verticalPosition === 'center' ) {
4590 newPos.top = containerPos.top +
4591 ( this.$floatableContainer.height() - this.$floatable.height() ) / 2;
4592 }
4593
4594 if ( this.horizontalPosition === 'before' ) {
4595 newPos.end = containerPos.start;
4596 } else if ( this.horizontalPosition === 'after' ) {
4597 newPos.start = containerPos.end;
4598 } else if ( this.horizontalPosition === 'start' ) {
4599 newPos.start = containerPos.start;
4600 } else if ( this.horizontalPosition === 'end' ) {
4601 newPos.end = containerPos.end;
4602 } else if ( this.horizontalPosition === 'center' ) {
4603 newPos.left = containerPos.left +
4604 ( this.$floatableContainer.width() - this.$floatable.width() ) / 2;
4605 }
4606
4607 if ( newPos.start !== undefined ) {
4608 if ( direction === 'rtl' ) {
4609 newPos.right = ( isBody ? $( $offsetParent[ 0 ].ownerDocument.documentElement ) : $offsetParent ).outerWidth() - newPos.start;
4610 } else {
4611 newPos.left = newPos.start;
4612 }
4613 delete newPos.start;
4614 }
4615 if ( newPos.end !== undefined ) {
4616 if ( direction === 'rtl' ) {
4617 newPos.left = newPos.end;
4618 } else {
4619 newPos.right = ( isBody ? $( $offsetParent[ 0 ].ownerDocument.documentElement ) : $offsetParent ).outerWidth() - newPos.end;
4620 }
4621 delete newPos.end;
4622 }
4623
4624 // Account for scroll position
4625 if ( newPos.top !== '' ) {
4626 newPos.top += scrollTop;
4627 }
4628 if ( newPos.bottom !== '' ) {
4629 newPos.bottom -= scrollTop;
4630 }
4631 if ( newPos.left !== '' ) {
4632 newPos.left += scrollLeft;
4633 }
4634 if ( newPos.right !== '' ) {
4635 newPos.right -= scrollLeft;
4636 }
4637
4638 // Account for scrollbar gutter
4639 if ( newPos.bottom !== '' ) {
4640 newPos.bottom -= horizScrollbarHeight;
4641 }
4642 if ( direction === 'rtl' ) {
4643 if ( newPos.left !== '' ) {
4644 newPos.left -= vertScrollbarWidth;
4645 }
4646 } else {
4647 if ( newPos.right !== '' ) {
4648 newPos.right -= vertScrollbarWidth;
4649 }
4650 }
4651
4652 return newPos;
4653 };
4654
4655 /**
4656 * Element that can be automatically clipped to visible boundaries.
4657 *
4658 * Whenever the element's natural height changes, you have to call
4659 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
4660 * clipping correctly.
4661 *
4662 * The dimensions of #$clippableContainer will be compared to the boundaries of the
4663 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
4664 * then #$clippable will be given a fixed reduced height and/or width and will be made
4665 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
4666 * but you can build a static footer by setting #$clippableContainer to an element that contains
4667 * #$clippable and the footer.
4668 *
4669 * @abstract
4670 * @class
4671 *
4672 * @constructor
4673 * @param {Object} [config] Configuration options
4674 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
4675 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
4676 * omit to use #$clippable
4677 */
4678 OO.ui.mixin.ClippableElement = function OoUiMixinClippableElement( config ) {
4679 // Configuration initialization
4680 config = config || {};
4681
4682 // Properties
4683 this.$clippable = null;
4684 this.$clippableContainer = null;
4685 this.clipping = false;
4686 this.clippedHorizontally = false;
4687 this.clippedVertically = false;
4688 this.$clippableScrollableContainer = null;
4689 this.$clippableScroller = null;
4690 this.$clippableWindow = null;
4691 this.idealWidth = null;
4692 this.idealHeight = null;
4693 this.onClippableScrollHandler = this.clip.bind( this );
4694 this.onClippableWindowResizeHandler = this.clip.bind( this );
4695
4696 // Initialization
4697 if ( config.$clippableContainer ) {
4698 this.setClippableContainer( config.$clippableContainer );
4699 }
4700 this.setClippableElement( config.$clippable || this.$element );
4701 };
4702
4703 /* Methods */
4704
4705 /**
4706 * Set clippable element.
4707 *
4708 * If an element is already set, it will be cleaned up before setting up the new element.
4709 *
4710 * @param {jQuery} $clippable Element to make clippable
4711 */
4712 OO.ui.mixin.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
4713 if ( this.$clippable ) {
4714 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
4715 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
4716 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
4717 }
4718
4719 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
4720 this.clip();
4721 };
4722
4723 /**
4724 * Set clippable container.
4725 *
4726 * This is the container that will be measured when deciding whether to clip. When clipping,
4727 * #$clippable will be resized in order to keep the clippable container fully visible.
4728 *
4729 * If the clippable container is unset, #$clippable will be used.
4730 *
4731 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
4732 */
4733 OO.ui.mixin.ClippableElement.prototype.setClippableContainer = function ( $clippableContainer ) {
4734 this.$clippableContainer = $clippableContainer;
4735 if ( this.$clippable ) {
4736 this.clip();
4737 }
4738 };
4739
4740 /**
4741 * Toggle clipping.
4742 *
4743 * Do not turn clipping on until after the element is attached to the DOM and visible.
4744 *
4745 * @param {boolean} [clipping] Enable clipping, omit to toggle
4746 * @chainable
4747 */
4748 OO.ui.mixin.ClippableElement.prototype.toggleClipping = function ( clipping ) {
4749 clipping = clipping === undefined ? !this.clipping : !!clipping;
4750
4751 if ( clipping && !this.warnedUnattached && !this.isElementAttached() ) {
4752 OO.ui.warnDeprecation( 'ClippableElement#toggleClipping: Before calling this method, the element must be attached to the DOM.' );
4753 this.warnedUnattached = true;
4754 }
4755
4756 if ( this.clipping !== clipping ) {
4757 this.clipping = clipping;
4758 if ( clipping ) {
4759 this.$clippableScrollableContainer = $( this.getClosestScrollableElementContainer() );
4760 // If the clippable container is the root, we have to listen to scroll events and check
4761 // jQuery.scrollTop on the window because of browser inconsistencies
4762 this.$clippableScroller = this.$clippableScrollableContainer.is( 'html, body' ) ?
4763 $( OO.ui.Element.static.getWindow( this.$clippableScrollableContainer ) ) :
4764 this.$clippableScrollableContainer;
4765 this.$clippableScroller.on( 'scroll', this.onClippableScrollHandler );
4766 this.$clippableWindow = $( this.getElementWindow() )
4767 .on( 'resize', this.onClippableWindowResizeHandler );
4768 // Initial clip after visible
4769 this.clip();
4770 } else {
4771 this.$clippable.css( {
4772 width: '',
4773 height: '',
4774 maxWidth: '',
4775 maxHeight: '',
4776 overflowX: '',
4777 overflowY: ''
4778 } );
4779 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
4780
4781 this.$clippableScrollableContainer = null;
4782 this.$clippableScroller.off( 'scroll', this.onClippableScrollHandler );
4783 this.$clippableScroller = null;
4784 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
4785 this.$clippableWindow = null;
4786 }
4787 }
4788
4789 return this;
4790 };
4791
4792 /**
4793 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4794 *
4795 * @return {boolean} Element will be clipped to the visible area
4796 */
4797 OO.ui.mixin.ClippableElement.prototype.isClipping = function () {
4798 return this.clipping;
4799 };
4800
4801 /**
4802 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
4803 *
4804 * @return {boolean} Part of the element is being clipped
4805 */
4806 OO.ui.mixin.ClippableElement.prototype.isClipped = function () {
4807 return this.clippedHorizontally || this.clippedVertically;
4808 };
4809
4810 /**
4811 * Check if the right of the element is being clipped by the nearest scrollable container.
4812 *
4813 * @return {boolean} Part of the element is being clipped
4814 */
4815 OO.ui.mixin.ClippableElement.prototype.isClippedHorizontally = function () {
4816 return this.clippedHorizontally;
4817 };
4818
4819 /**
4820 * Check if the bottom of the element is being clipped by the nearest scrollable container.
4821 *
4822 * @return {boolean} Part of the element is being clipped
4823 */
4824 OO.ui.mixin.ClippableElement.prototype.isClippedVertically = function () {
4825 return this.clippedVertically;
4826 };
4827
4828 /**
4829 * Set the ideal size. These are the dimensions #$clippable will have when it's not being clipped.
4830 *
4831 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
4832 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
4833 */
4834 OO.ui.mixin.ClippableElement.prototype.setIdealSize = function ( width, height ) {
4835 this.idealWidth = width;
4836 this.idealHeight = height;
4837
4838 if ( !this.clipping ) {
4839 // Update dimensions
4840 this.$clippable.css( { width: width, height: height } );
4841 }
4842 // While clipping, idealWidth and idealHeight are not considered
4843 };
4844
4845 /**
4846 * Return the side of the clippable on which it is "anchored" (aligned to something else).
4847 * ClippableElement will clip the opposite side when reducing element's width.
4848 *
4849 * Classes that mix in ClippableElement should override this to return 'right' if their
4850 * clippable is absolutely positioned and using 'right: Npx' (and not using 'left').
4851 * If your class also mixes in FloatableElement, this is handled automatically.
4852 *
4853 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
4854 * always in pixels, even if they were unset or set to 'auto'.)
4855 *
4856 * When in doubt, 'left' (or 'right' in RTL) is a sane fallback.
4857 *
4858 * @return {string} 'left' or 'right'
4859 */
4860 OO.ui.mixin.ClippableElement.prototype.getHorizontalAnchorEdge = function () {
4861 if ( this.computePosition && this.positioning && this.computePosition().right !== '' ) {
4862 return 'right';
4863 }
4864 return 'left';
4865 };
4866
4867 /**
4868 * Return the side of the clippable on which it is "anchored" (aligned to something else).
4869 * ClippableElement will clip the opposite side when reducing element's width.
4870 *
4871 * Classes that mix in ClippableElement should override this to return 'bottom' if their
4872 * clippable is absolutely positioned and using 'bottom: Npx' (and not using 'top').
4873 * If your class also mixes in FloatableElement, this is handled automatically.
4874 *
4875 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
4876 * always in pixels, even if they were unset or set to 'auto'.)
4877 *
4878 * When in doubt, 'top' is a sane fallback.
4879 *
4880 * @return {string} 'top' or 'bottom'
4881 */
4882 OO.ui.mixin.ClippableElement.prototype.getVerticalAnchorEdge = function () {
4883 if ( this.computePosition && this.positioning && this.computePosition().bottom !== '' ) {
4884 return 'bottom';
4885 }
4886 return 'top';
4887 };
4888
4889 /**
4890 * Clip element to visible boundaries and allow scrolling when needed. You should call this method
4891 * when the element's natural height changes.
4892 *
4893 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
4894 * overlapped by, the visible area of the nearest scrollable container.
4895 *
4896 * Because calling clip() when the natural height changes isn't always possible, we also set
4897 * max-height when the element isn't being clipped. This means that if the element tries to grow
4898 * beyond the edge, something reasonable will happen before clip() is called.
4899 *
4900 * @chainable
4901 */
4902 OO.ui.mixin.ClippableElement.prototype.clip = function () {
4903 var extraHeight, extraWidth, viewportSpacing,
4904 desiredWidth, desiredHeight, allotedWidth, allotedHeight,
4905 naturalWidth, naturalHeight, clipWidth, clipHeight,
4906 $item, itemRect, $viewport, viewportRect, availableRect,
4907 direction, vertScrollbarWidth, horizScrollbarHeight,
4908 // Extra tolerance so that the sloppy code below doesn't result in results that are off
4909 // by one or two pixels. (And also so that we have space to display drop shadows.)
4910 // Chosen by fair dice roll.
4911 buffer = 7;
4912
4913 if ( !this.clipping ) {
4914 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
4915 return this;
4916 }
4917
4918 function rectIntersection( a, b ) {
4919 var out = {};
4920 out.top = Math.max( a.top, b.top );
4921 out.left = Math.max( a.left, b.left );
4922 out.bottom = Math.min( a.bottom, b.bottom );
4923 out.right = Math.min( a.right, b.right );
4924 return out;
4925 }
4926
4927 viewportSpacing = OO.ui.getViewportSpacing();
4928
4929 if ( this.$clippableScrollableContainer.is( 'html, body' ) ) {
4930 $viewport = $( this.$clippableScrollableContainer[ 0 ].ownerDocument.body );
4931 // Dimensions of the browser window, rather than the element!
4932 viewportRect = {
4933 top: 0,
4934 left: 0,
4935 right: document.documentElement.clientWidth,
4936 bottom: document.documentElement.clientHeight
4937 };
4938 viewportRect.top += viewportSpacing.top;
4939 viewportRect.left += viewportSpacing.left;
4940 viewportRect.right -= viewportSpacing.right;
4941 viewportRect.bottom -= viewportSpacing.bottom;
4942 } else {
4943 $viewport = this.$clippableScrollableContainer;
4944 viewportRect = $viewport[ 0 ].getBoundingClientRect();
4945 // Convert into a plain object
4946 viewportRect = $.extend( {}, viewportRect );
4947 }
4948
4949 // Account for scrollbar gutter
4950 direction = $viewport.css( 'direction' );
4951 vertScrollbarWidth = $viewport.innerWidth() - $viewport.prop( 'clientWidth' );
4952 horizScrollbarHeight = $viewport.innerHeight() - $viewport.prop( 'clientHeight' );
4953 viewportRect.bottom -= horizScrollbarHeight;
4954 if ( direction === 'rtl' ) {
4955 viewportRect.left += vertScrollbarWidth;
4956 } else {
4957 viewportRect.right -= vertScrollbarWidth;
4958 }
4959
4960 // Add arbitrary tolerance
4961 viewportRect.top += buffer;
4962 viewportRect.left += buffer;
4963 viewportRect.right -= buffer;
4964 viewportRect.bottom -= buffer;
4965
4966 $item = this.$clippableContainer || this.$clippable;
4967
4968 extraHeight = $item.outerHeight() - this.$clippable.outerHeight();
4969 extraWidth = $item.outerWidth() - this.$clippable.outerWidth();
4970
4971 itemRect = $item[ 0 ].getBoundingClientRect();
4972 // Convert into a plain object
4973 itemRect = $.extend( {}, itemRect );
4974
4975 // Item might already be clipped, so we can't just use its dimensions (in case we might need to
4976 // make it larger than before). Extend the rectangle to the maximum size we are allowed to take.
4977 if ( this.getHorizontalAnchorEdge() === 'right' ) {
4978 itemRect.left = viewportRect.left;
4979 } else {
4980 itemRect.right = viewportRect.right;
4981 }
4982 if ( this.getVerticalAnchorEdge() === 'bottom' ) {
4983 itemRect.top = viewportRect.top;
4984 } else {
4985 itemRect.bottom = viewportRect.bottom;
4986 }
4987
4988 availableRect = rectIntersection( viewportRect, itemRect );
4989
4990 desiredWidth = Math.max( 0, availableRect.right - availableRect.left );
4991 desiredHeight = Math.max( 0, availableRect.bottom - availableRect.top );
4992 // It should never be desirable to exceed the dimensions of the browser viewport... right?
4993 desiredWidth = Math.min( desiredWidth,
4994 document.documentElement.clientWidth - viewportSpacing.left - viewportSpacing.right );
4995 desiredHeight = Math.min( desiredHeight,
4996 document.documentElement.clientHeight - viewportSpacing.top - viewportSpacing.right );
4997 allotedWidth = Math.ceil( desiredWidth - extraWidth );
4998 allotedHeight = Math.ceil( desiredHeight - extraHeight );
4999 naturalWidth = this.$clippable.prop( 'scrollWidth' );
5000 naturalHeight = this.$clippable.prop( 'scrollHeight' );
5001 clipWidth = allotedWidth < naturalWidth;
5002 clipHeight = allotedHeight < naturalHeight;
5003
5004 if ( clipWidth ) {
5005 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. See T157672.
5006 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
5007 this.$clippable.css( 'overflowX', 'scroll' );
5008 void this.$clippable[ 0 ].offsetHeight; // Force reflow
5009 this.$clippable.css( {
5010 width: Math.max( 0, allotedWidth ),
5011 maxWidth: ''
5012 } );
5013 } else {
5014 this.$clippable.css( {
5015 overflowX: '',
5016 width: this.idealWidth || '',
5017 maxWidth: Math.max( 0, allotedWidth )
5018 } );
5019 }
5020 if ( clipHeight ) {
5021 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. See T157672.
5022 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
5023 this.$clippable.css( 'overflowY', 'scroll' );
5024 void this.$clippable[ 0 ].offsetHeight; // Force reflow
5025 this.$clippable.css( {
5026 height: Math.max( 0, allotedHeight ),
5027 maxHeight: ''
5028 } );
5029 } else {
5030 this.$clippable.css( {
5031 overflowY: '',
5032 height: this.idealHeight || '',
5033 maxHeight: Math.max( 0, allotedHeight )
5034 } );
5035 }
5036
5037 // If we stopped clipping in at least one of the dimensions
5038 if ( ( this.clippedHorizontally && !clipWidth ) || ( this.clippedVertically && !clipHeight ) ) {
5039 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
5040 }
5041
5042 this.clippedHorizontally = clipWidth;
5043 this.clippedVertically = clipHeight;
5044
5045 return this;
5046 };
5047
5048 /**
5049 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
5050 * By default, each popup has an anchor that points toward its origin.
5051 * Please see the [OOUI documentation on Mediawiki] [1] for more information and examples.
5052 *
5053 * Unlike most widgets, PopupWidget is initially hidden and must be shown by calling #toggle.
5054 *
5055 * @example
5056 * // A popup widget.
5057 * var popup = new OO.ui.PopupWidget( {
5058 * $content: $( '<p>Hi there!</p>' ),
5059 * padded: true,
5060 * width: 300
5061 * } );
5062 *
5063 * $( 'body' ).append( popup.$element );
5064 * // To display the popup, toggle the visibility to 'true'.
5065 * popup.toggle( true );
5066 *
5067 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups
5068 *
5069 * @class
5070 * @extends OO.ui.Widget
5071 * @mixins OO.ui.mixin.LabelElement
5072 * @mixins OO.ui.mixin.ClippableElement
5073 * @mixins OO.ui.mixin.FloatableElement
5074 *
5075 * @constructor
5076 * @param {Object} [config] Configuration options
5077 * @cfg {number} [width=320] Width of popup in pixels
5078 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
5079 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
5080 * @cfg {string} [position='below'] Where to position the popup relative to $floatableContainer
5081 * 'above': Put popup above $floatableContainer; anchor points down to the horizontal center
5082 * of $floatableContainer
5083 * 'below': Put popup below $floatableContainer; anchor points up to the horizontal center
5084 * of $floatableContainer
5085 * 'before': Put popup to the left (LTR) / right (RTL) of $floatableContainer; anchor points
5086 * endwards (right/left) to the vertical center of $floatableContainer
5087 * 'after': Put popup to the right (LTR) / left (RTL) of $floatableContainer; anchor points
5088 * startwards (left/right) to the vertical center of $floatableContainer
5089 * @cfg {string} [align='center'] How to align the popup to $floatableContainer
5090 * 'forwards': If position is above/below, move the popup as far endwards (right in LTR, left in RTL)
5091 * as possible while still keeping the anchor within the popup;
5092 * if position is before/after, move the popup as far downwards as possible.
5093 * 'backwards': If position is above/below, move the popup as far startwards (left in LTR, right in RTL)
5094 * as possible while still keeping the anchor within the popup;
5095 * if position in before/after, move the popup as far upwards as possible.
5096 * 'center': Horizontally (if position is above/below) or vertically (before/after) align the center
5097 * of the popup with the center of $floatableContainer.
5098 * 'force-left': Alias for 'forwards' in LTR and 'backwards' in RTL
5099 * 'force-right': Alias for 'backwards' in RTL and 'forwards' in LTR
5100 * @cfg {boolean} [autoFlip=true] Whether to automatically switch the popup's position between
5101 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5102 * desired direction to display the popup without clipping
5103 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
5104 * See the [OOUI docs on MediaWiki][3] for an example.
5105 * [3]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#containerExample
5106 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
5107 * @cfg {jQuery} [$content] Content to append to the popup's body
5108 * @cfg {jQuery} [$footer] Content to append to the popup's footer
5109 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
5110 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
5111 * This config option is only relevant if #autoClose is set to `true`. See the [OOUI documentation on MediaWiki][2]
5112 * for an example.
5113 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#autocloseExample
5114 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
5115 * button.
5116 * @cfg {boolean} [padded=false] Add padding to the popup's body
5117 */
5118 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
5119 // Configuration initialization
5120 config = config || {};
5121
5122 // Parent constructor
5123 OO.ui.PopupWidget.parent.call( this, config );
5124
5125 // Properties (must be set before ClippableElement constructor call)
5126 this.$body = $( '<div>' );
5127 this.$popup = $( '<div>' );
5128
5129 // Mixin constructors
5130 OO.ui.mixin.LabelElement.call( this, config );
5131 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, {
5132 $clippable: this.$body,
5133 $clippableContainer: this.$popup
5134 } ) );
5135 OO.ui.mixin.FloatableElement.call( this, config );
5136
5137 // Properties
5138 this.$anchor = $( '<div>' );
5139 // If undefined, will be computed lazily in computePosition()
5140 this.$container = config.$container;
5141 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
5142 this.autoClose = !!config.autoClose;
5143 this.$autoCloseIgnore = config.$autoCloseIgnore;
5144 this.transitionTimeout = null;
5145 this.anchored = false;
5146 this.width = config.width !== undefined ? config.width : 320;
5147 this.height = config.height !== undefined ? config.height : null;
5148 this.onMouseDownHandler = this.onMouseDown.bind( this );
5149 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
5150
5151 // Initialization
5152 this.toggleAnchor( config.anchor === undefined || config.anchor );
5153 this.setAlignment( config.align || 'center' );
5154 this.setPosition( config.position || 'below' );
5155 this.setAutoFlip( config.autoFlip === undefined || config.autoFlip );
5156 this.$body.addClass( 'oo-ui-popupWidget-body' );
5157 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
5158 this.$popup
5159 .addClass( 'oo-ui-popupWidget-popup' )
5160 .append( this.$body );
5161 this.$element
5162 .addClass( 'oo-ui-popupWidget' )
5163 .append( this.$popup, this.$anchor );
5164 // Move content, which was added to #$element by OO.ui.Widget, to the body
5165 // FIXME This is gross, we should use '$body' or something for the config
5166 if ( config.$content instanceof jQuery ) {
5167 this.$body.append( config.$content );
5168 }
5169
5170 if ( config.padded ) {
5171 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
5172 }
5173
5174 if ( config.head ) {
5175 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
5176 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
5177 this.$head = $( '<div>' )
5178 .addClass( 'oo-ui-popupWidget-head' )
5179 .append( this.$label, this.closeButton.$element );
5180 this.$popup.prepend( this.$head );
5181 }
5182
5183 if ( config.$footer ) {
5184 this.$footer = $( '<div>' )
5185 .addClass( 'oo-ui-popupWidget-footer' )
5186 .append( config.$footer );
5187 this.$popup.append( this.$footer );
5188 }
5189
5190 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
5191 // that reference properties not initialized at that time of parent class construction
5192 // TODO: Find a better way to handle post-constructor setup
5193 this.visible = false;
5194 this.$element.addClass( 'oo-ui-element-hidden' );
5195 };
5196
5197 /* Setup */
5198
5199 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
5200 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.LabelElement );
5201 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.ClippableElement );
5202 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.FloatableElement );
5203
5204 /* Events */
5205
5206 /**
5207 * @event ready
5208 *
5209 * The popup is ready: it is visible and has been positioned and clipped.
5210 */
5211
5212 /* Methods */
5213
5214 /**
5215 * Handles mouse down events.
5216 *
5217 * @private
5218 * @param {MouseEvent} e Mouse down event
5219 */
5220 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
5221 if (
5222 this.isVisible() &&
5223 !OO.ui.contains( this.$element.add( this.$autoCloseIgnore ).get(), e.target, true )
5224 ) {
5225 this.toggle( false );
5226 }
5227 };
5228
5229 /**
5230 * Bind mouse down listener.
5231 *
5232 * @private
5233 */
5234 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
5235 // Capture clicks outside popup
5236 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler, true );
5237 };
5238
5239 /**
5240 * Handles close button click events.
5241 *
5242 * @private
5243 */
5244 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
5245 if ( this.isVisible() ) {
5246 this.toggle( false );
5247 }
5248 };
5249
5250 /**
5251 * Unbind mouse down listener.
5252 *
5253 * @private
5254 */
5255 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
5256 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler, true );
5257 };
5258
5259 /**
5260 * Handles key down events.
5261 *
5262 * @private
5263 * @param {KeyboardEvent} e Key down event
5264 */
5265 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
5266 if (
5267 e.which === OO.ui.Keys.ESCAPE &&
5268 this.isVisible()
5269 ) {
5270 this.toggle( false );
5271 e.preventDefault();
5272 e.stopPropagation();
5273 }
5274 };
5275
5276 /**
5277 * Bind key down listener.
5278 *
5279 * @private
5280 */
5281 OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
5282 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
5283 };
5284
5285 /**
5286 * Unbind key down listener.
5287 *
5288 * @private
5289 */
5290 OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
5291 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
5292 };
5293
5294 /**
5295 * Show, hide, or toggle the visibility of the anchor.
5296 *
5297 * @param {boolean} [show] Show anchor, omit to toggle
5298 */
5299 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
5300 show = show === undefined ? !this.anchored : !!show;
5301
5302 if ( this.anchored !== show ) {
5303 if ( show ) {
5304 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
5305 this.$element.addClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge );
5306 } else {
5307 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
5308 this.$element.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge );
5309 }
5310 this.anchored = show;
5311 }
5312 };
5313
5314 /**
5315 * Change which edge the anchor appears on.
5316 *
5317 * @param {string} edge 'top', 'bottom', 'start' or 'end'
5318 */
5319 OO.ui.PopupWidget.prototype.setAnchorEdge = function ( edge ) {
5320 if ( [ 'top', 'bottom', 'start', 'end' ].indexOf( edge ) === -1 ) {
5321 throw new Error( 'Invalid value for edge: ' + edge );
5322 }
5323 if ( this.anchorEdge !== null ) {
5324 this.$element.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge );
5325 }
5326 this.anchorEdge = edge;
5327 if ( this.anchored ) {
5328 this.$element.addClass( 'oo-ui-popupWidget-anchored-' + edge );
5329 }
5330 };
5331
5332 /**
5333 * Check if the anchor is visible.
5334 *
5335 * @return {boolean} Anchor is visible
5336 */
5337 OO.ui.PopupWidget.prototype.hasAnchor = function () {
5338 return this.anchored;
5339 };
5340
5341 /**
5342 * Toggle visibility of the popup. The popup is initially hidden and must be shown by calling
5343 * `.toggle( true )` after its #$element is attached to the DOM.
5344 *
5345 * Do not show the popup while it is not attached to the DOM. The calculations required to display
5346 * it in the right place and with the right dimensions only work correctly while it is attached.
5347 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
5348 * strictly enforced, so currently it only generates a warning in the browser console.
5349 *
5350 * @fires ready
5351 * @inheritdoc
5352 */
5353 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
5354 var change, normalHeight, oppositeHeight, normalWidth, oppositeWidth;
5355 show = show === undefined ? !this.isVisible() : !!show;
5356
5357 change = show !== this.isVisible();
5358
5359 if ( show && !this.warnedUnattached && !this.isElementAttached() ) {
5360 OO.ui.warnDeprecation( 'PopupWidget#toggle: Before calling this method, the popup must be attached to the DOM.' );
5361 this.warnedUnattached = true;
5362 }
5363 if ( show && !this.$floatableContainer && this.isElementAttached() ) {
5364 // Fall back to the parent node if the floatableContainer is not set
5365 this.setFloatableContainer( this.$element.parent() );
5366 }
5367
5368 if ( change && show && this.autoFlip ) {
5369 // Reset auto-flipping before showing the popup again. It's possible we no longer need to flip
5370 // (e.g. if the user scrolled).
5371 this.isAutoFlipped = false;
5372 }
5373
5374 // Parent method
5375 OO.ui.PopupWidget.parent.prototype.toggle.call( this, show );
5376
5377 if ( change ) {
5378 this.togglePositioning( show && !!this.$floatableContainer );
5379
5380 if ( show ) {
5381 if ( this.autoClose ) {
5382 this.bindMouseDownListener();
5383 this.bindKeyDownListener();
5384 }
5385 this.updateDimensions();
5386 this.toggleClipping( true );
5387
5388 if ( this.autoFlip ) {
5389 if ( this.popupPosition === 'above' || this.popupPosition === 'below' ) {
5390 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5391 // If opening the popup in the normal direction causes it to be clipped, open
5392 // in the opposite one instead
5393 normalHeight = this.$element.height();
5394 this.isAutoFlipped = !this.isAutoFlipped;
5395 this.position();
5396 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5397 // If that also causes it to be clipped, open in whichever direction
5398 // we have more space
5399 oppositeHeight = this.$element.height();
5400 if ( oppositeHeight < normalHeight ) {
5401 this.isAutoFlipped = !this.isAutoFlipped;
5402 this.position();
5403 }
5404 }
5405 }
5406 }
5407 if ( this.popupPosition === 'before' || this.popupPosition === 'after' ) {
5408 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5409 // If opening the popup in the normal direction causes it to be clipped, open
5410 // in the opposite one instead
5411 normalWidth = this.$element.width();
5412 this.isAutoFlipped = !this.isAutoFlipped;
5413 // Due to T180173 horizontally clipped PopupWidgets have messed up dimensions,
5414 // which causes positioning to be off. Toggle clipping back and fort to work around.
5415 this.toggleClipping( false );
5416 this.position();
5417 this.toggleClipping( true );
5418 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5419 // If that also causes it to be clipped, open in whichever direction
5420 // we have more space
5421 oppositeWidth = this.$element.width();
5422 if ( oppositeWidth < normalWidth ) {
5423 this.isAutoFlipped = !this.isAutoFlipped;
5424 // Due to T180173 horizontally clipped PopupWidgets have messed up dimensions,
5425 // which causes positioning to be off. Toggle clipping back and fort to work around.
5426 this.toggleClipping( false );
5427 this.position();
5428 this.toggleClipping( true );
5429 }
5430 }
5431 }
5432 }
5433 }
5434
5435 this.emit( 'ready' );
5436 } else {
5437 this.toggleClipping( false );
5438 if ( this.autoClose ) {
5439 this.unbindMouseDownListener();
5440 this.unbindKeyDownListener();
5441 }
5442 }
5443 }
5444
5445 return this;
5446 };
5447
5448 /**
5449 * Set the size of the popup.
5450 *
5451 * Changing the size may also change the popup's position depending on the alignment.
5452 *
5453 * @param {number} width Width in pixels
5454 * @param {number} height Height in pixels
5455 * @param {boolean} [transition=false] Use a smooth transition
5456 * @chainable
5457 */
5458 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
5459 this.width = width;
5460 this.height = height !== undefined ? height : null;
5461 if ( this.isVisible() ) {
5462 this.updateDimensions( transition );
5463 }
5464 };
5465
5466 /**
5467 * Update the size and position.
5468 *
5469 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
5470 * be called automatically.
5471 *
5472 * @param {boolean} [transition=false] Use a smooth transition
5473 * @chainable
5474 */
5475 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
5476 var widget = this;
5477
5478 // Prevent transition from being interrupted
5479 clearTimeout( this.transitionTimeout );
5480 if ( transition ) {
5481 // Enable transition
5482 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
5483 }
5484
5485 this.position();
5486
5487 if ( transition ) {
5488 // Prevent transitioning after transition is complete
5489 this.transitionTimeout = setTimeout( function () {
5490 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
5491 }, 200 );
5492 } else {
5493 // Prevent transitioning immediately
5494 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
5495 }
5496 };
5497
5498 /**
5499 * @inheritdoc
5500 */
5501 OO.ui.PopupWidget.prototype.computePosition = function () {
5502 var direction, align, vertical, start, end, near, far, sizeProp, popupSize, anchorSize, anchorPos,
5503 anchorOffset, anchorMargin, parentPosition, positionProp, positionAdjustment, floatablePos,
5504 offsetParentPos, containerPos, popupPosition, viewportSpacing,
5505 popupPos = {},
5506 anchorCss = { left: '', right: '', top: '', bottom: '' },
5507 popupPositionOppositeMap = {
5508 above: 'below',
5509 below: 'above',
5510 before: 'after',
5511 after: 'before'
5512 },
5513 alignMap = {
5514 ltr: {
5515 'force-left': 'backwards',
5516 'force-right': 'forwards'
5517 },
5518 rtl: {
5519 'force-left': 'forwards',
5520 'force-right': 'backwards'
5521 }
5522 },
5523 anchorEdgeMap = {
5524 above: 'bottom',
5525 below: 'top',
5526 before: 'end',
5527 after: 'start'
5528 },
5529 hPosMap = {
5530 forwards: 'start',
5531 center: 'center',
5532 backwards: this.anchored ? 'before' : 'end'
5533 },
5534 vPosMap = {
5535 forwards: 'top',
5536 center: 'center',
5537 backwards: 'bottom'
5538 };
5539
5540 if ( !this.$container ) {
5541 // Lazy-initialize $container if not specified in constructor
5542 this.$container = $( this.getClosestScrollableElementContainer() );
5543 }
5544 direction = this.$container.css( 'direction' );
5545
5546 // Set height and width before we do anything else, since it might cause our measurements
5547 // to change (e.g. due to scrollbars appearing or disappearing), and it also affects centering
5548 this.$popup.css( {
5549 width: this.width,
5550 height: this.height !== null ? this.height : 'auto'
5551 } );
5552
5553 align = alignMap[ direction ][ this.align ] || this.align;
5554 popupPosition = this.popupPosition;
5555 if ( this.isAutoFlipped ) {
5556 popupPosition = popupPositionOppositeMap[ popupPosition ];
5557 }
5558
5559 // If the popup is positioned before or after, then the anchor positioning is vertical, otherwise horizontal
5560 vertical = popupPosition === 'before' || popupPosition === 'after';
5561 start = vertical ? 'top' : ( direction === 'rtl' ? 'right' : 'left' );
5562 end = vertical ? 'bottom' : ( direction === 'rtl' ? 'left' : 'right' );
5563 near = vertical ? 'top' : 'left';
5564 far = vertical ? 'bottom' : 'right';
5565 sizeProp = vertical ? 'Height' : 'Width';
5566 popupSize = vertical ? ( this.height || this.$popup.height() ) : this.width;
5567
5568 this.setAnchorEdge( anchorEdgeMap[ popupPosition ] );
5569 this.horizontalPosition = vertical ? popupPosition : hPosMap[ align ];
5570 this.verticalPosition = vertical ? vPosMap[ align ] : popupPosition;
5571
5572 // Parent method
5573 parentPosition = OO.ui.mixin.FloatableElement.prototype.computePosition.call( this );
5574 // Find out which property FloatableElement used for positioning, and adjust that value
5575 positionProp = vertical ?
5576 ( parentPosition.top !== '' ? 'top' : 'bottom' ) :
5577 ( parentPosition.left !== '' ? 'left' : 'right' );
5578
5579 // Figure out where the near and far edges of the popup and $floatableContainer are
5580 floatablePos = this.$floatableContainer.offset();
5581 floatablePos[ far ] = floatablePos[ near ] + this.$floatableContainer[ 'outer' + sizeProp ]();
5582 // Measure where the offsetParent is and compute our position based on that and parentPosition
5583 offsetParentPos = this.$element.offsetParent()[ 0 ] === document.documentElement ?
5584 { top: 0, left: 0 } :
5585 this.$element.offsetParent().offset();
5586
5587 if ( positionProp === near ) {
5588 popupPos[ near ] = offsetParentPos[ near ] + parentPosition[ near ];
5589 popupPos[ far ] = popupPos[ near ] + popupSize;
5590 } else {
5591 popupPos[ far ] = offsetParentPos[ near ] +
5592 this.$element.offsetParent()[ 'inner' + sizeProp ]() - parentPosition[ far ];
5593 popupPos[ near ] = popupPos[ far ] - popupSize;
5594 }
5595
5596 if ( this.anchored ) {
5597 // Position the anchor (which is positioned relative to the popup) to point to $floatableContainer
5598 anchorPos = ( floatablePos[ start ] + floatablePos[ end ] ) / 2;
5599 anchorOffset = ( start === far ? -1 : 1 ) * ( anchorPos - popupPos[ start ] );
5600
5601 // If the anchor is less than 2*anchorSize from either edge, move the popup to make more space
5602 // this.$anchor.width()/height() returns 0 because of the CSS trickery we use, so use scrollWidth/Height
5603 anchorSize = this.$anchor[ 0 ][ 'scroll' + sizeProp ];
5604 anchorMargin = parseFloat( this.$anchor.css( 'margin-' + start ) );
5605 if ( anchorOffset + anchorMargin < 2 * anchorSize ) {
5606 // Not enough space for the anchor on the start side; pull the popup startwards
5607 positionAdjustment = ( positionProp === start ? -1 : 1 ) *
5608 ( 2 * anchorSize - ( anchorOffset + anchorMargin ) );
5609 } else if ( anchorOffset + anchorMargin > popupSize - 2 * anchorSize ) {
5610 // Not enough space for the anchor on the end side; pull the popup endwards
5611 positionAdjustment = ( positionProp === end ? -1 : 1 ) *
5612 ( anchorOffset + anchorMargin - ( popupSize - 2 * anchorSize ) );
5613 } else {
5614 positionAdjustment = 0;
5615 }
5616 } else {
5617 positionAdjustment = 0;
5618 }
5619
5620 // Check if the popup will go beyond the edge of this.$container
5621 containerPos = this.$container[ 0 ] === document.documentElement ?
5622 { top: 0, left: 0 } :
5623 this.$container.offset();
5624 containerPos[ far ] = containerPos[ near ] + this.$container[ 'inner' + sizeProp ]();
5625 if ( this.$container[ 0 ] === document.documentElement ) {
5626 viewportSpacing = OO.ui.getViewportSpacing();
5627 containerPos[ near ] += viewportSpacing[ near ];
5628 containerPos[ far ] -= viewportSpacing[ far ];
5629 }
5630 // Take into account how much the popup will move because of the adjustments we're going to make
5631 popupPos[ near ] += ( positionProp === near ? 1 : -1 ) * positionAdjustment;
5632 popupPos[ far ] += ( positionProp === near ? 1 : -1 ) * positionAdjustment;
5633 if ( containerPos[ near ] + this.containerPadding > popupPos[ near ] ) {
5634 // Popup goes beyond the near (left/top) edge, move it to the right/bottom
5635 positionAdjustment += ( positionProp === near ? 1 : -1 ) *
5636 ( containerPos[ near ] + this.containerPadding - popupPos[ near ] );
5637 } else if ( containerPos[ far ] - this.containerPadding < popupPos[ far ] ) {
5638 // Popup goes beyond the far (right/bottom) edge, move it to the left/top
5639 positionAdjustment += ( positionProp === far ? 1 : -1 ) *
5640 ( popupPos[ far ] - ( containerPos[ far ] - this.containerPadding ) );
5641 }
5642
5643 if ( this.anchored ) {
5644 // Adjust anchorOffset for positionAdjustment
5645 anchorOffset += ( positionProp === start ? -1 : 1 ) * positionAdjustment;
5646
5647 // Position the anchor
5648 anchorCss[ start ] = anchorOffset;
5649 this.$anchor.css( anchorCss );
5650 }
5651
5652 // Move the popup if needed
5653 parentPosition[ positionProp ] += positionAdjustment;
5654
5655 return parentPosition;
5656 };
5657
5658 /**
5659 * Set popup alignment
5660 *
5661 * @param {string} [align=center] Alignment of the popup, `center`, `force-left`, `force-right`,
5662 * `backwards` or `forwards`.
5663 */
5664 OO.ui.PopupWidget.prototype.setAlignment = function ( align ) {
5665 // Validate alignment
5666 if ( [ 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align ) > -1 ) {
5667 this.align = align;
5668 } else {
5669 this.align = 'center';
5670 }
5671 this.position();
5672 };
5673
5674 /**
5675 * Get popup alignment
5676 *
5677 * @return {string} Alignment of the popup, `center`, `force-left`, `force-right`,
5678 * `backwards` or `forwards`.
5679 */
5680 OO.ui.PopupWidget.prototype.getAlignment = function () {
5681 return this.align;
5682 };
5683
5684 /**
5685 * Change the positioning of the popup.
5686 *
5687 * @param {string} position 'above', 'below', 'before' or 'after'
5688 */
5689 OO.ui.PopupWidget.prototype.setPosition = function ( position ) {
5690 if ( [ 'above', 'below', 'before', 'after' ].indexOf( position ) === -1 ) {
5691 position = 'below';
5692 }
5693 this.popupPosition = position;
5694 this.position();
5695 };
5696
5697 /**
5698 * Get popup positioning.
5699 *
5700 * @return {string} 'above', 'below', 'before' or 'after'
5701 */
5702 OO.ui.PopupWidget.prototype.getPosition = function () {
5703 return this.popupPosition;
5704 };
5705
5706 /**
5707 * Set popup auto-flipping.
5708 *
5709 * @param {boolean} autoFlip Whether to automatically switch the popup's position between
5710 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5711 * desired direction to display the popup without clipping
5712 */
5713 OO.ui.PopupWidget.prototype.setAutoFlip = function ( autoFlip ) {
5714 autoFlip = !!autoFlip;
5715
5716 if ( this.autoFlip !== autoFlip ) {
5717 this.autoFlip = autoFlip;
5718 }
5719 };
5720
5721 /**
5722 * Get an ID of the body element, this can be used as the
5723 * `aria-describedby` attribute for an input field.
5724 *
5725 * @return {string} The ID of the body element
5726 */
5727 OO.ui.PopupWidget.prototype.getBodyId = function () {
5728 var id = this.$body.attr( 'id' );
5729 if ( id === undefined ) {
5730 id = OO.ui.generateElementId();
5731 this.$body.attr( 'id', id );
5732 }
5733 return id;
5734 };
5735
5736 /**
5737 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5738 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5739 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5740 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5741 *
5742 * @abstract
5743 * @class
5744 *
5745 * @constructor
5746 * @param {Object} [config] Configuration options
5747 * @cfg {Object} [popup] Configuration to pass to popup
5748 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5749 */
5750 OO.ui.mixin.PopupElement = function OoUiMixinPopupElement( config ) {
5751 // Configuration initialization
5752 config = config || {};
5753
5754 // Properties
5755 this.popup = new OO.ui.PopupWidget( $.extend(
5756 {
5757 autoClose: true,
5758 $floatableContainer: this.$element
5759 },
5760 config.popup,
5761 {
5762 $autoCloseIgnore: this.$element.add( config.popup && config.popup.$autoCloseIgnore )
5763 }
5764 ) );
5765 };
5766
5767 /* Methods */
5768
5769 /**
5770 * Get popup.
5771 *
5772 * @return {OO.ui.PopupWidget} Popup widget
5773 */
5774 OO.ui.mixin.PopupElement.prototype.getPopup = function () {
5775 return this.popup;
5776 };
5777
5778 /**
5779 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
5780 * which is used to display additional information or options.
5781 *
5782 * @example
5783 * // Example of a popup button.
5784 * var popupButton = new OO.ui.PopupButtonWidget( {
5785 * label: 'Popup button with options',
5786 * icon: 'menu',
5787 * popup: {
5788 * $content: $( '<p>Additional options here.</p>' ),
5789 * padded: true,
5790 * align: 'force-left'
5791 * }
5792 * } );
5793 * // Append the button to the DOM.
5794 * $( 'body' ).append( popupButton.$element );
5795 *
5796 * @class
5797 * @extends OO.ui.ButtonWidget
5798 * @mixins OO.ui.mixin.PopupElement
5799 *
5800 * @constructor
5801 * @param {Object} [config] Configuration options
5802 * @cfg {jQuery} [$overlay] Render the popup into a separate layer. This configuration is useful in cases where
5803 * the expanded popup is larger than its containing `<div>`. The specified overlay layer is usually on top of the
5804 * containing `<div>` and has a larger area. By default, the popup uses relative positioning.
5805 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
5806 */
5807 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
5808 // Configuration initialization
5809 config = config || {};
5810
5811 // Parent constructor
5812 OO.ui.PopupButtonWidget.parent.call( this, config );
5813
5814 // Mixin constructors
5815 OO.ui.mixin.PopupElement.call( this, config );
5816
5817 // Properties
5818 this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
5819
5820 // Events
5821 this.connect( this, { click: 'onAction' } );
5822
5823 // Initialization
5824 this.$element
5825 .addClass( 'oo-ui-popupButtonWidget' )
5826 .attr( 'aria-haspopup', 'true' );
5827 this.popup.$element
5828 .addClass( 'oo-ui-popupButtonWidget-popup' )
5829 .toggleClass( 'oo-ui-popupButtonWidget-framed-popup', this.isFramed() )
5830 .toggleClass( 'oo-ui-popupButtonWidget-frameless-popup', !this.isFramed() );
5831 this.$overlay.append( this.popup.$element );
5832 };
5833
5834 /* Setup */
5835
5836 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
5837 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.mixin.PopupElement );
5838
5839 /* Methods */
5840
5841 /**
5842 * Handle the button action being triggered.
5843 *
5844 * @private
5845 */
5846 OO.ui.PopupButtonWidget.prototype.onAction = function () {
5847 this.popup.toggle();
5848 };
5849
5850 /**
5851 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
5852 *
5853 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
5854 *
5855 * @private
5856 * @abstract
5857 * @class
5858 * @mixins OO.ui.mixin.GroupElement
5859 *
5860 * @constructor
5861 * @param {Object} [config] Configuration options
5862 */
5863 OO.ui.mixin.GroupWidget = function OoUiMixinGroupWidget( config ) {
5864 // Mixin constructors
5865 OO.ui.mixin.GroupElement.call( this, config );
5866 };
5867
5868 /* Setup */
5869
5870 OO.mixinClass( OO.ui.mixin.GroupWidget, OO.ui.mixin.GroupElement );
5871
5872 /* Methods */
5873
5874 /**
5875 * Set the disabled state of the widget.
5876 *
5877 * This will also update the disabled state of child widgets.
5878 *
5879 * @param {boolean} disabled Disable widget
5880 * @chainable
5881 */
5882 OO.ui.mixin.GroupWidget.prototype.setDisabled = function ( disabled ) {
5883 var i, len;
5884
5885 // Parent method
5886 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
5887 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
5888
5889 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
5890 if ( this.items ) {
5891 for ( i = 0, len = this.items.length; i < len; i++ ) {
5892 this.items[ i ].updateDisabled();
5893 }
5894 }
5895
5896 return this;
5897 };
5898
5899 /**
5900 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
5901 *
5902 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
5903 * allows bidirectional communication.
5904 *
5905 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
5906 *
5907 * @private
5908 * @abstract
5909 * @class
5910 *
5911 * @constructor
5912 */
5913 OO.ui.mixin.ItemWidget = function OoUiMixinItemWidget() {
5914 //
5915 };
5916
5917 /* Methods */
5918
5919 /**
5920 * Check if widget is disabled.
5921 *
5922 * Checks parent if present, making disabled state inheritable.
5923 *
5924 * @return {boolean} Widget is disabled
5925 */
5926 OO.ui.mixin.ItemWidget.prototype.isDisabled = function () {
5927 return this.disabled ||
5928 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
5929 };
5930
5931 /**
5932 * Set group element is in.
5933 *
5934 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
5935 * @chainable
5936 */
5937 OO.ui.mixin.ItemWidget.prototype.setElementGroup = function ( group ) {
5938 // Parent method
5939 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
5940 OO.ui.Element.prototype.setElementGroup.call( this, group );
5941
5942 // Initialize item disabled states
5943 this.updateDisabled();
5944
5945 return this;
5946 };
5947
5948 /**
5949 * OptionWidgets are special elements that can be selected and configured with data. The
5950 * data is often unique for each option, but it does not have to be. OptionWidgets are used
5951 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
5952 * and examples, please see the [OOUI documentation on MediaWiki][1].
5953 *
5954 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
5955 *
5956 * @class
5957 * @extends OO.ui.Widget
5958 * @mixins OO.ui.mixin.ItemWidget
5959 * @mixins OO.ui.mixin.LabelElement
5960 * @mixins OO.ui.mixin.FlaggedElement
5961 * @mixins OO.ui.mixin.AccessKeyedElement
5962 *
5963 * @constructor
5964 * @param {Object} [config] Configuration options
5965 */
5966 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
5967 // Configuration initialization
5968 config = config || {};
5969
5970 // Parent constructor
5971 OO.ui.OptionWidget.parent.call( this, config );
5972
5973 // Mixin constructors
5974 OO.ui.mixin.ItemWidget.call( this );
5975 OO.ui.mixin.LabelElement.call( this, config );
5976 OO.ui.mixin.FlaggedElement.call( this, config );
5977 OO.ui.mixin.AccessKeyedElement.call( this, config );
5978
5979 // Properties
5980 this.selected = false;
5981 this.highlighted = false;
5982 this.pressed = false;
5983
5984 // Initialization
5985 this.$element
5986 .data( 'oo-ui-optionWidget', this )
5987 // Allow programmatic focussing (and by accesskey), but not tabbing
5988 .attr( 'tabindex', '-1' )
5989 .attr( 'role', 'option' )
5990 .attr( 'aria-selected', 'false' )
5991 .addClass( 'oo-ui-optionWidget' )
5992 .append( this.$label );
5993 };
5994
5995 /* Setup */
5996
5997 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
5998 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.ItemWidget );
5999 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.LabelElement );
6000 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.FlaggedElement );
6001 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.AccessKeyedElement );
6002
6003 /* Static Properties */
6004
6005 /**
6006 * Whether this option can be selected. See #setSelected.
6007 *
6008 * @static
6009 * @inheritable
6010 * @property {boolean}
6011 */
6012 OO.ui.OptionWidget.static.selectable = true;
6013
6014 /**
6015 * Whether this option can be highlighted. See #setHighlighted.
6016 *
6017 * @static
6018 * @inheritable
6019 * @property {boolean}
6020 */
6021 OO.ui.OptionWidget.static.highlightable = true;
6022
6023 /**
6024 * Whether this option can be pressed. See #setPressed.
6025 *
6026 * @static
6027 * @inheritable
6028 * @property {boolean}
6029 */
6030 OO.ui.OptionWidget.static.pressable = true;
6031
6032 /**
6033 * Whether this option will be scrolled into view when it is selected.
6034 *
6035 * @static
6036 * @inheritable
6037 * @property {boolean}
6038 */
6039 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
6040
6041 /* Methods */
6042
6043 /**
6044 * Check if the option can be selected.
6045 *
6046 * @return {boolean} Item is selectable
6047 */
6048 OO.ui.OptionWidget.prototype.isSelectable = function () {
6049 return this.constructor.static.selectable && !this.disabled && this.isVisible();
6050 };
6051
6052 /**
6053 * Check if the option can be highlighted. A highlight indicates that the option
6054 * may be selected when a user presses enter or clicks. Disabled items cannot
6055 * be highlighted.
6056 *
6057 * @return {boolean} Item is highlightable
6058 */
6059 OO.ui.OptionWidget.prototype.isHighlightable = function () {
6060 return this.constructor.static.highlightable && !this.disabled && this.isVisible();
6061 };
6062
6063 /**
6064 * Check if the option can be pressed. The pressed state occurs when a user mouses
6065 * down on an item, but has not yet let go of the mouse.
6066 *
6067 * @return {boolean} Item is pressable
6068 */
6069 OO.ui.OptionWidget.prototype.isPressable = function () {
6070 return this.constructor.static.pressable && !this.disabled && this.isVisible();
6071 };
6072
6073 /**
6074 * Check if the option is selected.
6075 *
6076 * @return {boolean} Item is selected
6077 */
6078 OO.ui.OptionWidget.prototype.isSelected = function () {
6079 return this.selected;
6080 };
6081
6082 /**
6083 * Check if the option is highlighted. A highlight indicates that the
6084 * item may be selected when a user presses enter or clicks.
6085 *
6086 * @return {boolean} Item is highlighted
6087 */
6088 OO.ui.OptionWidget.prototype.isHighlighted = function () {
6089 return this.highlighted;
6090 };
6091
6092 /**
6093 * Check if the option is pressed. The pressed state occurs when a user mouses
6094 * down on an item, but has not yet let go of the mouse. The item may appear
6095 * selected, but it will not be selected until the user releases the mouse.
6096 *
6097 * @return {boolean} Item is pressed
6098 */
6099 OO.ui.OptionWidget.prototype.isPressed = function () {
6100 return this.pressed;
6101 };
6102
6103 /**
6104 * Set the option’s selected state. In general, all modifications to the selection
6105 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
6106 * method instead of this method.
6107 *
6108 * @param {boolean} [state=false] Select option
6109 * @chainable
6110 */
6111 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
6112 if ( this.constructor.static.selectable ) {
6113 this.selected = !!state;
6114 this.$element
6115 .toggleClass( 'oo-ui-optionWidget-selected', state )
6116 .attr( 'aria-selected', state.toString() );
6117 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
6118 this.scrollElementIntoView();
6119 }
6120 this.updateThemeClasses();
6121 }
6122 return this;
6123 };
6124
6125 /**
6126 * Set the option’s highlighted state. In general, all programmatic
6127 * modifications to the highlight should be handled by the
6128 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
6129 * method instead of this method.
6130 *
6131 * @param {boolean} [state=false] Highlight option
6132 * @chainable
6133 */
6134 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
6135 if ( this.constructor.static.highlightable ) {
6136 this.highlighted = !!state;
6137 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
6138 this.updateThemeClasses();
6139 }
6140 return this;
6141 };
6142
6143 /**
6144 * Set the option’s pressed state. In general, all
6145 * programmatic modifications to the pressed state should be handled by the
6146 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
6147 * method instead of this method.
6148 *
6149 * @param {boolean} [state=false] Press option
6150 * @chainable
6151 */
6152 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
6153 if ( this.constructor.static.pressable ) {
6154 this.pressed = !!state;
6155 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
6156 this.updateThemeClasses();
6157 }
6158 return this;
6159 };
6160
6161 /**
6162 * Get text to match search strings against.
6163 *
6164 * The default implementation returns the label text, but subclasses
6165 * can override this to provide more complex behavior.
6166 *
6167 * @return {string|boolean} String to match search string against
6168 */
6169 OO.ui.OptionWidget.prototype.getMatchText = function () {
6170 var label = this.getLabel();
6171 return typeof label === 'string' ? label : this.$label.text();
6172 };
6173
6174 /**
6175 * A SelectWidget is of a generic selection of options. The OOUI library contains several types of
6176 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
6177 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
6178 * menu selects}.
6179 *
6180 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
6181 * information, please see the [OOUI documentation on MediaWiki][1].
6182 *
6183 * @example
6184 * // Example of a select widget with three options
6185 * var select = new OO.ui.SelectWidget( {
6186 * items: [
6187 * new OO.ui.OptionWidget( {
6188 * data: 'a',
6189 * label: 'Option One',
6190 * } ),
6191 * new OO.ui.OptionWidget( {
6192 * data: 'b',
6193 * label: 'Option Two',
6194 * } ),
6195 * new OO.ui.OptionWidget( {
6196 * data: 'c',
6197 * label: 'Option Three',
6198 * } )
6199 * ]
6200 * } );
6201 * $( 'body' ).append( select.$element );
6202 *
6203 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6204 *
6205 * @abstract
6206 * @class
6207 * @extends OO.ui.Widget
6208 * @mixins OO.ui.mixin.GroupWidget
6209 *
6210 * @constructor
6211 * @param {Object} [config] Configuration options
6212 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
6213 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
6214 * the [OOUI documentation on MediaWiki] [2] for examples.
6215 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6216 */
6217 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
6218 // Configuration initialization
6219 config = config || {};
6220
6221 // Parent constructor
6222 OO.ui.SelectWidget.parent.call( this, config );
6223
6224 // Mixin constructors
6225 OO.ui.mixin.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
6226
6227 // Properties
6228 this.pressed = false;
6229 this.selecting = null;
6230 this.onMouseUpHandler = this.onMouseUp.bind( this );
6231 this.onMouseMoveHandler = this.onMouseMove.bind( this );
6232 this.onKeyDownHandler = this.onKeyDown.bind( this );
6233 this.onKeyPressHandler = this.onKeyPress.bind( this );
6234 this.keyPressBuffer = '';
6235 this.keyPressBufferTimer = null;
6236 this.blockMouseOverEvents = 0;
6237
6238 // Events
6239 this.connect( this, {
6240 toggle: 'onToggle'
6241 } );
6242 this.$element.on( {
6243 focusin: this.onFocus.bind( this ),
6244 mousedown: this.onMouseDown.bind( this ),
6245 mouseover: this.onMouseOver.bind( this ),
6246 mouseleave: this.onMouseLeave.bind( this )
6247 } );
6248
6249 // Initialization
6250 this.$element
6251 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
6252 .attr( 'role', 'listbox' );
6253 this.setFocusOwner( this.$element );
6254 if ( Array.isArray( config.items ) ) {
6255 this.addItems( config.items );
6256 }
6257 };
6258
6259 /* Setup */
6260
6261 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
6262 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupWidget );
6263
6264 /* Events */
6265
6266 /**
6267 * @event highlight
6268 *
6269 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
6270 *
6271 * @param {OO.ui.OptionWidget|null} item Highlighted item
6272 */
6273
6274 /**
6275 * @event press
6276 *
6277 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
6278 * pressed state of an option.
6279 *
6280 * @param {OO.ui.OptionWidget|null} item Pressed item
6281 */
6282
6283 /**
6284 * @event select
6285 *
6286 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
6287 *
6288 * @param {OO.ui.OptionWidget|null} item Selected item
6289 */
6290
6291 /**
6292 * @event choose
6293 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
6294 * @param {OO.ui.OptionWidget} item Chosen item
6295 */
6296
6297 /**
6298 * @event add
6299 *
6300 * An `add` event is emitted when options are added to the select with the #addItems method.
6301 *
6302 * @param {OO.ui.OptionWidget[]} items Added items
6303 * @param {number} index Index of insertion point
6304 */
6305
6306 /**
6307 * @event remove
6308 *
6309 * A `remove` event is emitted when options are removed from the select with the #clearItems
6310 * or #removeItems methods.
6311 *
6312 * @param {OO.ui.OptionWidget[]} items Removed items
6313 */
6314
6315 /* Methods */
6316
6317 /**
6318 * Handle focus events
6319 *
6320 * @private
6321 * @param {jQuery.Event} event
6322 */
6323 OO.ui.SelectWidget.prototype.onFocus = function ( event ) {
6324 var item;
6325 if ( event.target === this.$element[ 0 ] ) {
6326 // This widget was focussed, e.g. by the user tabbing to it.
6327 // The styles for focus state depend on one of the items being selected.
6328 if ( !this.findSelectedItem() ) {
6329 item = this.findFirstSelectableItem();
6330 }
6331 } else {
6332 if ( event.target.tabIndex === -1 ) {
6333 // One of the options got focussed (and the event bubbled up here).
6334 // They can't be tabbed to, but they can be activated using accesskeys.
6335 // OptionWidgets and focusable UI elements inside them have tabindex="-1" set.
6336 item = this.findTargetItem( event );
6337 } else {
6338 // There is something actually user-focusable in one of the labels of the options, and the
6339 // user focussed it (e.g. by tabbing to it). Do nothing (especially, don't change the focus).
6340 return;
6341 }
6342 }
6343
6344 if ( item ) {
6345 if ( item.constructor.static.highlightable ) {
6346 this.highlightItem( item );
6347 } else {
6348 this.selectItem( item );
6349 }
6350 }
6351
6352 if ( event.target !== this.$element[ 0 ] ) {
6353 this.$focusOwner.focus();
6354 }
6355 };
6356
6357 /**
6358 * Handle mouse down events.
6359 *
6360 * @private
6361 * @param {jQuery.Event} e Mouse down event
6362 */
6363 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
6364 var item;
6365
6366 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
6367 this.togglePressed( true );
6368 item = this.findTargetItem( e );
6369 if ( item && item.isSelectable() ) {
6370 this.pressItem( item );
6371 this.selecting = item;
6372 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true );
6373 this.getElementDocument().addEventListener( 'mousemove', this.onMouseMoveHandler, true );
6374 }
6375 }
6376 return false;
6377 };
6378
6379 /**
6380 * Handle mouse up events.
6381 *
6382 * @private
6383 * @param {MouseEvent} e Mouse up event
6384 */
6385 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
6386 var item;
6387
6388 this.togglePressed( false );
6389 if ( !this.selecting ) {
6390 item = this.findTargetItem( e );
6391 if ( item && item.isSelectable() ) {
6392 this.selecting = item;
6393 }
6394 }
6395 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT && this.selecting ) {
6396 this.pressItem( null );
6397 this.chooseItem( this.selecting );
6398 this.selecting = null;
6399 }
6400
6401 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true );
6402 this.getElementDocument().removeEventListener( 'mousemove', this.onMouseMoveHandler, true );
6403
6404 return false;
6405 };
6406
6407 /**
6408 * Handle mouse move events.
6409 *
6410 * @private
6411 * @param {MouseEvent} e Mouse move event
6412 */
6413 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
6414 var item;
6415
6416 if ( !this.isDisabled() && this.pressed ) {
6417 item = this.findTargetItem( e );
6418 if ( item && item !== this.selecting && item.isSelectable() ) {
6419 this.pressItem( item );
6420 this.selecting = item;
6421 }
6422 }
6423 };
6424
6425 /**
6426 * Handle mouse over events.
6427 *
6428 * @private
6429 * @param {jQuery.Event} e Mouse over event
6430 */
6431 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
6432 var item;
6433 if ( this.blockMouseOverEvents ) {
6434 return;
6435 }
6436 if ( !this.isDisabled() ) {
6437 item = this.findTargetItem( e );
6438 this.highlightItem( item && item.isHighlightable() ? item : null );
6439 }
6440 return false;
6441 };
6442
6443 /**
6444 * Handle mouse leave events.
6445 *
6446 * @private
6447 * @param {jQuery.Event} e Mouse over event
6448 */
6449 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
6450 if ( !this.isDisabled() ) {
6451 this.highlightItem( null );
6452 }
6453 return false;
6454 };
6455
6456 /**
6457 * Handle key down events.
6458 *
6459 * @protected
6460 * @param {KeyboardEvent} e Key down event
6461 */
6462 OO.ui.SelectWidget.prototype.onKeyDown = function ( e ) {
6463 var nextItem,
6464 handled = false,
6465 currentItem = this.findHighlightedItem() || this.findSelectedItem();
6466
6467 if ( !this.isDisabled() && this.isVisible() ) {
6468 switch ( e.keyCode ) {
6469 case OO.ui.Keys.ENTER:
6470 if ( currentItem && currentItem.constructor.static.highlightable ) {
6471 // Was only highlighted, now let's select it. No-op if already selected.
6472 this.chooseItem( currentItem );
6473 handled = true;
6474 }
6475 break;
6476 case OO.ui.Keys.UP:
6477 case OO.ui.Keys.LEFT:
6478 this.clearKeyPressBuffer();
6479 nextItem = this.findRelativeSelectableItem( currentItem, -1 );
6480 handled = true;
6481 break;
6482 case OO.ui.Keys.DOWN:
6483 case OO.ui.Keys.RIGHT:
6484 this.clearKeyPressBuffer();
6485 nextItem = this.findRelativeSelectableItem( currentItem, 1 );
6486 handled = true;
6487 break;
6488 case OO.ui.Keys.ESCAPE:
6489 case OO.ui.Keys.TAB:
6490 if ( currentItem && currentItem.constructor.static.highlightable ) {
6491 currentItem.setHighlighted( false );
6492 }
6493 this.unbindKeyDownListener();
6494 this.unbindKeyPressListener();
6495 // Don't prevent tabbing away / defocusing
6496 handled = false;
6497 break;
6498 }
6499
6500 if ( nextItem ) {
6501 if ( nextItem.constructor.static.highlightable ) {
6502 this.highlightItem( nextItem );
6503 } else {
6504 this.chooseItem( nextItem );
6505 }
6506 this.scrollItemIntoView( nextItem );
6507 }
6508
6509 if ( handled ) {
6510 e.preventDefault();
6511 e.stopPropagation();
6512 }
6513 }
6514 };
6515
6516 /**
6517 * Bind key down listener.
6518 *
6519 * @protected
6520 */
6521 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
6522 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler, true );
6523 };
6524
6525 /**
6526 * Unbind key down listener.
6527 *
6528 * @protected
6529 */
6530 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
6531 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler, true );
6532 };
6533
6534 /**
6535 * Scroll item into view, preventing spurious mouse highlight actions from happening.
6536 *
6537 * @param {OO.ui.OptionWidget} item Item to scroll into view
6538 */
6539 OO.ui.SelectWidget.prototype.scrollItemIntoView = function ( item ) {
6540 var widget = this;
6541 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling
6542 // and around 100-150 ms after it is finished.
6543 this.blockMouseOverEvents++;
6544 item.scrollElementIntoView().done( function () {
6545 setTimeout( function () {
6546 widget.blockMouseOverEvents--;
6547 }, 200 );
6548 } );
6549 };
6550
6551 /**
6552 * Clear the key-press buffer
6553 *
6554 * @protected
6555 */
6556 OO.ui.SelectWidget.prototype.clearKeyPressBuffer = function () {
6557 if ( this.keyPressBufferTimer ) {
6558 clearTimeout( this.keyPressBufferTimer );
6559 this.keyPressBufferTimer = null;
6560 }
6561 this.keyPressBuffer = '';
6562 };
6563
6564 /**
6565 * Handle key press events.
6566 *
6567 * @protected
6568 * @param {KeyboardEvent} e Key press event
6569 */
6570 OO.ui.SelectWidget.prototype.onKeyPress = function ( e ) {
6571 var c, filter, item;
6572
6573 if ( !e.charCode ) {
6574 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.keyPressBuffer !== '' ) {
6575 this.keyPressBuffer = this.keyPressBuffer.substr( 0, this.keyPressBuffer.length - 1 );
6576 return false;
6577 }
6578 return;
6579 }
6580 if ( String.fromCodePoint ) {
6581 c = String.fromCodePoint( e.charCode );
6582 } else {
6583 c = String.fromCharCode( e.charCode );
6584 }
6585
6586 if ( this.keyPressBufferTimer ) {
6587 clearTimeout( this.keyPressBufferTimer );
6588 }
6589 this.keyPressBufferTimer = setTimeout( this.clearKeyPressBuffer.bind( this ), 1500 );
6590
6591 item = this.findHighlightedItem() || this.findSelectedItem();
6592
6593 if ( this.keyPressBuffer === c ) {
6594 // Common (if weird) special case: typing "xxxx" will cycle through all
6595 // the items beginning with "x".
6596 if ( item ) {
6597 item = this.findRelativeSelectableItem( item, 1 );
6598 }
6599 } else {
6600 this.keyPressBuffer += c;
6601 }
6602
6603 filter = this.getItemMatcher( this.keyPressBuffer, false );
6604 if ( !item || !filter( item ) ) {
6605 item = this.findRelativeSelectableItem( item, 1, filter );
6606 }
6607 if ( item ) {
6608 if ( this.isVisible() && item.constructor.static.highlightable ) {
6609 this.highlightItem( item );
6610 } else {
6611 this.chooseItem( item );
6612 }
6613 this.scrollItemIntoView( item );
6614 }
6615
6616 e.preventDefault();
6617 e.stopPropagation();
6618 };
6619
6620 /**
6621 * Get a matcher for the specific string
6622 *
6623 * @protected
6624 * @param {string} s String to match against items
6625 * @param {boolean} [exact=false] Only accept exact matches
6626 * @return {Function} function ( OO.ui.OptionWidget ) => boolean
6627 */
6628 OO.ui.SelectWidget.prototype.getItemMatcher = function ( s, exact ) {
6629 var re;
6630
6631 if ( s.normalize ) {
6632 s = s.normalize();
6633 }
6634 s = exact ? s.trim() : s.replace( /^\s+/, '' );
6635 re = '^\\s*' + s.replace( /([\\{}()|.?*+\-^$[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
6636 if ( exact ) {
6637 re += '\\s*$';
6638 }
6639 re = new RegExp( re, 'i' );
6640 return function ( item ) {
6641 var matchText = item.getMatchText();
6642 if ( matchText.normalize ) {
6643 matchText = matchText.normalize();
6644 }
6645 return re.test( matchText );
6646 };
6647 };
6648
6649 /**
6650 * Bind key press listener.
6651 *
6652 * @protected
6653 */
6654 OO.ui.SelectWidget.prototype.bindKeyPressListener = function () {
6655 this.getElementWindow().addEventListener( 'keypress', this.onKeyPressHandler, true );
6656 };
6657
6658 /**
6659 * Unbind key down listener.
6660 *
6661 * If you override this, be sure to call this.clearKeyPressBuffer() from your
6662 * implementation.
6663 *
6664 * @protected
6665 */
6666 OO.ui.SelectWidget.prototype.unbindKeyPressListener = function () {
6667 this.getElementWindow().removeEventListener( 'keypress', this.onKeyPressHandler, true );
6668 this.clearKeyPressBuffer();
6669 };
6670
6671 /**
6672 * Visibility change handler
6673 *
6674 * @protected
6675 * @param {boolean} visible
6676 */
6677 OO.ui.SelectWidget.prototype.onToggle = function ( visible ) {
6678 if ( !visible ) {
6679 this.clearKeyPressBuffer();
6680 }
6681 };
6682
6683 /**
6684 * Get the closest item to a jQuery.Event.
6685 *
6686 * @private
6687 * @param {jQuery.Event} e
6688 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
6689 */
6690 OO.ui.SelectWidget.prototype.findTargetItem = function ( e ) {
6691 var $option = $( e.target ).closest( '.oo-ui-optionWidget' );
6692 if ( !$option.closest( '.oo-ui-selectWidget' ).is( this.$element ) ) {
6693 return null;
6694 }
6695 return $option.data( 'oo-ui-optionWidget' ) || null;
6696 };
6697
6698 /**
6699 * Find selected item.
6700 *
6701 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
6702 */
6703 OO.ui.SelectWidget.prototype.findSelectedItem = function () {
6704 var i, len;
6705
6706 for ( i = 0, len = this.items.length; i < len; i++ ) {
6707 if ( this.items[ i ].isSelected() ) {
6708 return this.items[ i ];
6709 }
6710 }
6711 return null;
6712 };
6713
6714 /**
6715 * Find highlighted item.
6716 *
6717 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
6718 */
6719 OO.ui.SelectWidget.prototype.findHighlightedItem = function () {
6720 var i, len;
6721
6722 for ( i = 0, len = this.items.length; i < len; i++ ) {
6723 if ( this.items[ i ].isHighlighted() ) {
6724 return this.items[ i ];
6725 }
6726 }
6727 return null;
6728 };
6729
6730 /**
6731 * Toggle pressed state.
6732 *
6733 * Press is a state that occurs when a user mouses down on an item, but
6734 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
6735 * until the user releases the mouse.
6736 *
6737 * @param {boolean} pressed An option is being pressed
6738 */
6739 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
6740 if ( pressed === undefined ) {
6741 pressed = !this.pressed;
6742 }
6743 if ( pressed !== this.pressed ) {
6744 this.$element
6745 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
6746 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
6747 this.pressed = pressed;
6748 }
6749 };
6750
6751 /**
6752 * Highlight an option. If the `item` param is omitted, no options will be highlighted
6753 * and any existing highlight will be removed. The highlight is mutually exclusive.
6754 *
6755 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
6756 * @fires highlight
6757 * @chainable
6758 */
6759 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
6760 var i, len, highlighted,
6761 changed = false;
6762
6763 for ( i = 0, len = this.items.length; i < len; i++ ) {
6764 highlighted = this.items[ i ] === item;
6765 if ( this.items[ i ].isHighlighted() !== highlighted ) {
6766 this.items[ i ].setHighlighted( highlighted );
6767 changed = true;
6768 }
6769 }
6770 if ( changed ) {
6771 if ( item ) {
6772 this.$focusOwner.attr( 'aria-activedescendant', item.getElementId() );
6773 } else {
6774 this.$focusOwner.removeAttr( 'aria-activedescendant' );
6775 }
6776 this.emit( 'highlight', item );
6777 }
6778
6779 return this;
6780 };
6781
6782 /**
6783 * Fetch an item by its label.
6784 *
6785 * @param {string} label Label of the item to select.
6786 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
6787 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
6788 */
6789 OO.ui.SelectWidget.prototype.getItemFromLabel = function ( label, prefix ) {
6790 var i, item, found,
6791 len = this.items.length,
6792 filter = this.getItemMatcher( label, true );
6793
6794 for ( i = 0; i < len; i++ ) {
6795 item = this.items[ i ];
6796 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
6797 return item;
6798 }
6799 }
6800
6801 if ( prefix ) {
6802 found = null;
6803 filter = this.getItemMatcher( label, false );
6804 for ( i = 0; i < len; i++ ) {
6805 item = this.items[ i ];
6806 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
6807 if ( found ) {
6808 return null;
6809 }
6810 found = item;
6811 }
6812 }
6813 if ( found ) {
6814 return found;
6815 }
6816 }
6817
6818 return null;
6819 };
6820
6821 /**
6822 * Programmatically select an option by its label. If the item does not exist,
6823 * all options will be deselected.
6824 *
6825 * @param {string} [label] Label of the item to select.
6826 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
6827 * @fires select
6828 * @chainable
6829 */
6830 OO.ui.SelectWidget.prototype.selectItemByLabel = function ( label, prefix ) {
6831 var itemFromLabel = this.getItemFromLabel( label, !!prefix );
6832 if ( label === undefined || !itemFromLabel ) {
6833 return this.selectItem();
6834 }
6835 return this.selectItem( itemFromLabel );
6836 };
6837
6838 /**
6839 * Programmatically select an option by its data. If the `data` parameter is omitted,
6840 * or if the item does not exist, all options will be deselected.
6841 *
6842 * @param {Object|string} [data] Value of the item to select, omit to deselect all
6843 * @fires select
6844 * @chainable
6845 */
6846 OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) {
6847 var itemFromData = this.findItemFromData( data );
6848 if ( data === undefined || !itemFromData ) {
6849 return this.selectItem();
6850 }
6851 return this.selectItem( itemFromData );
6852 };
6853
6854 /**
6855 * Programmatically select an option by its reference. If the `item` parameter is omitted,
6856 * all options will be deselected.
6857 *
6858 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
6859 * @fires select
6860 * @chainable
6861 */
6862 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
6863 var i, len, selected,
6864 changed = false;
6865
6866 for ( i = 0, len = this.items.length; i < len; i++ ) {
6867 selected = this.items[ i ] === item;
6868 if ( this.items[ i ].isSelected() !== selected ) {
6869 this.items[ i ].setSelected( selected );
6870 changed = true;
6871 }
6872 }
6873 if ( changed ) {
6874 if ( item && !item.constructor.static.highlightable ) {
6875 if ( item ) {
6876 this.$focusOwner.attr( 'aria-activedescendant', item.getElementId() );
6877 } else {
6878 this.$focusOwner.removeAttr( 'aria-activedescendant' );
6879 }
6880 }
6881 this.emit( 'select', item );
6882 }
6883
6884 return this;
6885 };
6886
6887 /**
6888 * Press an item.
6889 *
6890 * Press is a state that occurs when a user mouses down on an item, but has not
6891 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
6892 * releases the mouse.
6893 *
6894 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
6895 * @fires press
6896 * @chainable
6897 */
6898 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
6899 var i, len, pressed,
6900 changed = false;
6901
6902 for ( i = 0, len = this.items.length; i < len; i++ ) {
6903 pressed = this.items[ i ] === item;
6904 if ( this.items[ i ].isPressed() !== pressed ) {
6905 this.items[ i ].setPressed( pressed );
6906 changed = true;
6907 }
6908 }
6909 if ( changed ) {
6910 this.emit( 'press', item );
6911 }
6912
6913 return this;
6914 };
6915
6916 /**
6917 * Choose an item.
6918 *
6919 * Note that ‘choose’ should never be modified programmatically. A user can choose
6920 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
6921 * use the #selectItem method.
6922 *
6923 * This method is identical to #selectItem, but may vary in subclasses that take additional action
6924 * when users choose an item with the keyboard or mouse.
6925 *
6926 * @param {OO.ui.OptionWidget} item Item to choose
6927 * @fires choose
6928 * @chainable
6929 */
6930 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
6931 if ( item ) {
6932 this.selectItem( item );
6933 this.emit( 'choose', item );
6934 }
6935
6936 return this;
6937 };
6938
6939 /**
6940 * Find an option by its position relative to the specified item (or to the start of the option array,
6941 * if item is `null`). The direction in which to search through the option array is specified with a
6942 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
6943 * `null` if there are no options in the array.
6944 *
6945 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
6946 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
6947 * @param {Function} [filter] Only consider items for which this function returns
6948 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
6949 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
6950 */
6951 OO.ui.SelectWidget.prototype.findRelativeSelectableItem = function ( item, direction, filter ) {
6952 var currentIndex, nextIndex, i,
6953 increase = direction > 0 ? 1 : -1,
6954 len = this.items.length;
6955
6956 if ( item instanceof OO.ui.OptionWidget ) {
6957 currentIndex = this.items.indexOf( item );
6958 nextIndex = ( currentIndex + increase + len ) % len;
6959 } else {
6960 // If no item is selected and moving forward, start at the beginning.
6961 // If moving backward, start at the end.
6962 nextIndex = direction > 0 ? 0 : len - 1;
6963 }
6964
6965 for ( i = 0; i < len; i++ ) {
6966 item = this.items[ nextIndex ];
6967 if (
6968 item instanceof OO.ui.OptionWidget && item.isSelectable() &&
6969 ( !filter || filter( item ) )
6970 ) {
6971 return item;
6972 }
6973 nextIndex = ( nextIndex + increase + len ) % len;
6974 }
6975 return null;
6976 };
6977
6978 /**
6979 * Find the next selectable item or `null` if there are no selectable items.
6980 * Disabled options and menu-section markers and breaks are not selectable.
6981 *
6982 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
6983 */
6984 OO.ui.SelectWidget.prototype.findFirstSelectableItem = function () {
6985 return this.findRelativeSelectableItem( null, 1 );
6986 };
6987
6988 /**
6989 * Add an array of options to the select. Optionally, an index number can be used to
6990 * specify an insertion point.
6991 *
6992 * @param {OO.ui.OptionWidget[]} items Items to add
6993 * @param {number} [index] Index to insert items after
6994 * @fires add
6995 * @chainable
6996 */
6997 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
6998 // Mixin method
6999 OO.ui.mixin.GroupWidget.prototype.addItems.call( this, items, index );
7000
7001 // Always provide an index, even if it was omitted
7002 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
7003
7004 return this;
7005 };
7006
7007 /**
7008 * Remove the specified array of options from the select. Options will be detached
7009 * from the DOM, not removed, so they can be reused later. To remove all options from
7010 * the select, you may wish to use the #clearItems method instead.
7011 *
7012 * @param {OO.ui.OptionWidget[]} items Items to remove
7013 * @fires remove
7014 * @chainable
7015 */
7016 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
7017 var i, len, item;
7018
7019 // Deselect items being removed
7020 for ( i = 0, len = items.length; i < len; i++ ) {
7021 item = items[ i ];
7022 if ( item.isSelected() ) {
7023 this.selectItem( null );
7024 }
7025 }
7026
7027 // Mixin method
7028 OO.ui.mixin.GroupWidget.prototype.removeItems.call( this, items );
7029
7030 this.emit( 'remove', items );
7031
7032 return this;
7033 };
7034
7035 /**
7036 * Clear all options from the select. Options will be detached from the DOM, not removed,
7037 * so that they can be reused later. To remove a subset of options from the select, use
7038 * the #removeItems method.
7039 *
7040 * @fires remove
7041 * @chainable
7042 */
7043 OO.ui.SelectWidget.prototype.clearItems = function () {
7044 var items = this.items.slice();
7045
7046 // Mixin method
7047 OO.ui.mixin.GroupWidget.prototype.clearItems.call( this );
7048
7049 // Clear selection
7050 this.selectItem( null );
7051
7052 this.emit( 'remove', items );
7053
7054 return this;
7055 };
7056
7057 /**
7058 * Set the DOM element which has focus while the user is interacting with this SelectWidget.
7059 *
7060 * Currently this is just used to set `aria-activedescendant` on it.
7061 *
7062 * @protected
7063 * @param {jQuery} $focusOwner
7064 */
7065 OO.ui.SelectWidget.prototype.setFocusOwner = function ( $focusOwner ) {
7066 this.$focusOwner = $focusOwner;
7067 };
7068
7069 /**
7070 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
7071 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
7072 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
7073 * options. For more information about options and selects, please see the
7074 * [OOUI documentation on MediaWiki][1].
7075 *
7076 * @example
7077 * // Decorated options in a select widget
7078 * var select = new OO.ui.SelectWidget( {
7079 * items: [
7080 * new OO.ui.DecoratedOptionWidget( {
7081 * data: 'a',
7082 * label: 'Option with icon',
7083 * icon: 'help'
7084 * } ),
7085 * new OO.ui.DecoratedOptionWidget( {
7086 * data: 'b',
7087 * label: 'Option with indicator',
7088 * indicator: 'next'
7089 * } )
7090 * ]
7091 * } );
7092 * $( 'body' ).append( select.$element );
7093 *
7094 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7095 *
7096 * @class
7097 * @extends OO.ui.OptionWidget
7098 * @mixins OO.ui.mixin.IconElement
7099 * @mixins OO.ui.mixin.IndicatorElement
7100 *
7101 * @constructor
7102 * @param {Object} [config] Configuration options
7103 */
7104 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
7105 // Parent constructor
7106 OO.ui.DecoratedOptionWidget.parent.call( this, config );
7107
7108 // Mixin constructors
7109 OO.ui.mixin.IconElement.call( this, config );
7110 OO.ui.mixin.IndicatorElement.call( this, config );
7111
7112 // Initialization
7113 this.$element
7114 .addClass( 'oo-ui-decoratedOptionWidget' )
7115 .prepend( this.$icon )
7116 .append( this.$indicator );
7117 };
7118
7119 /* Setup */
7120
7121 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
7122 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IconElement );
7123 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IndicatorElement );
7124
7125 /**
7126 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
7127 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
7128 * the [OOUI documentation on MediaWiki] [1] for more information.
7129 *
7130 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
7131 *
7132 * @class
7133 * @extends OO.ui.DecoratedOptionWidget
7134 *
7135 * @constructor
7136 * @param {Object} [config] Configuration options
7137 */
7138 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
7139 // Parent constructor
7140 OO.ui.MenuOptionWidget.parent.call( this, config );
7141
7142 // Properties
7143 this.checkIcon = new OO.ui.IconWidget( {
7144 icon: 'check',
7145 classes: [ 'oo-ui-menuOptionWidget-checkIcon' ]
7146 } );
7147
7148 // Initialization
7149 this.$element
7150 .prepend( this.checkIcon.$element )
7151 .addClass( 'oo-ui-menuOptionWidget' );
7152 };
7153
7154 /* Setup */
7155
7156 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
7157
7158 /* Static Properties */
7159
7160 /**
7161 * @static
7162 * @inheritdoc
7163 */
7164 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
7165
7166 /**
7167 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
7168 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
7169 *
7170 * @example
7171 * var myDropdown = new OO.ui.DropdownWidget( {
7172 * menu: {
7173 * items: [
7174 * new OO.ui.MenuSectionOptionWidget( {
7175 * label: 'Dogs'
7176 * } ),
7177 * new OO.ui.MenuOptionWidget( {
7178 * data: 'corgi',
7179 * label: 'Welsh Corgi'
7180 * } ),
7181 * new OO.ui.MenuOptionWidget( {
7182 * data: 'poodle',
7183 * label: 'Standard Poodle'
7184 * } ),
7185 * new OO.ui.MenuSectionOptionWidget( {
7186 * label: 'Cats'
7187 * } ),
7188 * new OO.ui.MenuOptionWidget( {
7189 * data: 'lion',
7190 * label: 'Lion'
7191 * } )
7192 * ]
7193 * }
7194 * } );
7195 * $( 'body' ).append( myDropdown.$element );
7196 *
7197 * @class
7198 * @extends OO.ui.DecoratedOptionWidget
7199 *
7200 * @constructor
7201 * @param {Object} [config] Configuration options
7202 */
7203 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
7204 // Parent constructor
7205 OO.ui.MenuSectionOptionWidget.parent.call( this, config );
7206
7207 // Initialization
7208 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' )
7209 .removeAttr( 'role aria-selected' );
7210 };
7211
7212 /* Setup */
7213
7214 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
7215
7216 /* Static Properties */
7217
7218 /**
7219 * @static
7220 * @inheritdoc
7221 */
7222 OO.ui.MenuSectionOptionWidget.static.selectable = false;
7223
7224 /**
7225 * @static
7226 * @inheritdoc
7227 */
7228 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
7229
7230 /**
7231 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
7232 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
7233 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
7234 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
7235 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
7236 * and customized to be opened, closed, and displayed as needed.
7237 *
7238 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
7239 * mouse outside the menu.
7240 *
7241 * Menus also have support for keyboard interaction:
7242 *
7243 * - Enter/Return key: choose and select a menu option
7244 * - Up-arrow key: highlight the previous menu option
7245 * - Down-arrow key: highlight the next menu option
7246 * - Esc key: hide the menu
7247 *
7248 * Unlike most widgets, MenuSelectWidget is initially hidden and must be shown by calling #toggle.
7249 *
7250 * Please see the [OOUI documentation on MediaWiki][1] for more information.
7251 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7252 *
7253 * @class
7254 * @extends OO.ui.SelectWidget
7255 * @mixins OO.ui.mixin.ClippableElement
7256 * @mixins OO.ui.mixin.FloatableElement
7257 *
7258 * @constructor
7259 * @param {Object} [config] Configuration options
7260 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
7261 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
7262 * and {@link OO.ui.mixin.LookupElement LookupElement}
7263 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
7264 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiselectWidget CapsuleMultiselectWidget}
7265 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
7266 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
7267 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
7268 * that button, unless the button (or its parent widget) is passed in here.
7269 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
7270 * @cfg {jQuery} [$autoCloseIgnore] If these elements are clicked, don't auto-hide the menu.
7271 * @cfg {boolean} [hideOnChoose=true] Hide the menu when the user chooses an option.
7272 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
7273 * @cfg {boolean} [highlightOnFilter] Highlight the first result when filtering
7274 * @cfg {number} [width] Width of the menu
7275 */
7276 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
7277 // Configuration initialization
7278 config = config || {};
7279
7280 // Parent constructor
7281 OO.ui.MenuSelectWidget.parent.call( this, config );
7282
7283 // Mixin constructors
7284 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
7285 OO.ui.mixin.FloatableElement.call( this, config );
7286
7287 // Initial vertical positions other than 'center' will result in
7288 // the menu being flipped if there is not enough space in the container.
7289 // Store the original position so we know what to reset to.
7290 this.originalVerticalPosition = this.verticalPosition;
7291
7292 // Properties
7293 this.autoHide = config.autoHide === undefined || !!config.autoHide;
7294 this.hideOnChoose = config.hideOnChoose === undefined || !!config.hideOnChoose;
7295 this.filterFromInput = !!config.filterFromInput;
7296 this.$input = config.$input ? config.$input : config.input ? config.input.$input : null;
7297 this.$widget = config.widget ? config.widget.$element : null;
7298 this.$autoCloseIgnore = config.$autoCloseIgnore || $( [] );
7299 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
7300 this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 );
7301 this.highlightOnFilter = !!config.highlightOnFilter;
7302 this.width = config.width;
7303
7304 // Initialization
7305 this.$element.addClass( 'oo-ui-menuSelectWidget' );
7306 if ( config.widget ) {
7307 this.setFocusOwner( config.widget.$tabIndexed );
7308 }
7309
7310 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
7311 // that reference properties not initialized at that time of parent class construction
7312 // TODO: Find a better way to handle post-constructor setup
7313 this.visible = false;
7314 this.$element.addClass( 'oo-ui-element-hidden' );
7315 };
7316
7317 /* Setup */
7318
7319 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
7320 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement );
7321 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.FloatableElement );
7322
7323 /* Events */
7324
7325 /**
7326 * @event ready
7327 *
7328 * The menu is ready: it is visible and has been positioned and clipped.
7329 */
7330
7331 /* Static properties */
7332
7333 /**
7334 * Positions to flip to if there isn't room in the container for the
7335 * menu in a specific direction.
7336 *
7337 * @property {Object.<string,string>}
7338 */
7339 OO.ui.MenuSelectWidget.static.flippedPositions = {
7340 below: 'above',
7341 above: 'below',
7342 top: 'bottom',
7343 bottom: 'top'
7344 };
7345
7346 /* Methods */
7347
7348 /**
7349 * Handles document mouse down events.
7350 *
7351 * @protected
7352 * @param {MouseEvent} e Mouse down event
7353 */
7354 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
7355 if (
7356 this.isVisible() &&
7357 !OO.ui.contains(
7358 this.$element.add( this.$widget ).add( this.$autoCloseIgnore ).get(),
7359 e.target,
7360 true
7361 )
7362 ) {
7363 this.toggle( false );
7364 }
7365 };
7366
7367 /**
7368 * @inheritdoc
7369 */
7370 OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
7371 var currentItem = this.findHighlightedItem() || this.findSelectedItem();
7372
7373 if ( !this.isDisabled() && this.isVisible() ) {
7374 switch ( e.keyCode ) {
7375 case OO.ui.Keys.LEFT:
7376 case OO.ui.Keys.RIGHT:
7377 // Do nothing if a text field is associated, arrow keys will be handled natively
7378 if ( !this.$input ) {
7379 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
7380 }
7381 break;
7382 case OO.ui.Keys.ESCAPE:
7383 case OO.ui.Keys.TAB:
7384 if ( currentItem ) {
7385 currentItem.setHighlighted( false );
7386 }
7387 this.toggle( false );
7388 // Don't prevent tabbing away, prevent defocusing
7389 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
7390 e.preventDefault();
7391 e.stopPropagation();
7392 }
7393 break;
7394 default:
7395 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
7396 return;
7397 }
7398 }
7399 };
7400
7401 /**
7402 * Update menu item visibility and clipping after input changes (if filterFromInput is enabled)
7403 * or after items were added/removed (always).
7404 *
7405 * @protected
7406 */
7407 OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () {
7408 var i, item, visible, section, sectionEmpty, filter, exactFilter,
7409 firstItemFound = false,
7410 anyVisible = false,
7411 len = this.items.length,
7412 showAll = !this.isVisible(),
7413 exactMatch = false;
7414
7415 if ( this.$input && this.filterFromInput ) {
7416 filter = showAll ? null : this.getItemMatcher( this.$input.val() );
7417 exactFilter = this.getItemMatcher( this.$input.val(), true );
7418
7419 // Hide non-matching options, and also hide section headers if all options
7420 // in their section are hidden.
7421 for ( i = 0; i < len; i++ ) {
7422 item = this.items[ i ];
7423 if ( item instanceof OO.ui.MenuSectionOptionWidget ) {
7424 if ( section ) {
7425 // If the previous section was empty, hide its header
7426 section.toggle( showAll || !sectionEmpty );
7427 }
7428 section = item;
7429 sectionEmpty = true;
7430 } else if ( item instanceof OO.ui.OptionWidget ) {
7431 visible = showAll || filter( item );
7432 exactMatch = exactMatch || exactFilter( item );
7433 anyVisible = anyVisible || visible;
7434 sectionEmpty = sectionEmpty && !visible;
7435 item.toggle( visible );
7436 if ( this.highlightOnFilter && visible && !firstItemFound ) {
7437 // Highlight the first item in the list
7438 this.highlightItem( item );
7439 firstItemFound = true;
7440 }
7441 }
7442 }
7443 // Process the final section
7444 if ( section ) {
7445 section.toggle( showAll || !sectionEmpty );
7446 }
7447
7448 if ( anyVisible && this.items.length && !exactMatch ) {
7449 this.scrollItemIntoView( this.items[ 0 ] );
7450 }
7451
7452 this.$element.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible );
7453 }
7454
7455 // Reevaluate clipping
7456 this.clip();
7457 };
7458
7459 /**
7460 * @inheritdoc
7461 */
7462 OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
7463 if ( this.$input ) {
7464 this.$input.on( 'keydown', this.onKeyDownHandler );
7465 } else {
7466 OO.ui.MenuSelectWidget.parent.prototype.bindKeyDownListener.call( this );
7467 }
7468 };
7469
7470 /**
7471 * @inheritdoc
7472 */
7473 OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
7474 if ( this.$input ) {
7475 this.$input.off( 'keydown', this.onKeyDownHandler );
7476 } else {
7477 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyDownListener.call( this );
7478 }
7479 };
7480
7481 /**
7482 * @inheritdoc
7483 */
7484 OO.ui.MenuSelectWidget.prototype.bindKeyPressListener = function () {
7485 if ( this.$input ) {
7486 if ( this.filterFromInput ) {
7487 this.$input.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
7488 this.updateItemVisibility();
7489 }
7490 } else {
7491 OO.ui.MenuSelectWidget.parent.prototype.bindKeyPressListener.call( this );
7492 }
7493 };
7494
7495 /**
7496 * @inheritdoc
7497 */
7498 OO.ui.MenuSelectWidget.prototype.unbindKeyPressListener = function () {
7499 if ( this.$input ) {
7500 if ( this.filterFromInput ) {
7501 this.$input.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
7502 this.updateItemVisibility();
7503 }
7504 } else {
7505 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyPressListener.call( this );
7506 }
7507 };
7508
7509 /**
7510 * Choose an item.
7511 *
7512 * When a user chooses an item, the menu is closed, unless the hideOnChoose config option is set to false.
7513 *
7514 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
7515 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
7516 *
7517 * @param {OO.ui.OptionWidget} item Item to choose
7518 * @chainable
7519 */
7520 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
7521 OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item );
7522 if ( this.hideOnChoose ) {
7523 this.toggle( false );
7524 }
7525 return this;
7526 };
7527
7528 /**
7529 * @inheritdoc
7530 */
7531 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
7532 // Parent method
7533 OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index );
7534
7535 this.updateItemVisibility();
7536
7537 return this;
7538 };
7539
7540 /**
7541 * @inheritdoc
7542 */
7543 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
7544 // Parent method
7545 OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items );
7546
7547 this.updateItemVisibility();
7548
7549 return this;
7550 };
7551
7552 /**
7553 * @inheritdoc
7554 */
7555 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
7556 // Parent method
7557 OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this );
7558
7559 this.updateItemVisibility();
7560
7561 return this;
7562 };
7563
7564 /**
7565 * Toggle visibility of the menu. The menu is initially hidden and must be shown by calling
7566 * `.toggle( true )` after its #$element is attached to the DOM.
7567 *
7568 * Do not show the menu while it is not attached to the DOM. The calculations required to display
7569 * it in the right place and with the right dimensions only work correctly while it is attached.
7570 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
7571 * strictly enforced, so currently it only generates a warning in the browser console.
7572 *
7573 * @fires ready
7574 * @inheritdoc
7575 */
7576 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
7577 var change, originalHeight, flippedHeight;
7578
7579 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
7580 change = visible !== this.isVisible();
7581
7582 if ( visible && !this.warnedUnattached && !this.isElementAttached() ) {
7583 OO.ui.warnDeprecation( 'MenuSelectWidget#toggle: Before calling this method, the menu must be attached to the DOM.' );
7584 this.warnedUnattached = true;
7585 }
7586
7587 if ( change && visible ) {
7588 // Reset position before showing the popup again. It's possible we no longer need to flip
7589 // (e.g. if the user scrolled).
7590 this.setVerticalPosition( this.originalVerticalPosition );
7591 }
7592
7593 // Parent method
7594 OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible );
7595
7596 if ( change ) {
7597 if ( visible ) {
7598
7599 if ( this.width ) {
7600 this.setIdealSize( this.width );
7601 } else if ( this.$floatableContainer ) {
7602 this.$clippable.css( 'width', 'auto' );
7603 this.setIdealSize(
7604 this.$floatableContainer[ 0 ].offsetWidth > this.$clippable[ 0 ].offsetWidth ?
7605 // Dropdown is smaller than handle so expand to width
7606 this.$floatableContainer[ 0 ].offsetWidth :
7607 // Dropdown is larger than handle so auto size
7608 'auto'
7609 );
7610 this.$clippable.css( 'width', '' );
7611 }
7612
7613 this.togglePositioning( !!this.$floatableContainer );
7614 this.toggleClipping( true );
7615
7616 this.bindKeyDownListener();
7617 this.bindKeyPressListener();
7618
7619 if (
7620 ( this.isClippedVertically() || this.isFloatableOutOfView() ) &&
7621 this.originalVerticalPosition !== 'center'
7622 ) {
7623 // If opening the menu in one direction causes it to be clipped, flip it
7624 originalHeight = this.$element.height();
7625 this.setVerticalPosition(
7626 this.constructor.static.flippedPositions[ this.originalVerticalPosition ]
7627 );
7628 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
7629 // If flipping also causes it to be clipped, open in whichever direction
7630 // we have more space
7631 flippedHeight = this.$element.height();
7632 if ( originalHeight > flippedHeight ) {
7633 this.setVerticalPosition( this.originalVerticalPosition );
7634 }
7635 }
7636 }
7637 // Note that we do not flip the menu's opening direction if the clipping changes
7638 // later (e.g. after the user scrolls), that seems like it would be annoying
7639
7640 this.$focusOwner.attr( 'aria-expanded', 'true' );
7641
7642 if ( this.findSelectedItem() ) {
7643 this.$focusOwner.attr( 'aria-activedescendant', this.findSelectedItem().getElementId() );
7644 this.findSelectedItem().scrollElementIntoView( { duration: 0 } );
7645 }
7646
7647 // Auto-hide
7648 if ( this.autoHide ) {
7649 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
7650 }
7651
7652 this.emit( 'ready' );
7653 } else {
7654 this.$focusOwner.removeAttr( 'aria-activedescendant' );
7655 this.unbindKeyDownListener();
7656 this.unbindKeyPressListener();
7657 this.$focusOwner.attr( 'aria-expanded', 'false' );
7658 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
7659 this.togglePositioning( false );
7660 this.toggleClipping( false );
7661 }
7662 }
7663
7664 return this;
7665 };
7666
7667 /**
7668 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
7669 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
7670 * users can interact with it.
7671 *
7672 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7673 * OO.ui.DropdownInputWidget instead.
7674 *
7675 * @example
7676 * // Example: A DropdownWidget with a menu that contains three options
7677 * var dropDown = new OO.ui.DropdownWidget( {
7678 * label: 'Dropdown menu: Select a menu option',
7679 * menu: {
7680 * items: [
7681 * new OO.ui.MenuOptionWidget( {
7682 * data: 'a',
7683 * label: 'First'
7684 * } ),
7685 * new OO.ui.MenuOptionWidget( {
7686 * data: 'b',
7687 * label: 'Second'
7688 * } ),
7689 * new OO.ui.MenuOptionWidget( {
7690 * data: 'c',
7691 * label: 'Third'
7692 * } )
7693 * ]
7694 * }
7695 * } );
7696 *
7697 * $( 'body' ).append( dropDown.$element );
7698 *
7699 * dropDown.getMenu().selectItemByData( 'b' );
7700 *
7701 * dropDown.getMenu().findSelectedItem().getData(); // returns 'b'
7702 *
7703 * For more information, please see the [OOUI documentation on MediaWiki] [1].
7704 *
7705 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
7706 *
7707 * @class
7708 * @extends OO.ui.Widget
7709 * @mixins OO.ui.mixin.IconElement
7710 * @mixins OO.ui.mixin.IndicatorElement
7711 * @mixins OO.ui.mixin.LabelElement
7712 * @mixins OO.ui.mixin.TitledElement
7713 * @mixins OO.ui.mixin.TabIndexedElement
7714 *
7715 * @constructor
7716 * @param {Object} [config] Configuration options
7717 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.MenuSelectWidget menu select widget}
7718 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
7719 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
7720 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
7721 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
7722 */
7723 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
7724 // Configuration initialization
7725 config = $.extend( { indicator: 'down' }, config );
7726
7727 // Parent constructor
7728 OO.ui.DropdownWidget.parent.call( this, config );
7729
7730 // Properties (must be set before TabIndexedElement constructor call)
7731 this.$handle = $( '<span>' );
7732 this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
7733
7734 // Mixin constructors
7735 OO.ui.mixin.IconElement.call( this, config );
7736 OO.ui.mixin.IndicatorElement.call( this, config );
7737 OO.ui.mixin.LabelElement.call( this, config );
7738 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
7739 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
7740
7741 // Properties
7742 this.menu = new OO.ui.MenuSelectWidget( $.extend( {
7743 widget: this,
7744 $floatableContainer: this.$element
7745 }, config.menu ) );
7746
7747 // Events
7748 this.$handle.on( {
7749 click: this.onClick.bind( this ),
7750 keydown: this.onKeyDown.bind( this ),
7751 // Hack? Handle type-to-search when menu is not expanded and not handling its own events
7752 keypress: this.menu.onKeyPressHandler,
7753 blur: this.menu.clearKeyPressBuffer.bind( this.menu )
7754 } );
7755 this.menu.connect( this, {
7756 select: 'onMenuSelect',
7757 toggle: 'onMenuToggle'
7758 } );
7759
7760 // Initialization
7761 this.$handle
7762 .addClass( 'oo-ui-dropdownWidget-handle' )
7763 .attr( {
7764 role: 'combobox',
7765 'aria-owns': this.menu.getElementId(),
7766 'aria-autocomplete': 'list'
7767 } )
7768 .append( this.$icon, this.$label, this.$indicator );
7769 this.$element
7770 .addClass( 'oo-ui-dropdownWidget' )
7771 .append( this.$handle );
7772 this.$overlay.append( this.menu.$element );
7773 };
7774
7775 /* Setup */
7776
7777 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
7778 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IconElement );
7779 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IndicatorElement );
7780 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.LabelElement );
7781 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TitledElement );
7782 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TabIndexedElement );
7783
7784 /* Methods */
7785
7786 /**
7787 * Get the menu.
7788 *
7789 * @return {OO.ui.MenuSelectWidget} Menu of widget
7790 */
7791 OO.ui.DropdownWidget.prototype.getMenu = function () {
7792 return this.menu;
7793 };
7794
7795 /**
7796 * Handles menu select events.
7797 *
7798 * @private
7799 * @param {OO.ui.MenuOptionWidget} item Selected menu item
7800 */
7801 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
7802 var selectedLabel;
7803
7804 if ( !item ) {
7805 this.setLabel( null );
7806 return;
7807 }
7808
7809 selectedLabel = item.getLabel();
7810
7811 // If the label is a DOM element, clone it, because setLabel will append() it
7812 if ( selectedLabel instanceof jQuery ) {
7813 selectedLabel = selectedLabel.clone();
7814 }
7815
7816 this.setLabel( selectedLabel );
7817 };
7818
7819 /**
7820 * Handle menu toggle events.
7821 *
7822 * @private
7823 * @param {boolean} isVisible Open state of the menu
7824 */
7825 OO.ui.DropdownWidget.prototype.onMenuToggle = function ( isVisible ) {
7826 this.$element.toggleClass( 'oo-ui-dropdownWidget-open', isVisible );
7827 this.$handle.attr(
7828 'aria-expanded',
7829 this.$element.hasClass( 'oo-ui-dropdownWidget-open' ).toString()
7830 );
7831 };
7832
7833 /**
7834 * Handle mouse click events.
7835 *
7836 * @private
7837 * @param {jQuery.Event} e Mouse click event
7838 */
7839 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
7840 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
7841 this.menu.toggle();
7842 }
7843 return false;
7844 };
7845
7846 /**
7847 * Handle key down events.
7848 *
7849 * @private
7850 * @param {jQuery.Event} e Key down event
7851 */
7852 OO.ui.DropdownWidget.prototype.onKeyDown = function ( e ) {
7853 if (
7854 !this.isDisabled() &&
7855 (
7856 e.which === OO.ui.Keys.ENTER ||
7857 (
7858 e.which === OO.ui.Keys.SPACE &&
7859 // Avoid conflicts with type-to-search, see SelectWidget#onKeyPress.
7860 // Space only closes the menu is the user is not typing to search.
7861 this.menu.keyPressBuffer === ''
7862 ) ||
7863 (
7864 !this.menu.isVisible() &&
7865 (
7866 e.which === OO.ui.Keys.UP ||
7867 e.which === OO.ui.Keys.DOWN
7868 )
7869 )
7870 )
7871 ) {
7872 this.menu.toggle();
7873 return false;
7874 }
7875 };
7876
7877 /**
7878 * RadioOptionWidget is an option widget that looks like a radio button.
7879 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
7880 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
7881 *
7882 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
7883 *
7884 * @class
7885 * @extends OO.ui.OptionWidget
7886 *
7887 * @constructor
7888 * @param {Object} [config] Configuration options
7889 */
7890 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
7891 // Configuration initialization
7892 config = config || {};
7893
7894 // Properties (must be done before parent constructor which calls #setDisabled)
7895 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
7896
7897 // Parent constructor
7898 OO.ui.RadioOptionWidget.parent.call( this, config );
7899
7900 // Initialization
7901 // Remove implicit role, we're handling it ourselves
7902 this.radio.$input.attr( 'role', 'presentation' );
7903 this.$element
7904 .addClass( 'oo-ui-radioOptionWidget' )
7905 .attr( 'role', 'radio' )
7906 .attr( 'aria-checked', 'false' )
7907 .removeAttr( 'aria-selected' )
7908 .prepend( this.radio.$element );
7909 };
7910
7911 /* Setup */
7912
7913 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
7914
7915 /* Static Properties */
7916
7917 /**
7918 * @static
7919 * @inheritdoc
7920 */
7921 OO.ui.RadioOptionWidget.static.highlightable = false;
7922
7923 /**
7924 * @static
7925 * @inheritdoc
7926 */
7927 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
7928
7929 /**
7930 * @static
7931 * @inheritdoc
7932 */
7933 OO.ui.RadioOptionWidget.static.pressable = false;
7934
7935 /**
7936 * @static
7937 * @inheritdoc
7938 */
7939 OO.ui.RadioOptionWidget.static.tagName = 'label';
7940
7941 /* Methods */
7942
7943 /**
7944 * @inheritdoc
7945 */
7946 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
7947 OO.ui.RadioOptionWidget.parent.prototype.setSelected.call( this, state );
7948
7949 this.radio.setSelected( state );
7950 this.$element
7951 .attr( 'aria-checked', state.toString() )
7952 .removeAttr( 'aria-selected' );
7953
7954 return this;
7955 };
7956
7957 /**
7958 * @inheritdoc
7959 */
7960 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
7961 OO.ui.RadioOptionWidget.parent.prototype.setDisabled.call( this, disabled );
7962
7963 this.radio.setDisabled( this.isDisabled() );
7964
7965 return this;
7966 };
7967
7968 /**
7969 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
7970 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
7971 * an interface for adding, removing and selecting options.
7972 * Please see the [OOUI documentation on MediaWiki][1] for more information.
7973 *
7974 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7975 * OO.ui.RadioSelectInputWidget instead.
7976 *
7977 * @example
7978 * // A RadioSelectWidget with RadioOptions.
7979 * var option1 = new OO.ui.RadioOptionWidget( {
7980 * data: 'a',
7981 * label: 'Selected radio option'
7982 * } );
7983 *
7984 * var option2 = new OO.ui.RadioOptionWidget( {
7985 * data: 'b',
7986 * label: 'Unselected radio option'
7987 * } );
7988 *
7989 * var radioSelect=new OO.ui.RadioSelectWidget( {
7990 * items: [ option1, option2 ]
7991 * } );
7992 *
7993 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
7994 * radioSelect.selectItem( option1 );
7995 *
7996 * $( 'body' ).append( radioSelect.$element );
7997 *
7998 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7999
8000 *
8001 * @class
8002 * @extends OO.ui.SelectWidget
8003 * @mixins OO.ui.mixin.TabIndexedElement
8004 *
8005 * @constructor
8006 * @param {Object} [config] Configuration options
8007 */
8008 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
8009 // Parent constructor
8010 OO.ui.RadioSelectWidget.parent.call( this, config );
8011
8012 // Mixin constructors
8013 OO.ui.mixin.TabIndexedElement.call( this, config );
8014
8015 // Events
8016 this.$element.on( {
8017 focus: this.bindKeyDownListener.bind( this ),
8018 blur: this.unbindKeyDownListener.bind( this )
8019 } );
8020
8021 // Initialization
8022 this.$element
8023 .addClass( 'oo-ui-radioSelectWidget' )
8024 .attr( 'role', 'radiogroup' );
8025 };
8026
8027 /* Setup */
8028
8029 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
8030 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.mixin.TabIndexedElement );
8031
8032 /**
8033 * MultioptionWidgets are special elements that can be selected and configured with data. The
8034 * data is often unique for each option, but it does not have to be. MultioptionWidgets are used
8035 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
8036 * and examples, please see the [OOUI documentation on MediaWiki][1].
8037 *
8038 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Multioptions
8039 *
8040 * @class
8041 * @extends OO.ui.Widget
8042 * @mixins OO.ui.mixin.ItemWidget
8043 * @mixins OO.ui.mixin.LabelElement
8044 *
8045 * @constructor
8046 * @param {Object} [config] Configuration options
8047 * @cfg {boolean} [selected=false] Whether the option is initially selected
8048 */
8049 OO.ui.MultioptionWidget = function OoUiMultioptionWidget( config ) {
8050 // Configuration initialization
8051 config = config || {};
8052
8053 // Parent constructor
8054 OO.ui.MultioptionWidget.parent.call( this, config );
8055
8056 // Mixin constructors
8057 OO.ui.mixin.ItemWidget.call( this );
8058 OO.ui.mixin.LabelElement.call( this, config );
8059
8060 // Properties
8061 this.selected = null;
8062
8063 // Initialization
8064 this.$element
8065 .addClass( 'oo-ui-multioptionWidget' )
8066 .append( this.$label );
8067 this.setSelected( config.selected );
8068 };
8069
8070 /* Setup */
8071
8072 OO.inheritClass( OO.ui.MultioptionWidget, OO.ui.Widget );
8073 OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.ItemWidget );
8074 OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.LabelElement );
8075
8076 /* Events */
8077
8078 /**
8079 * @event change
8080 *
8081 * A change event is emitted when the selected state of the option changes.
8082 *
8083 * @param {boolean} selected Whether the option is now selected
8084 */
8085
8086 /* Methods */
8087
8088 /**
8089 * Check if the option is selected.
8090 *
8091 * @return {boolean} Item is selected
8092 */
8093 OO.ui.MultioptionWidget.prototype.isSelected = function () {
8094 return this.selected;
8095 };
8096
8097 /**
8098 * Set the option’s selected state. In general, all modifications to the selection
8099 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
8100 * method instead of this method.
8101 *
8102 * @param {boolean} [state=false] Select option
8103 * @chainable
8104 */
8105 OO.ui.MultioptionWidget.prototype.setSelected = function ( state ) {
8106 state = !!state;
8107 if ( this.selected !== state ) {
8108 this.selected = state;
8109 this.emit( 'change', state );
8110 this.$element.toggleClass( 'oo-ui-multioptionWidget-selected', state );
8111 }
8112 return this;
8113 };
8114
8115 /**
8116 * MultiselectWidget allows selecting multiple options from a list.
8117 *
8118 * For more information about menus and options, please see the [OOUI documentation on MediaWiki][1].
8119 *
8120 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
8121 *
8122 * @class
8123 * @abstract
8124 * @extends OO.ui.Widget
8125 * @mixins OO.ui.mixin.GroupWidget
8126 *
8127 * @constructor
8128 * @param {Object} [config] Configuration options
8129 * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
8130 */
8131 OO.ui.MultiselectWidget = function OoUiMultiselectWidget( config ) {
8132 // Parent constructor
8133 OO.ui.MultiselectWidget.parent.call( this, config );
8134
8135 // Configuration initialization
8136 config = config || {};
8137
8138 // Mixin constructors
8139 OO.ui.mixin.GroupWidget.call( this, config );
8140
8141 // Events
8142 this.aggregate( { change: 'select' } );
8143 // This is mostly for compatibility with CapsuleMultiselectWidget... normally, 'change' is emitted
8144 // by GroupElement only when items are added/removed
8145 this.connect( this, { select: [ 'emit', 'change' ] } );
8146
8147 // Initialization
8148 if ( config.items ) {
8149 this.addItems( config.items );
8150 }
8151 this.$group.addClass( 'oo-ui-multiselectWidget-group' );
8152 this.$element.addClass( 'oo-ui-multiselectWidget' )
8153 .append( this.$group );
8154 };
8155
8156 /* Setup */
8157
8158 OO.inheritClass( OO.ui.MultiselectWidget, OO.ui.Widget );
8159 OO.mixinClass( OO.ui.MultiselectWidget, OO.ui.mixin.GroupWidget );
8160
8161 /* Events */
8162
8163 /**
8164 * @event change
8165 *
8166 * A change event is emitted when the set of items changes, or an item is selected or deselected.
8167 */
8168
8169 /**
8170 * @event select
8171 *
8172 * A select event is emitted when an item is selected or deselected.
8173 */
8174
8175 /* Methods */
8176
8177 /**
8178 * Find options that are selected.
8179 *
8180 * @return {OO.ui.MultioptionWidget[]} Selected options
8181 */
8182 OO.ui.MultiselectWidget.prototype.findSelectedItems = function () {
8183 return this.items.filter( function ( item ) {
8184 return item.isSelected();
8185 } );
8186 };
8187
8188 /**
8189 * Find the data of options that are selected.
8190 *
8191 * @return {Object[]|string[]} Values of selected options
8192 */
8193 OO.ui.MultiselectWidget.prototype.findSelectedItemsData = function () {
8194 return this.findSelectedItems().map( function ( item ) {
8195 return item.data;
8196 } );
8197 };
8198
8199 /**
8200 * Select options by reference. Options not mentioned in the `items` array will be deselected.
8201 *
8202 * @param {OO.ui.MultioptionWidget[]} items Items to select
8203 * @chainable
8204 */
8205 OO.ui.MultiselectWidget.prototype.selectItems = function ( items ) {
8206 this.items.forEach( function ( item ) {
8207 var selected = items.indexOf( item ) !== -1;
8208 item.setSelected( selected );
8209 } );
8210 return this;
8211 };
8212
8213 /**
8214 * Select items by their data. Options not mentioned in the `datas` array will be deselected.
8215 *
8216 * @param {Object[]|string[]} datas Values of items to select
8217 * @chainable
8218 */
8219 OO.ui.MultiselectWidget.prototype.selectItemsByData = function ( datas ) {
8220 var items,
8221 widget = this;
8222 items = datas.map( function ( data ) {
8223 return widget.findItemFromData( data );
8224 } );
8225 this.selectItems( items );
8226 return this;
8227 };
8228
8229 /**
8230 * CheckboxMultioptionWidget is an option widget that looks like a checkbox.
8231 * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
8232 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8233 *
8234 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8235 *
8236 * @class
8237 * @extends OO.ui.MultioptionWidget
8238 *
8239 * @constructor
8240 * @param {Object} [config] Configuration options
8241 */
8242 OO.ui.CheckboxMultioptionWidget = function OoUiCheckboxMultioptionWidget( config ) {
8243 // Configuration initialization
8244 config = config || {};
8245
8246 // Properties (must be done before parent constructor which calls #setDisabled)
8247 this.checkbox = new OO.ui.CheckboxInputWidget();
8248
8249 // Parent constructor
8250 OO.ui.CheckboxMultioptionWidget.parent.call( this, config );
8251
8252 // Events
8253 this.checkbox.on( 'change', this.onCheckboxChange.bind( this ) );
8254 this.$element.on( 'keydown', this.onKeyDown.bind( this ) );
8255
8256 // Initialization
8257 this.$element
8258 .addClass( 'oo-ui-checkboxMultioptionWidget' )
8259 .prepend( this.checkbox.$element );
8260 };
8261
8262 /* Setup */
8263
8264 OO.inheritClass( OO.ui.CheckboxMultioptionWidget, OO.ui.MultioptionWidget );
8265
8266 /* Static Properties */
8267
8268 /**
8269 * @static
8270 * @inheritdoc
8271 */
8272 OO.ui.CheckboxMultioptionWidget.static.tagName = 'label';
8273
8274 /* Methods */
8275
8276 /**
8277 * Handle checkbox selected state change.
8278 *
8279 * @private
8280 */
8281 OO.ui.CheckboxMultioptionWidget.prototype.onCheckboxChange = function () {
8282 this.setSelected( this.checkbox.isSelected() );
8283 };
8284
8285 /**
8286 * @inheritdoc
8287 */
8288 OO.ui.CheckboxMultioptionWidget.prototype.setSelected = function ( state ) {
8289 OO.ui.CheckboxMultioptionWidget.parent.prototype.setSelected.call( this, state );
8290 this.checkbox.setSelected( state );
8291 return this;
8292 };
8293
8294 /**
8295 * @inheritdoc
8296 */
8297 OO.ui.CheckboxMultioptionWidget.prototype.setDisabled = function ( disabled ) {
8298 OO.ui.CheckboxMultioptionWidget.parent.prototype.setDisabled.call( this, disabled );
8299 this.checkbox.setDisabled( this.isDisabled() );
8300 return this;
8301 };
8302
8303 /**
8304 * Focus the widget.
8305 */
8306 OO.ui.CheckboxMultioptionWidget.prototype.focus = function () {
8307 this.checkbox.focus();
8308 };
8309
8310 /**
8311 * Handle key down events.
8312 *
8313 * @protected
8314 * @param {jQuery.Event} e
8315 */
8316 OO.ui.CheckboxMultioptionWidget.prototype.onKeyDown = function ( e ) {
8317 var
8318 element = this.getElementGroup(),
8319 nextItem;
8320
8321 if ( e.keyCode === OO.ui.Keys.LEFT || e.keyCode === OO.ui.Keys.UP ) {
8322 nextItem = element.getRelativeFocusableItem( this, -1 );
8323 } else if ( e.keyCode === OO.ui.Keys.RIGHT || e.keyCode === OO.ui.Keys.DOWN ) {
8324 nextItem = element.getRelativeFocusableItem( this, 1 );
8325 }
8326
8327 if ( nextItem ) {
8328 e.preventDefault();
8329 nextItem.focus();
8330 }
8331 };
8332
8333 /**
8334 * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
8335 * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
8336 * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
8337 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8338 *
8339 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8340 * OO.ui.CheckboxMultiselectInputWidget instead.
8341 *
8342 * @example
8343 * // A CheckboxMultiselectWidget with CheckboxMultioptions.
8344 * var option1 = new OO.ui.CheckboxMultioptionWidget( {
8345 * data: 'a',
8346 * selected: true,
8347 * label: 'Selected checkbox'
8348 * } );
8349 *
8350 * var option2 = new OO.ui.CheckboxMultioptionWidget( {
8351 * data: 'b',
8352 * label: 'Unselected checkbox'
8353 * } );
8354 *
8355 * var multiselect=new OO.ui.CheckboxMultiselectWidget( {
8356 * items: [ option1, option2 ]
8357 * } );
8358 *
8359 * $( 'body' ).append( multiselect.$element );
8360 *
8361 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8362 *
8363 * @class
8364 * @extends OO.ui.MultiselectWidget
8365 *
8366 * @constructor
8367 * @param {Object} [config] Configuration options
8368 */
8369 OO.ui.CheckboxMultiselectWidget = function OoUiCheckboxMultiselectWidget( config ) {
8370 // Parent constructor
8371 OO.ui.CheckboxMultiselectWidget.parent.call( this, config );
8372
8373 // Properties
8374 this.$lastClicked = null;
8375
8376 // Events
8377 this.$group.on( 'click', this.onClick.bind( this ) );
8378
8379 // Initialization
8380 this.$element
8381 .addClass( 'oo-ui-checkboxMultiselectWidget' );
8382 };
8383
8384 /* Setup */
8385
8386 OO.inheritClass( OO.ui.CheckboxMultiselectWidget, OO.ui.MultiselectWidget );
8387
8388 /* Methods */
8389
8390 /**
8391 * Get an option by its position relative to the specified item (or to the start of the option array,
8392 * if item is `null`). The direction in which to search through the option array is specified with a
8393 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
8394 * `null` if there are no options in the array.
8395 *
8396 * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
8397 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
8398 * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items in the select
8399 */
8400 OO.ui.CheckboxMultiselectWidget.prototype.getRelativeFocusableItem = function ( item, direction ) {
8401 var currentIndex, nextIndex, i,
8402 increase = direction > 0 ? 1 : -1,
8403 len = this.items.length;
8404
8405 if ( item ) {
8406 currentIndex = this.items.indexOf( item );
8407 nextIndex = ( currentIndex + increase + len ) % len;
8408 } else {
8409 // If no item is selected and moving forward, start at the beginning.
8410 // If moving backward, start at the end.
8411 nextIndex = direction > 0 ? 0 : len - 1;
8412 }
8413
8414 for ( i = 0; i < len; i++ ) {
8415 item = this.items[ nextIndex ];
8416 if ( item && !item.isDisabled() ) {
8417 return item;
8418 }
8419 nextIndex = ( nextIndex + increase + len ) % len;
8420 }
8421 return null;
8422 };
8423
8424 /**
8425 * Handle click events on checkboxes.
8426 *
8427 * @param {jQuery.Event} e
8428 */
8429 OO.ui.CheckboxMultiselectWidget.prototype.onClick = function ( e ) {
8430 var $options, lastClickedIndex, nowClickedIndex, i, direction, wasSelected, items,
8431 $lastClicked = this.$lastClicked,
8432 $nowClicked = $( e.target ).closest( '.oo-ui-checkboxMultioptionWidget' )
8433 .not( '.oo-ui-widget-disabled' );
8434
8435 // Allow selecting multiple options at once by Shift-clicking them
8436 if ( $lastClicked && $nowClicked.length && e.shiftKey ) {
8437 $options = this.$group.find( '.oo-ui-checkboxMultioptionWidget' );
8438 lastClickedIndex = $options.index( $lastClicked );
8439 nowClickedIndex = $options.index( $nowClicked );
8440 // If it's the same item, either the user is being silly, or it's a fake event generated by the
8441 // browser. In either case we don't need custom handling.
8442 if ( nowClickedIndex !== lastClickedIndex ) {
8443 items = this.items;
8444 wasSelected = items[ nowClickedIndex ].isSelected();
8445 direction = nowClickedIndex > lastClickedIndex ? 1 : -1;
8446
8447 // This depends on the DOM order of the items and the order of the .items array being the same.
8448 for ( i = lastClickedIndex; i !== nowClickedIndex; i += direction ) {
8449 if ( !items[ i ].isDisabled() ) {
8450 items[ i ].setSelected( !wasSelected );
8451 }
8452 }
8453 // For the now-clicked element, use immediate timeout to allow the browser to do its own
8454 // handling first, then set our value. The order in which events happen is different for
8455 // clicks on the <input> and on the <label> and there are additional fake clicks fired for
8456 // non-click actions that change the checkboxes.
8457 e.preventDefault();
8458 setTimeout( function () {
8459 if ( !items[ nowClickedIndex ].isDisabled() ) {
8460 items[ nowClickedIndex ].setSelected( !wasSelected );
8461 }
8462 } );
8463 }
8464 }
8465
8466 if ( $nowClicked.length ) {
8467 this.$lastClicked = $nowClicked;
8468 }
8469 };
8470
8471 /**
8472 * Focus the widget
8473 *
8474 * @chainable
8475 */
8476 OO.ui.CheckboxMultiselectWidget.prototype.focus = function () {
8477 var item;
8478 if ( !this.isDisabled() ) {
8479 item = this.getRelativeFocusableItem( null, 1 );
8480 if ( item ) {
8481 item.focus();
8482 }
8483 }
8484 return this;
8485 };
8486
8487 /**
8488 * @inheritdoc
8489 */
8490 OO.ui.CheckboxMultiselectWidget.prototype.simulateLabelClick = function () {
8491 this.focus();
8492 };
8493
8494 /**
8495 * Progress bars visually display the status of an operation, such as a download,
8496 * and can be either determinate or indeterminate:
8497 *
8498 * - **determinate** process bars show the percent of an operation that is complete.
8499 *
8500 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
8501 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
8502 * not use percentages.
8503 *
8504 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
8505 *
8506 * @example
8507 * // Examples of determinate and indeterminate progress bars.
8508 * var progressBar1 = new OO.ui.ProgressBarWidget( {
8509 * progress: 33
8510 * } );
8511 * var progressBar2 = new OO.ui.ProgressBarWidget();
8512 *
8513 * // Create a FieldsetLayout to layout progress bars
8514 * var fieldset = new OO.ui.FieldsetLayout;
8515 * fieldset.addItems( [
8516 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
8517 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
8518 * ] );
8519 * $( 'body' ).append( fieldset.$element );
8520 *
8521 * @class
8522 * @extends OO.ui.Widget
8523 *
8524 * @constructor
8525 * @param {Object} [config] Configuration options
8526 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
8527 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
8528 * By default, the progress bar is indeterminate.
8529 */
8530 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
8531 // Configuration initialization
8532 config = config || {};
8533
8534 // Parent constructor
8535 OO.ui.ProgressBarWidget.parent.call( this, config );
8536
8537 // Properties
8538 this.$bar = $( '<div>' );
8539 this.progress = null;
8540
8541 // Initialization
8542 this.setProgress( config.progress !== undefined ? config.progress : false );
8543 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
8544 this.$element
8545 .attr( {
8546 role: 'progressbar',
8547 'aria-valuemin': 0,
8548 'aria-valuemax': 100
8549 } )
8550 .addClass( 'oo-ui-progressBarWidget' )
8551 .append( this.$bar );
8552 };
8553
8554 /* Setup */
8555
8556 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
8557
8558 /* Static Properties */
8559
8560 /**
8561 * @static
8562 * @inheritdoc
8563 */
8564 OO.ui.ProgressBarWidget.static.tagName = 'div';
8565
8566 /* Methods */
8567
8568 /**
8569 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
8570 *
8571 * @return {number|boolean} Progress percent
8572 */
8573 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
8574 return this.progress;
8575 };
8576
8577 /**
8578 * Set the percent of the process completed or `false` for an indeterminate process.
8579 *
8580 * @param {number|boolean} progress Progress percent or `false` for indeterminate
8581 */
8582 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
8583 this.progress = progress;
8584
8585 if ( progress !== false ) {
8586 this.$bar.css( 'width', this.progress + '%' );
8587 this.$element.attr( 'aria-valuenow', this.progress );
8588 } else {
8589 this.$bar.css( 'width', '' );
8590 this.$element.removeAttr( 'aria-valuenow' );
8591 }
8592 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress === false );
8593 };
8594
8595 /**
8596 * InputWidget is the base class for all input widgets, which
8597 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
8598 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
8599 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
8600 *
8601 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
8602 *
8603 * @abstract
8604 * @class
8605 * @extends OO.ui.Widget
8606 * @mixins OO.ui.mixin.FlaggedElement
8607 * @mixins OO.ui.mixin.TabIndexedElement
8608 * @mixins OO.ui.mixin.TitledElement
8609 * @mixins OO.ui.mixin.AccessKeyedElement
8610 *
8611 * @constructor
8612 * @param {Object} [config] Configuration options
8613 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
8614 * @cfg {string} [value=''] The value of the input.
8615 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
8616 * @cfg {string} [inputId] The value of the input’s HTML `id` attribute.
8617 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
8618 * before it is accepted.
8619 */
8620 OO.ui.InputWidget = function OoUiInputWidget( config ) {
8621 // Configuration initialization
8622 config = config || {};
8623
8624 // Parent constructor
8625 OO.ui.InputWidget.parent.call( this, config );
8626
8627 // Properties
8628 // See #reusePreInfuseDOM about config.$input
8629 this.$input = config.$input || this.getInputElement( config );
8630 this.value = '';
8631 this.inputFilter = config.inputFilter;
8632
8633 // Mixin constructors
8634 OO.ui.mixin.FlaggedElement.call( this, config );
8635 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
8636 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
8637 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$input } ) );
8638
8639 // Events
8640 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
8641
8642 // Initialization
8643 this.$input
8644 .addClass( 'oo-ui-inputWidget-input' )
8645 .attr( 'name', config.name )
8646 .prop( 'disabled', this.isDisabled() );
8647 this.$element
8648 .addClass( 'oo-ui-inputWidget' )
8649 .append( this.$input );
8650 this.setValue( config.value );
8651 if ( config.dir ) {
8652 this.setDir( config.dir );
8653 }
8654 if ( config.inputId !== undefined ) {
8655 this.setInputId( config.inputId );
8656 }
8657 };
8658
8659 /* Setup */
8660
8661 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
8662 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.FlaggedElement );
8663 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TabIndexedElement );
8664 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TitledElement );
8665 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.AccessKeyedElement );
8666
8667 /* Static Methods */
8668
8669 /**
8670 * @inheritdoc
8671 */
8672 OO.ui.InputWidget.static.reusePreInfuseDOM = function ( node, config ) {
8673 config = OO.ui.InputWidget.parent.static.reusePreInfuseDOM( node, config );
8674 // Reusing `$input` lets browsers preserve inputted values across page reloads, see T114134.
8675 config.$input = $( node ).find( '.oo-ui-inputWidget-input' );
8676 return config;
8677 };
8678
8679 /**
8680 * @inheritdoc
8681 */
8682 OO.ui.InputWidget.static.gatherPreInfuseState = function ( node, config ) {
8683 var state = OO.ui.InputWidget.parent.static.gatherPreInfuseState( node, config );
8684 if ( config.$input && config.$input.length ) {
8685 state.value = config.$input.val();
8686 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
8687 state.focus = config.$input.is( ':focus' );
8688 }
8689 return state;
8690 };
8691
8692 /* Events */
8693
8694 /**
8695 * @event change
8696 *
8697 * A change event is emitted when the value of the input changes.
8698 *
8699 * @param {string} value
8700 */
8701
8702 /* Methods */
8703
8704 /**
8705 * Get input element.
8706 *
8707 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
8708 * different circumstances. The element must have a `value` property (like form elements).
8709 *
8710 * @protected
8711 * @param {Object} config Configuration options
8712 * @return {jQuery} Input element
8713 */
8714 OO.ui.InputWidget.prototype.getInputElement = function () {
8715 return $( '<input>' );
8716 };
8717
8718 /**
8719 * Handle potentially value-changing events.
8720 *
8721 * @private
8722 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
8723 */
8724 OO.ui.InputWidget.prototype.onEdit = function () {
8725 var widget = this;
8726 if ( !this.isDisabled() ) {
8727 // Allow the stack to clear so the value will be updated
8728 setTimeout( function () {
8729 widget.setValue( widget.$input.val() );
8730 } );
8731 }
8732 };
8733
8734 /**
8735 * Get the value of the input.
8736 *
8737 * @return {string} Input value
8738 */
8739 OO.ui.InputWidget.prototype.getValue = function () {
8740 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
8741 // it, and we won't know unless they're kind enough to trigger a 'change' event.
8742 var value = this.$input.val();
8743 if ( this.value !== value ) {
8744 this.setValue( value );
8745 }
8746 return this.value;
8747 };
8748
8749 /**
8750 * Set the directionality of the input.
8751 *
8752 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
8753 * @chainable
8754 */
8755 OO.ui.InputWidget.prototype.setDir = function ( dir ) {
8756 this.$input.prop( 'dir', dir );
8757 return this;
8758 };
8759
8760 /**
8761 * Set the value of the input.
8762 *
8763 * @param {string} value New value
8764 * @fires change
8765 * @chainable
8766 */
8767 OO.ui.InputWidget.prototype.setValue = function ( value ) {
8768 value = this.cleanUpValue( value );
8769 // Update the DOM if it has changed. Note that with cleanUpValue, it
8770 // is possible for the DOM value to change without this.value changing.
8771 if ( this.$input.val() !== value ) {
8772 this.$input.val( value );
8773 }
8774 if ( this.value !== value ) {
8775 this.value = value;
8776 this.emit( 'change', this.value );
8777 }
8778 // The first time that the value is set (probably while constructing the widget),
8779 // remember it in defaultValue. This property can be later used to check whether
8780 // the value of the input has been changed since it was created.
8781 if ( this.defaultValue === undefined ) {
8782 this.defaultValue = this.value;
8783 this.$input[ 0 ].defaultValue = this.defaultValue;
8784 }
8785 return this;
8786 };
8787
8788 /**
8789 * Clean up incoming value.
8790 *
8791 * Ensures value is a string, and converts undefined and null to empty string.
8792 *
8793 * @private
8794 * @param {string} value Original value
8795 * @return {string} Cleaned up value
8796 */
8797 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
8798 if ( value === undefined || value === null ) {
8799 return '';
8800 } else if ( this.inputFilter ) {
8801 return this.inputFilter( String( value ) );
8802 } else {
8803 return String( value );
8804 }
8805 };
8806
8807 /**
8808 * @inheritdoc
8809 */
8810 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
8811 OO.ui.InputWidget.parent.prototype.setDisabled.call( this, state );
8812 if ( this.$input ) {
8813 this.$input.prop( 'disabled', this.isDisabled() );
8814 }
8815 return this;
8816 };
8817
8818 /**
8819 * Set the 'id' attribute of the `<input>` element.
8820 *
8821 * @param {string} id
8822 * @chainable
8823 */
8824 OO.ui.InputWidget.prototype.setInputId = function ( id ) {
8825 this.$input.attr( 'id', id );
8826 return this;
8827 };
8828
8829 /**
8830 * @inheritdoc
8831 */
8832 OO.ui.InputWidget.prototype.restorePreInfuseState = function ( state ) {
8833 OO.ui.InputWidget.parent.prototype.restorePreInfuseState.call( this, state );
8834 if ( state.value !== undefined && state.value !== this.getValue() ) {
8835 this.setValue( state.value );
8836 }
8837 if ( state.focus ) {
8838 this.focus();
8839 }
8840 };
8841
8842 /**
8843 * Data widget intended for creating 'hidden'-type inputs.
8844 *
8845 * @class
8846 * @extends OO.ui.Widget
8847 *
8848 * @constructor
8849 * @param {Object} [config] Configuration options
8850 * @cfg {string} [value=''] The value of the input.
8851 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
8852 */
8853 OO.ui.HiddenInputWidget = function OoUiHiddenInputWidget( config ) {
8854 // Configuration initialization
8855 config = $.extend( { value: '', name: '' }, config );
8856
8857 // Parent constructor
8858 OO.ui.HiddenInputWidget.parent.call( this, config );
8859
8860 // Initialization
8861 this.$element.attr( {
8862 type: 'hidden',
8863 value: config.value,
8864 name: config.name
8865 } );
8866 this.$element.removeAttr( 'aria-disabled' );
8867 };
8868
8869 /* Setup */
8870
8871 OO.inheritClass( OO.ui.HiddenInputWidget, OO.ui.Widget );
8872
8873 /* Static Properties */
8874
8875 /**
8876 * @static
8877 * @inheritdoc
8878 */
8879 OO.ui.HiddenInputWidget.static.tagName = 'input';
8880
8881 /**
8882 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
8883 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
8884 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
8885 * HTML `<button>` (the default) or an HTML `<input>` tags. See the
8886 * [OOUI documentation on MediaWiki] [1] for more information.
8887 *
8888 * @example
8889 * // A ButtonInputWidget rendered as an HTML button, the default.
8890 * var button = new OO.ui.ButtonInputWidget( {
8891 * label: 'Input button',
8892 * icon: 'check',
8893 * value: 'check'
8894 * } );
8895 * $( 'body' ).append( button.$element );
8896 *
8897 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#Button_inputs
8898 *
8899 * @class
8900 * @extends OO.ui.InputWidget
8901 * @mixins OO.ui.mixin.ButtonElement
8902 * @mixins OO.ui.mixin.IconElement
8903 * @mixins OO.ui.mixin.IndicatorElement
8904 * @mixins OO.ui.mixin.LabelElement
8905 * @mixins OO.ui.mixin.TitledElement
8906 *
8907 * @constructor
8908 * @param {Object} [config] Configuration options
8909 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
8910 * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
8911 * Widgets configured to be an `<input>` do not support {@link #icon icons} and {@link #indicator indicators},
8912 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
8913 * be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
8914 */
8915 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
8916 // Configuration initialization
8917 config = $.extend( { type: 'button', useInputTag: false }, config );
8918
8919 // See InputWidget#reusePreInfuseDOM about config.$input
8920 if ( config.$input ) {
8921 config.$input.empty();
8922 }
8923
8924 // Properties (must be set before parent constructor, which calls #setValue)
8925 this.useInputTag = config.useInputTag;
8926
8927 // Parent constructor
8928 OO.ui.ButtonInputWidget.parent.call( this, config );
8929
8930 // Mixin constructors
8931 OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
8932 OO.ui.mixin.IconElement.call( this, config );
8933 OO.ui.mixin.IndicatorElement.call( this, config );
8934 OO.ui.mixin.LabelElement.call( this, config );
8935 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
8936
8937 // Initialization
8938 if ( !config.useInputTag ) {
8939 this.$input.append( this.$icon, this.$label, this.$indicator );
8940 }
8941 this.$element.addClass( 'oo-ui-buttonInputWidget' );
8942 };
8943
8944 /* Setup */
8945
8946 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
8947 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.ButtonElement );
8948 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IconElement );
8949 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IndicatorElement );
8950 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.LabelElement );
8951 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.TitledElement );
8952
8953 /* Static Properties */
8954
8955 /**
8956 * @static
8957 * @inheritdoc
8958 */
8959 OO.ui.ButtonInputWidget.static.tagName = 'span';
8960
8961 /* Methods */
8962
8963 /**
8964 * @inheritdoc
8965 * @protected
8966 */
8967 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
8968 var type;
8969 type = [ 'button', 'submit', 'reset' ].indexOf( config.type ) !== -1 ? config.type : 'button';
8970 return $( '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + type + '">' );
8971 };
8972
8973 /**
8974 * Set label value.
8975 *
8976 * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
8977 *
8978 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
8979 * text, or `null` for no label
8980 * @chainable
8981 */
8982 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
8983 if ( typeof label === 'function' ) {
8984 label = OO.ui.resolveMsg( label );
8985 }
8986
8987 if ( this.useInputTag ) {
8988 // Discard non-plaintext labels
8989 if ( typeof label !== 'string' ) {
8990 label = '';
8991 }
8992
8993 this.$input.val( label );
8994 }
8995
8996 return OO.ui.mixin.LabelElement.prototype.setLabel.call( this, label );
8997 };
8998
8999 /**
9000 * Set the value of the input.
9001 *
9002 * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
9003 * they do not support {@link #value values}.
9004 *
9005 * @param {string} value New value
9006 * @chainable
9007 */
9008 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
9009 if ( !this.useInputTag ) {
9010 OO.ui.ButtonInputWidget.parent.prototype.setValue.call( this, value );
9011 }
9012 return this;
9013 };
9014
9015 /**
9016 * @inheritdoc
9017 */
9018 OO.ui.ButtonInputWidget.prototype.getInputId = function () {
9019 // Disable generating `<label>` elements for buttons. One would very rarely need additional label
9020 // for a button, and it's already a big clickable target, and it causes unexpected rendering.
9021 return null;
9022 };
9023
9024 /**
9025 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
9026 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
9027 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
9028 * alignment. For more information, please see the [OOUI documentation on MediaWiki][1].
9029 *
9030 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9031 *
9032 * @example
9033 * // An example of selected, unselected, and disabled checkbox inputs
9034 * var checkbox1=new OO.ui.CheckboxInputWidget( {
9035 * value: 'a',
9036 * selected: true
9037 * } );
9038 * var checkbox2=new OO.ui.CheckboxInputWidget( {
9039 * value: 'b'
9040 * } );
9041 * var checkbox3=new OO.ui.CheckboxInputWidget( {
9042 * value:'c',
9043 * disabled: true
9044 * } );
9045 * // Create a fieldset layout with fields for each checkbox.
9046 * var fieldset = new OO.ui.FieldsetLayout( {
9047 * label: 'Checkboxes'
9048 * } );
9049 * fieldset.addItems( [
9050 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
9051 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
9052 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
9053 * ] );
9054 * $( 'body' ).append( fieldset.$element );
9055 *
9056 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9057 *
9058 * @class
9059 * @extends OO.ui.InputWidget
9060 *
9061 * @constructor
9062 * @param {Object} [config] Configuration options
9063 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
9064 */
9065 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
9066 // Configuration initialization
9067 config = config || {};
9068
9069 // Parent constructor
9070 OO.ui.CheckboxInputWidget.parent.call( this, config );
9071
9072 // Properties
9073 this.checkIcon = new OO.ui.IconWidget( {
9074 icon: 'check',
9075 classes: [ 'oo-ui-checkboxInputWidget-checkIcon' ]
9076 } );
9077
9078 // Initialization
9079 this.$element
9080 .addClass( 'oo-ui-checkboxInputWidget' )
9081 // Required for pretty styling in WikimediaUI theme
9082 .append( this.checkIcon.$element );
9083 this.setSelected( config.selected !== undefined ? config.selected : false );
9084 };
9085
9086 /* Setup */
9087
9088 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
9089
9090 /* Static Properties */
9091
9092 /**
9093 * @static
9094 * @inheritdoc
9095 */
9096 OO.ui.CheckboxInputWidget.static.tagName = 'span';
9097
9098 /* Static Methods */
9099
9100 /**
9101 * @inheritdoc
9102 */
9103 OO.ui.CheckboxInputWidget.static.gatherPreInfuseState = function ( node, config ) {
9104 var state = OO.ui.CheckboxInputWidget.parent.static.gatherPreInfuseState( node, config );
9105 state.checked = config.$input.prop( 'checked' );
9106 return state;
9107 };
9108
9109 /* Methods */
9110
9111 /**
9112 * @inheritdoc
9113 * @protected
9114 */
9115 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
9116 return $( '<input>' ).attr( 'type', 'checkbox' );
9117 };
9118
9119 /**
9120 * @inheritdoc
9121 */
9122 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
9123 var widget = this;
9124 if ( !this.isDisabled() ) {
9125 // Allow the stack to clear so the value will be updated
9126 setTimeout( function () {
9127 widget.setSelected( widget.$input.prop( 'checked' ) );
9128 } );
9129 }
9130 };
9131
9132 /**
9133 * Set selection state of this checkbox.
9134 *
9135 * @param {boolean} state `true` for selected
9136 * @chainable
9137 */
9138 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
9139 state = !!state;
9140 if ( this.selected !== state ) {
9141 this.selected = state;
9142 this.$input.prop( 'checked', this.selected );
9143 this.emit( 'change', this.selected );
9144 }
9145 // The first time that the selection state is set (probably while constructing the widget),
9146 // remember it in defaultSelected. This property can be later used to check whether
9147 // the selection state of the input has been changed since it was created.
9148 if ( this.defaultSelected === undefined ) {
9149 this.defaultSelected = this.selected;
9150 this.$input[ 0 ].defaultChecked = this.defaultSelected;
9151 }
9152 return this;
9153 };
9154
9155 /**
9156 * Check if this checkbox is selected.
9157 *
9158 * @return {boolean} Checkbox is selected
9159 */
9160 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
9161 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
9162 // it, and we won't know unless they're kind enough to trigger a 'change' event.
9163 var selected = this.$input.prop( 'checked' );
9164 if ( this.selected !== selected ) {
9165 this.setSelected( selected );
9166 }
9167 return this.selected;
9168 };
9169
9170 /**
9171 * @inheritdoc
9172 */
9173 OO.ui.CheckboxInputWidget.prototype.simulateLabelClick = function () {
9174 if ( !this.isDisabled() ) {
9175 this.$input.click();
9176 }
9177 this.focus();
9178 };
9179
9180 /**
9181 * @inheritdoc
9182 */
9183 OO.ui.CheckboxInputWidget.prototype.restorePreInfuseState = function ( state ) {
9184 OO.ui.CheckboxInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
9185 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
9186 this.setSelected( state.checked );
9187 }
9188 };
9189
9190 /**
9191 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
9192 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
9193 * of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9194 * more information about input widgets.
9195 *
9196 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
9197 * are no options. If no `value` configuration option is provided, the first option is selected.
9198 * If you need a state representing no value (no option being selected), use a DropdownWidget.
9199 *
9200 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
9201 *
9202 * @example
9203 * // Example: A DropdownInputWidget with three options
9204 * var dropdownInput = new OO.ui.DropdownInputWidget( {
9205 * options: [
9206 * { data: 'a', label: 'First' },
9207 * { data: 'b', label: 'Second'},
9208 * { data: 'c', label: 'Third' }
9209 * ]
9210 * } );
9211 * $( 'body' ).append( dropdownInput.$element );
9212 *
9213 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9214 *
9215 * @class
9216 * @extends OO.ui.InputWidget
9217 *
9218 * @constructor
9219 * @param {Object} [config] Configuration options
9220 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9221 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
9222 */
9223 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
9224 // Configuration initialization
9225 config = config || {};
9226
9227 // Properties (must be done before parent constructor which calls #setDisabled)
9228 this.dropdownWidget = new OO.ui.DropdownWidget( config.dropdown );
9229 // Set up the options before parent constructor, which uses them to validate config.value.
9230 // Use this instead of setOptions() because this.$input is not set up yet.
9231 this.setOptionsData( config.options || [] );
9232
9233 // Parent constructor
9234 OO.ui.DropdownInputWidget.parent.call( this, config );
9235
9236 // Events
9237 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
9238
9239 // Initialization
9240 this.$element
9241 .addClass( 'oo-ui-dropdownInputWidget' )
9242 .append( this.dropdownWidget.$element );
9243 this.setTabIndexedElement( this.dropdownWidget.$tabIndexed );
9244 };
9245
9246 /* Setup */
9247
9248 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
9249
9250 /* Methods */
9251
9252 /**
9253 * @inheritdoc
9254 * @protected
9255 */
9256 OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
9257 return $( '<select>' );
9258 };
9259
9260 /**
9261 * Handles menu select events.
9262 *
9263 * @private
9264 * @param {OO.ui.MenuOptionWidget|null} item Selected menu item
9265 */
9266 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
9267 this.setValue( item ? item.getData() : '' );
9268 };
9269
9270 /**
9271 * @inheritdoc
9272 */
9273 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
9274 var selected;
9275 value = this.cleanUpValue( value );
9276 // Only allow setting values that are actually present in the dropdown
9277 selected = this.dropdownWidget.getMenu().findItemFromData( value ) ||
9278 this.dropdownWidget.getMenu().findFirstSelectableItem();
9279 this.dropdownWidget.getMenu().selectItem( selected );
9280 value = selected ? selected.getData() : '';
9281 OO.ui.DropdownInputWidget.parent.prototype.setValue.call( this, value );
9282 if ( this.optionsDirty ) {
9283 // We reached this from the constructor or from #setOptions.
9284 // We have to update the <select> element.
9285 this.updateOptionsInterface();
9286 }
9287 return this;
9288 };
9289
9290 /**
9291 * @inheritdoc
9292 */
9293 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
9294 this.dropdownWidget.setDisabled( state );
9295 OO.ui.DropdownInputWidget.parent.prototype.setDisabled.call( this, state );
9296 return this;
9297 };
9298
9299 /**
9300 * Set the options available for this input.
9301 *
9302 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9303 * @chainable
9304 */
9305 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
9306 var value = this.getValue();
9307
9308 this.setOptionsData( options );
9309
9310 // Re-set the value to update the visible interface (DropdownWidget and <select>).
9311 // In case the previous value is no longer an available option, select the first valid one.
9312 this.setValue( value );
9313
9314 return this;
9315 };
9316
9317 /**
9318 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
9319 *
9320 * This method may be called before the parent constructor, so various properties may not be
9321 * intialized yet.
9322 *
9323 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9324 * @private
9325 */
9326 OO.ui.DropdownInputWidget.prototype.setOptionsData = function ( options ) {
9327 var
9328 optionWidgets,
9329 widget = this;
9330
9331 this.optionsDirty = true;
9332
9333 optionWidgets = options.map( function ( opt ) {
9334 var optValue;
9335
9336 if ( opt.optgroup !== undefined ) {
9337 return widget.createMenuSectionOptionWidget( opt.optgroup );
9338 }
9339
9340 optValue = widget.cleanUpValue( opt.data );
9341 return widget.createMenuOptionWidget(
9342 optValue,
9343 opt.label !== undefined ? opt.label : optValue
9344 );
9345
9346 } );
9347
9348 this.dropdownWidget.getMenu().clearItems().addItems( optionWidgets );
9349 };
9350
9351 /**
9352 * Create a menu option widget.
9353 *
9354 * @protected
9355 * @param {string} data Item data
9356 * @param {string} label Item label
9357 * @return {OO.ui.MenuOptionWidget} Option widget
9358 */
9359 OO.ui.DropdownInputWidget.prototype.createMenuOptionWidget = function ( data, label ) {
9360 return new OO.ui.MenuOptionWidget( {
9361 data: data,
9362 label: label
9363 } );
9364 };
9365
9366 /**
9367 * Create a menu section option widget.
9368 *
9369 * @protected
9370 * @param {string} label Section item label
9371 * @return {OO.ui.MenuSectionOptionWidget} Menu section option widget
9372 */
9373 OO.ui.DropdownInputWidget.prototype.createMenuSectionOptionWidget = function ( label ) {
9374 return new OO.ui.MenuSectionOptionWidget( {
9375 label: label
9376 } );
9377 };
9378
9379 /**
9380 * Update the user-visible interface to match the internal list of options and value.
9381 *
9382 * This method must only be called after the parent constructor.
9383 *
9384 * @private
9385 */
9386 OO.ui.DropdownInputWidget.prototype.updateOptionsInterface = function () {
9387 var
9388 $optionsContainer = this.$input,
9389 defaultValue = this.defaultValue,
9390 widget = this;
9391
9392 this.$input.empty();
9393
9394 this.dropdownWidget.getMenu().getItems().forEach( function ( optionWidget ) {
9395 var $optionNode;
9396
9397 if ( !( optionWidget instanceof OO.ui.MenuSectionOptionWidget ) ) {
9398 $optionNode = $( '<option>' )
9399 .attr( 'value', optionWidget.getData() )
9400 .text( optionWidget.getLabel() );
9401
9402 // Remember original selection state. This property can be later used to check whether
9403 // the selection state of the input has been changed since it was created.
9404 $optionNode[ 0 ].defaultSelected = ( optionWidget.getData() === defaultValue );
9405
9406 $optionsContainer.append( $optionNode );
9407 } else {
9408 $optionNode = $( '<optgroup>' )
9409 .attr( 'label', optionWidget.getLabel() );
9410 widget.$input.append( $optionNode );
9411 $optionsContainer = $optionNode;
9412 }
9413 } );
9414
9415 this.optionsDirty = false;
9416 };
9417
9418 /**
9419 * @inheritdoc
9420 */
9421 OO.ui.DropdownInputWidget.prototype.focus = function () {
9422 this.dropdownWidget.focus();
9423 return this;
9424 };
9425
9426 /**
9427 * @inheritdoc
9428 */
9429 OO.ui.DropdownInputWidget.prototype.blur = function () {
9430 this.dropdownWidget.blur();
9431 return this;
9432 };
9433
9434 /**
9435 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
9436 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
9437 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
9438 * please see the [OOUI documentation on MediaWiki][1].
9439 *
9440 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9441 *
9442 * @example
9443 * // An example of selected, unselected, and disabled radio inputs
9444 * var radio1 = new OO.ui.RadioInputWidget( {
9445 * value: 'a',
9446 * selected: true
9447 * } );
9448 * var radio2 = new OO.ui.RadioInputWidget( {
9449 * value: 'b'
9450 * } );
9451 * var radio3 = new OO.ui.RadioInputWidget( {
9452 * value: 'c',
9453 * disabled: true
9454 * } );
9455 * // Create a fieldset layout with fields for each radio button.
9456 * var fieldset = new OO.ui.FieldsetLayout( {
9457 * label: 'Radio inputs'
9458 * } );
9459 * fieldset.addItems( [
9460 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
9461 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
9462 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
9463 * ] );
9464 * $( 'body' ).append( fieldset.$element );
9465 *
9466 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9467 *
9468 * @class
9469 * @extends OO.ui.InputWidget
9470 *
9471 * @constructor
9472 * @param {Object} [config] Configuration options
9473 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
9474 */
9475 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
9476 // Configuration initialization
9477 config = config || {};
9478
9479 // Parent constructor
9480 OO.ui.RadioInputWidget.parent.call( this, config );
9481
9482 // Initialization
9483 this.$element
9484 .addClass( 'oo-ui-radioInputWidget' )
9485 // Required for pretty styling in WikimediaUI theme
9486 .append( $( '<span>' ) );
9487 this.setSelected( config.selected !== undefined ? config.selected : false );
9488 };
9489
9490 /* Setup */
9491
9492 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
9493
9494 /* Static Properties */
9495
9496 /**
9497 * @static
9498 * @inheritdoc
9499 */
9500 OO.ui.RadioInputWidget.static.tagName = 'span';
9501
9502 /* Static Methods */
9503
9504 /**
9505 * @inheritdoc
9506 */
9507 OO.ui.RadioInputWidget.static.gatherPreInfuseState = function ( node, config ) {
9508 var state = OO.ui.RadioInputWidget.parent.static.gatherPreInfuseState( node, config );
9509 state.checked = config.$input.prop( 'checked' );
9510 return state;
9511 };
9512
9513 /* Methods */
9514
9515 /**
9516 * @inheritdoc
9517 * @protected
9518 */
9519 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
9520 return $( '<input>' ).attr( 'type', 'radio' );
9521 };
9522
9523 /**
9524 * @inheritdoc
9525 */
9526 OO.ui.RadioInputWidget.prototype.onEdit = function () {
9527 // RadioInputWidget doesn't track its state.
9528 };
9529
9530 /**
9531 * Set selection state of this radio button.
9532 *
9533 * @param {boolean} state `true` for selected
9534 * @chainable
9535 */
9536 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
9537 // RadioInputWidget doesn't track its state.
9538 this.$input.prop( 'checked', state );
9539 // The first time that the selection state is set (probably while constructing the widget),
9540 // remember it in defaultSelected. This property can be later used to check whether
9541 // the selection state of the input has been changed since it was created.
9542 if ( this.defaultSelected === undefined ) {
9543 this.defaultSelected = state;
9544 this.$input[ 0 ].defaultChecked = this.defaultSelected;
9545 }
9546 return this;
9547 };
9548
9549 /**
9550 * Check if this radio button is selected.
9551 *
9552 * @return {boolean} Radio is selected
9553 */
9554 OO.ui.RadioInputWidget.prototype.isSelected = function () {
9555 return this.$input.prop( 'checked' );
9556 };
9557
9558 /**
9559 * @inheritdoc
9560 */
9561 OO.ui.RadioInputWidget.prototype.simulateLabelClick = function () {
9562 if ( !this.isDisabled() ) {
9563 this.$input.click();
9564 }
9565 this.focus();
9566 };
9567
9568 /**
9569 * @inheritdoc
9570 */
9571 OO.ui.RadioInputWidget.prototype.restorePreInfuseState = function ( state ) {
9572 OO.ui.RadioInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
9573 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
9574 this.setSelected( state.checked );
9575 }
9576 };
9577
9578 /**
9579 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
9580 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
9581 * of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9582 * more information about input widgets.
9583 *
9584 * This and OO.ui.DropdownInputWidget support the same configuration options.
9585 *
9586 * @example
9587 * // Example: A RadioSelectInputWidget with three options
9588 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
9589 * options: [
9590 * { data: 'a', label: 'First' },
9591 * { data: 'b', label: 'Second'},
9592 * { data: 'c', label: 'Third' }
9593 * ]
9594 * } );
9595 * $( 'body' ).append( radioSelectInput.$element );
9596 *
9597 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9598 *
9599 * @class
9600 * @extends OO.ui.InputWidget
9601 *
9602 * @constructor
9603 * @param {Object} [config] Configuration options
9604 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9605 */
9606 OO.ui.RadioSelectInputWidget = function OoUiRadioSelectInputWidget( config ) {
9607 // Configuration initialization
9608 config = config || {};
9609
9610 // Properties (must be done before parent constructor which calls #setDisabled)
9611 this.radioSelectWidget = new OO.ui.RadioSelectWidget();
9612 // Set up the options before parent constructor, which uses them to validate config.value.
9613 // Use this instead of setOptions() because this.$input is not set up yet
9614 this.setOptionsData( config.options || [] );
9615
9616 // Parent constructor
9617 OO.ui.RadioSelectInputWidget.parent.call( this, config );
9618
9619 // Events
9620 this.radioSelectWidget.connect( this, { select: 'onMenuSelect' } );
9621
9622 // Initialization
9623 this.$element
9624 .addClass( 'oo-ui-radioSelectInputWidget' )
9625 .append( this.radioSelectWidget.$element );
9626 this.setTabIndexedElement( this.radioSelectWidget.$tabIndexed );
9627 };
9628
9629 /* Setup */
9630
9631 OO.inheritClass( OO.ui.RadioSelectInputWidget, OO.ui.InputWidget );
9632
9633 /* Static Methods */
9634
9635 /**
9636 * @inheritdoc
9637 */
9638 OO.ui.RadioSelectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
9639 var state = OO.ui.RadioSelectInputWidget.parent.static.gatherPreInfuseState( node, config );
9640 state.value = $( node ).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
9641 return state;
9642 };
9643
9644 /**
9645 * @inheritdoc
9646 */
9647 OO.ui.RadioSelectInputWidget.static.reusePreInfuseDOM = function ( node, config ) {
9648 config = OO.ui.RadioSelectInputWidget.parent.static.reusePreInfuseDOM( node, config );
9649 // Cannot reuse the `<input type=radio>` set
9650 delete config.$input;
9651 return config;
9652 };
9653
9654 /* Methods */
9655
9656 /**
9657 * @inheritdoc
9658 * @protected
9659 */
9660 OO.ui.RadioSelectInputWidget.prototype.getInputElement = function () {
9661 // Use this instead of <input type="hidden">, because hidden inputs do not have separate
9662 // 'value' and 'defaultValue' properties, and InputWidget wants to handle 'defaultValue'.
9663 return $( '<input>' ).addClass( 'oo-ui-element-hidden' );
9664 };
9665
9666 /**
9667 * Handles menu select events.
9668 *
9669 * @private
9670 * @param {OO.ui.RadioOptionWidget} item Selected menu item
9671 */
9672 OO.ui.RadioSelectInputWidget.prototype.onMenuSelect = function ( item ) {
9673 this.setValue( item.getData() );
9674 };
9675
9676 /**
9677 * @inheritdoc
9678 */
9679 OO.ui.RadioSelectInputWidget.prototype.setValue = function ( value ) {
9680 var selected;
9681 value = this.cleanUpValue( value );
9682 // Only allow setting values that are actually present in the dropdown
9683 selected = this.radioSelectWidget.findItemFromData( value ) ||
9684 this.radioSelectWidget.findFirstSelectableItem();
9685 this.radioSelectWidget.selectItem( selected );
9686 value = selected ? selected.getData() : '';
9687 OO.ui.RadioSelectInputWidget.parent.prototype.setValue.call( this, value );
9688 return this;
9689 };
9690
9691 /**
9692 * @inheritdoc
9693 */
9694 OO.ui.RadioSelectInputWidget.prototype.setDisabled = function ( state ) {
9695 this.radioSelectWidget.setDisabled( state );
9696 OO.ui.RadioSelectInputWidget.parent.prototype.setDisabled.call( this, state );
9697 return this;
9698 };
9699
9700 /**
9701 * Set the options available for this input.
9702 *
9703 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9704 * @chainable
9705 */
9706 OO.ui.RadioSelectInputWidget.prototype.setOptions = function ( options ) {
9707 var value = this.getValue();
9708
9709 this.setOptionsData( options );
9710
9711 // Re-set the value to update the visible interface (RadioSelectWidget).
9712 // In case the previous value is no longer an available option, select the first valid one.
9713 this.setValue( value );
9714
9715 return this;
9716 };
9717
9718 /**
9719 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
9720 *
9721 * This method may be called before the parent constructor, so various properties may not be
9722 * intialized yet.
9723 *
9724 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9725 * @private
9726 */
9727 OO.ui.RadioSelectInputWidget.prototype.setOptionsData = function ( options ) {
9728 var widget = this;
9729
9730 this.radioSelectWidget
9731 .clearItems()
9732 .addItems( options.map( function ( opt ) {
9733 var optValue = widget.cleanUpValue( opt.data );
9734 return new OO.ui.RadioOptionWidget( {
9735 data: optValue,
9736 label: opt.label !== undefined ? opt.label : optValue
9737 } );
9738 } ) );
9739 };
9740
9741 /**
9742 * @inheritdoc
9743 */
9744 OO.ui.RadioSelectInputWidget.prototype.focus = function () {
9745 this.radioSelectWidget.focus();
9746 return this;
9747 };
9748
9749 /**
9750 * @inheritdoc
9751 */
9752 OO.ui.RadioSelectInputWidget.prototype.blur = function () {
9753 this.radioSelectWidget.blur();
9754 return this;
9755 };
9756
9757 /**
9758 * CheckboxMultiselectInputWidget is a
9759 * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
9760 * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
9761 * HTML `<input type=checkbox>` tags. Please see the [OOUI documentation on MediaWiki][1] for
9762 * more information about input widgets.
9763 *
9764 * @example
9765 * // Example: A CheckboxMultiselectInputWidget with three options
9766 * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
9767 * options: [
9768 * { data: 'a', label: 'First' },
9769 * { data: 'b', label: 'Second'},
9770 * { data: 'c', label: 'Third' }
9771 * ]
9772 * } );
9773 * $( 'body' ).append( multiselectInput.$element );
9774 *
9775 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9776 *
9777 * @class
9778 * @extends OO.ui.InputWidget
9779 *
9780 * @constructor
9781 * @param {Object} [config] Configuration options
9782 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: …, disabled: … }`
9783 */
9784 OO.ui.CheckboxMultiselectInputWidget = function OoUiCheckboxMultiselectInputWidget( config ) {
9785 // Configuration initialization
9786 config = config || {};
9787
9788 // Properties (must be done before parent constructor which calls #setDisabled)
9789 this.checkboxMultiselectWidget = new OO.ui.CheckboxMultiselectWidget();
9790 // Must be set before the #setOptionsData call below
9791 this.inputName = config.name;
9792 // Set up the options before parent constructor, which uses them to validate config.value.
9793 // Use this instead of setOptions() because this.$input is not set up yet
9794 this.setOptionsData( config.options || [] );
9795
9796 // Parent constructor
9797 OO.ui.CheckboxMultiselectInputWidget.parent.call( this, config );
9798
9799 // Events
9800 this.checkboxMultiselectWidget.connect( this, { select: 'onCheckboxesSelect' } );
9801
9802 // Initialization
9803 this.$element
9804 .addClass( 'oo-ui-checkboxMultiselectInputWidget' )
9805 .append( this.checkboxMultiselectWidget.$element );
9806 // We don't use this.$input, but rather the CheckboxInputWidgets inside each option
9807 this.$input.detach();
9808 };
9809
9810 /* Setup */
9811
9812 OO.inheritClass( OO.ui.CheckboxMultiselectInputWidget, OO.ui.InputWidget );
9813
9814 /* Static Methods */
9815
9816 /**
9817 * @inheritdoc
9818 */
9819 OO.ui.CheckboxMultiselectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
9820 var state = OO.ui.CheckboxMultiselectInputWidget.parent.static.gatherPreInfuseState( node, config );
9821 state.value = $( node ).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
9822 .toArray().map( function ( el ) { return el.value; } );
9823 return state;
9824 };
9825
9826 /**
9827 * @inheritdoc
9828 */
9829 OO.ui.CheckboxMultiselectInputWidget.static.reusePreInfuseDOM = function ( node, config ) {
9830 config = OO.ui.CheckboxMultiselectInputWidget.parent.static.reusePreInfuseDOM( node, config );
9831 // Cannot reuse the `<input type=checkbox>` set
9832 delete config.$input;
9833 return config;
9834 };
9835
9836 /* Methods */
9837
9838 /**
9839 * @inheritdoc
9840 * @protected
9841 */
9842 OO.ui.CheckboxMultiselectInputWidget.prototype.getInputElement = function () {
9843 // Actually unused
9844 return $( '<unused>' );
9845 };
9846
9847 /**
9848 * Handles CheckboxMultiselectWidget select events.
9849 *
9850 * @private
9851 */
9852 OO.ui.CheckboxMultiselectInputWidget.prototype.onCheckboxesSelect = function () {
9853 this.setValue( this.checkboxMultiselectWidget.findSelectedItemsData() );
9854 };
9855
9856 /**
9857 * @inheritdoc
9858 */
9859 OO.ui.CheckboxMultiselectInputWidget.prototype.getValue = function () {
9860 var value = this.$element.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
9861 .toArray().map( function ( el ) { return el.value; } );
9862 if ( this.value !== value ) {
9863 this.setValue( value );
9864 }
9865 return this.value;
9866 };
9867
9868 /**
9869 * @inheritdoc
9870 */
9871 OO.ui.CheckboxMultiselectInputWidget.prototype.setValue = function ( value ) {
9872 value = this.cleanUpValue( value );
9873 this.checkboxMultiselectWidget.selectItemsByData( value );
9874 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.setValue.call( this, value );
9875 if ( this.optionsDirty ) {
9876 // We reached this from the constructor or from #setOptions.
9877 // We have to update the <select> element.
9878 this.updateOptionsInterface();
9879 }
9880 return this;
9881 };
9882
9883 /**
9884 * Clean up incoming value.
9885 *
9886 * @param {string[]} value Original value
9887 * @return {string[]} Cleaned up value
9888 */
9889 OO.ui.CheckboxMultiselectInputWidget.prototype.cleanUpValue = function ( value ) {
9890 var i, singleValue,
9891 cleanValue = [];
9892 if ( !Array.isArray( value ) ) {
9893 return cleanValue;
9894 }
9895 for ( i = 0; i < value.length; i++ ) {
9896 singleValue =
9897 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.cleanUpValue.call( this, value[ i ] );
9898 // Remove options that we don't have here
9899 if ( !this.checkboxMultiselectWidget.findItemFromData( singleValue ) ) {
9900 continue;
9901 }
9902 cleanValue.push( singleValue );
9903 }
9904 return cleanValue;
9905 };
9906
9907 /**
9908 * @inheritdoc
9909 */
9910 OO.ui.CheckboxMultiselectInputWidget.prototype.setDisabled = function ( state ) {
9911 this.checkboxMultiselectWidget.setDisabled( state );
9912 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.setDisabled.call( this, state );
9913 return this;
9914 };
9915
9916 /**
9917 * Set the options available for this input.
9918 *
9919 * @param {Object[]} options Array of menu options in the format `{ data: …, label: …, disabled: … }`
9920 * @chainable
9921 */
9922 OO.ui.CheckboxMultiselectInputWidget.prototype.setOptions = function ( options ) {
9923 var value = this.getValue();
9924
9925 this.setOptionsData( options );
9926
9927 // Re-set the value to update the visible interface (CheckboxMultiselectWidget).
9928 // This will also get rid of any stale options that we just removed.
9929 this.setValue( value );
9930
9931 return this;
9932 };
9933
9934 /**
9935 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
9936 *
9937 * This method may be called before the parent constructor, so various properties may not be
9938 * intialized yet.
9939 *
9940 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9941 * @private
9942 */
9943 OO.ui.CheckboxMultiselectInputWidget.prototype.setOptionsData = function ( options ) {
9944 var widget = this;
9945
9946 this.optionsDirty = true;
9947
9948 this.checkboxMultiselectWidget
9949 .clearItems()
9950 .addItems( options.map( function ( opt ) {
9951 var optValue, item, optDisabled;
9952 optValue =
9953 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.cleanUpValue.call( widget, opt.data );
9954 optDisabled = opt.disabled !== undefined ? opt.disabled : false;
9955 item = new OO.ui.CheckboxMultioptionWidget( {
9956 data: optValue,
9957 label: opt.label !== undefined ? opt.label : optValue,
9958 disabled: optDisabled
9959 } );
9960 // Set the 'name' and 'value' for form submission
9961 item.checkbox.$input.attr( 'name', widget.inputName );
9962 item.checkbox.setValue( optValue );
9963 return item;
9964 } ) );
9965 };
9966
9967 /**
9968 * Update the user-visible interface to match the internal list of options and value.
9969 *
9970 * This method must only be called after the parent constructor.
9971 *
9972 * @private
9973 */
9974 OO.ui.CheckboxMultiselectInputWidget.prototype.updateOptionsInterface = function () {
9975 var defaultValue = this.defaultValue;
9976
9977 this.checkboxMultiselectWidget.getItems().forEach( function ( item ) {
9978 // Remember original selection state. This property can be later used to check whether
9979 // the selection state of the input has been changed since it was created.
9980 var isDefault = defaultValue.indexOf( item.getData() ) !== -1;
9981 item.checkbox.defaultSelected = isDefault;
9982 item.checkbox.$input[ 0 ].defaultChecked = isDefault;
9983 } );
9984
9985 this.optionsDirty = false;
9986 };
9987
9988 /**
9989 * @inheritdoc
9990 */
9991 OO.ui.CheckboxMultiselectInputWidget.prototype.focus = function () {
9992 this.checkboxMultiselectWidget.focus();
9993 return this;
9994 };
9995
9996 /**
9997 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
9998 * size of the field as well as its presentation. In addition, these widgets can be configured
9999 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
10000 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
10001 * which modifies incoming values rather than validating them.
10002 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
10003 *
10004 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
10005 *
10006 * @example
10007 * // Example of a text input widget
10008 * var textInput = new OO.ui.TextInputWidget( {
10009 * value: 'Text input'
10010 * } )
10011 * $( 'body' ).append( textInput.$element );
10012 *
10013 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
10014 *
10015 * @class
10016 * @extends OO.ui.InputWidget
10017 * @mixins OO.ui.mixin.IconElement
10018 * @mixins OO.ui.mixin.IndicatorElement
10019 * @mixins OO.ui.mixin.PendingElement
10020 * @mixins OO.ui.mixin.LabelElement
10021 *
10022 * @constructor
10023 * @param {Object} [config] Configuration options
10024 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password'
10025 * 'email', 'url' or 'number'.
10026 * @cfg {string} [placeholder] Placeholder text
10027 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
10028 * instruct the browser to focus this widget.
10029 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
10030 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
10031 *
10032 * For unfortunate historical reasons, this counts the number of UTF-16 code units rather than
10033 * Unicode codepoints, which means that codepoints outside the Basic Multilingual Plane (e.g.
10034 * many emojis) count as 2 characters each.
10035 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
10036 * the value or placeholder text: `'before'` or `'after'`
10037 * @cfg {boolean} [required=false] Mark the field as required with `true`. Implies `indicator: 'required'`.
10038 * Note that `false` & setting `indicator: 'required' will result in no indicator shown.
10039 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
10040 * @cfg {boolean} [spellcheck] Should the browser support spellcheck for this field (`undefined` means
10041 * leaving it up to the browser).
10042 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
10043 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
10044 * (the value must contain only numbers); when RegExp, a regular expression that must match the
10045 * value for it to be considered valid; when Function, a function receiving the value as parameter
10046 * that must return true, or promise resolving to true, for it to be considered valid.
10047 */
10048 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
10049 // Configuration initialization
10050 config = $.extend( {
10051 type: 'text',
10052 labelPosition: 'after'
10053 }, config );
10054
10055 if ( config.multiline ) {
10056 OO.ui.warnDeprecation( 'TextInputWidget: config.multiline is deprecated. Use the MultilineTextInputWidget instead. See T130434.' );
10057 return new OO.ui.MultilineTextInputWidget( config );
10058 }
10059
10060 // Parent constructor
10061 OO.ui.TextInputWidget.parent.call( this, config );
10062
10063 // Mixin constructors
10064 OO.ui.mixin.IconElement.call( this, config );
10065 OO.ui.mixin.IndicatorElement.call( this, config );
10066 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$input } ) );
10067 OO.ui.mixin.LabelElement.call( this, config );
10068
10069 // Properties
10070 this.type = this.getSaneType( config );
10071 this.readOnly = false;
10072 this.required = false;
10073 this.validate = null;
10074 this.styleHeight = null;
10075 this.scrollWidth = null;
10076
10077 this.setValidation( config.validate );
10078 this.setLabelPosition( config.labelPosition );
10079
10080 // Events
10081 this.$input.on( {
10082 keypress: this.onKeyPress.bind( this ),
10083 blur: this.onBlur.bind( this ),
10084 focus: this.onFocus.bind( this )
10085 } );
10086 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
10087 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
10088 this.on( 'labelChange', this.updatePosition.bind( this ) );
10089 this.on( 'change', OO.ui.debounce( this.onDebouncedChange.bind( this ), 250 ) );
10090
10091 // Initialization
10092 this.$element
10093 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type )
10094 .append( this.$icon, this.$indicator );
10095 this.setReadOnly( !!config.readOnly );
10096 this.setRequired( !!config.required );
10097 if ( config.placeholder !== undefined ) {
10098 this.$input.attr( 'placeholder', config.placeholder );
10099 }
10100 if ( config.maxLength !== undefined ) {
10101 this.$input.attr( 'maxlength', config.maxLength );
10102 }
10103 if ( config.autofocus ) {
10104 this.$input.attr( 'autofocus', 'autofocus' );
10105 }
10106 if ( config.autocomplete === false ) {
10107 this.$input.attr( 'autocomplete', 'off' );
10108 // Turning off autocompletion also disables "form caching" when the user navigates to a
10109 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
10110 $( window ).on( {
10111 beforeunload: function () {
10112 this.$input.removeAttr( 'autocomplete' );
10113 }.bind( this ),
10114 pageshow: function () {
10115 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
10116 // whole page... it shouldn't hurt, though.
10117 this.$input.attr( 'autocomplete', 'off' );
10118 }.bind( this )
10119 } );
10120 }
10121 if ( config.spellcheck !== undefined ) {
10122 this.$input.attr( 'spellcheck', config.spellcheck ? 'true' : 'false' );
10123 }
10124 if ( this.label ) {
10125 this.isWaitingToBeAttached = true;
10126 this.installParentChangeDetector();
10127 }
10128 };
10129
10130 /* Setup */
10131
10132 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
10133 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IconElement );
10134 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IndicatorElement );
10135 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.PendingElement );
10136 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.LabelElement );
10137
10138 /* Static Properties */
10139
10140 OO.ui.TextInputWidget.static.validationPatterns = {
10141 'non-empty': /.+/,
10142 integer: /^\d+$/
10143 };
10144
10145 /* Events */
10146
10147 /**
10148 * An `enter` event is emitted when the user presses 'enter' inside the text box.
10149 *
10150 * @event enter
10151 */
10152
10153 /* Methods */
10154
10155 /**
10156 * Handle icon mouse down events.
10157 *
10158 * @private
10159 * @param {jQuery.Event} e Mouse down event
10160 */
10161 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
10162 if ( e.which === OO.ui.MouseButtons.LEFT ) {
10163 this.focus();
10164 return false;
10165 }
10166 };
10167
10168 /**
10169 * Handle indicator mouse down events.
10170 *
10171 * @private
10172 * @param {jQuery.Event} e Mouse down event
10173 */
10174 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
10175 if ( e.which === OO.ui.MouseButtons.LEFT ) {
10176 this.focus();
10177 return false;
10178 }
10179 };
10180
10181 /**
10182 * Handle key press events.
10183 *
10184 * @private
10185 * @param {jQuery.Event} e Key press event
10186 * @fires enter If enter key is pressed
10187 */
10188 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
10189 if ( e.which === OO.ui.Keys.ENTER ) {
10190 this.emit( 'enter', e );
10191 }
10192 };
10193
10194 /**
10195 * Handle blur events.
10196 *
10197 * @private
10198 * @param {jQuery.Event} e Blur event
10199 */
10200 OO.ui.TextInputWidget.prototype.onBlur = function () {
10201 this.setValidityFlag();
10202 };
10203
10204 /**
10205 * Handle focus events.
10206 *
10207 * @private
10208 * @param {jQuery.Event} e Focus event
10209 */
10210 OO.ui.TextInputWidget.prototype.onFocus = function () {
10211 if ( this.isWaitingToBeAttached ) {
10212 // If we've received focus, then we must be attached to the document, and if
10213 // isWaitingToBeAttached is still true, that means the handler never fired. Fire it now.
10214 this.onElementAttach();
10215 }
10216 this.setValidityFlag( true );
10217 };
10218
10219 /**
10220 * Handle element attach events.
10221 *
10222 * @private
10223 * @param {jQuery.Event} e Element attach event
10224 */
10225 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
10226 this.isWaitingToBeAttached = false;
10227 // Any previously calculated size is now probably invalid if we reattached elsewhere
10228 this.valCache = null;
10229 this.positionLabel();
10230 };
10231
10232 /**
10233 * Handle debounced change events.
10234 *
10235 * @param {string} value
10236 * @private
10237 */
10238 OO.ui.TextInputWidget.prototype.onDebouncedChange = function () {
10239 this.setValidityFlag();
10240 };
10241
10242 /**
10243 * Check if the input is {@link #readOnly read-only}.
10244 *
10245 * @return {boolean}
10246 */
10247 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
10248 return this.readOnly;
10249 };
10250
10251 /**
10252 * Set the {@link #readOnly read-only} state of the input.
10253 *
10254 * @param {boolean} state Make input read-only
10255 * @chainable
10256 */
10257 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
10258 this.readOnly = !!state;
10259 this.$input.prop( 'readOnly', this.readOnly );
10260 return this;
10261 };
10262
10263 /**
10264 * Check if the input is {@link #required required}.
10265 *
10266 * @return {boolean}
10267 */
10268 OO.ui.TextInputWidget.prototype.isRequired = function () {
10269 return this.required;
10270 };
10271
10272 /**
10273 * Set the {@link #required required} state of the input.
10274 *
10275 * @param {boolean} state Make input required
10276 * @chainable
10277 */
10278 OO.ui.TextInputWidget.prototype.setRequired = function ( state ) {
10279 this.required = !!state;
10280 if ( this.required ) {
10281 this.$input
10282 .prop( 'required', true )
10283 .attr( 'aria-required', 'true' );
10284 if ( this.getIndicator() === null ) {
10285 this.setIndicator( 'required' );
10286 }
10287 } else {
10288 this.$input
10289 .prop( 'required', false )
10290 .removeAttr( 'aria-required' );
10291 if ( this.getIndicator() === 'required' ) {
10292 this.setIndicator( null );
10293 }
10294 }
10295 return this;
10296 };
10297
10298 /**
10299 * Support function for making #onElementAttach work across browsers.
10300 *
10301 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
10302 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
10303 *
10304 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
10305 * first time that the element gets attached to the documented.
10306 */
10307 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
10308 var mutationObserver, onRemove, topmostNode, fakeParentNode,
10309 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
10310 widget = this;
10311
10312 if ( MutationObserver ) {
10313 // The new way. If only it wasn't so ugly.
10314
10315 if ( this.isElementAttached() ) {
10316 // Widget is attached already, do nothing. This breaks the functionality of this function when
10317 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
10318 // would require observation of the whole document, which would hurt performance of other,
10319 // more important code.
10320 return;
10321 }
10322
10323 // Find topmost node in the tree
10324 topmostNode = this.$element[ 0 ];
10325 while ( topmostNode.parentNode ) {
10326 topmostNode = topmostNode.parentNode;
10327 }
10328
10329 // We have no way to detect the $element being attached somewhere without observing the entire
10330 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
10331 // parent node of $element, and instead detect when $element is removed from it (and thus
10332 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
10333 // doesn't get attached, we end up back here and create the parent.
10334
10335 mutationObserver = new MutationObserver( function ( mutations ) {
10336 var i, j, removedNodes;
10337 for ( i = 0; i < mutations.length; i++ ) {
10338 removedNodes = mutations[ i ].removedNodes;
10339 for ( j = 0; j < removedNodes.length; j++ ) {
10340 if ( removedNodes[ j ] === topmostNode ) {
10341 setTimeout( onRemove, 0 );
10342 return;
10343 }
10344 }
10345 }
10346 } );
10347
10348 onRemove = function () {
10349 // If the node was attached somewhere else, report it
10350 if ( widget.isElementAttached() ) {
10351 widget.onElementAttach();
10352 }
10353 mutationObserver.disconnect();
10354 widget.installParentChangeDetector();
10355 };
10356
10357 // Create a fake parent and observe it
10358 fakeParentNode = $( '<div>' ).append( topmostNode )[ 0 ];
10359 mutationObserver.observe( fakeParentNode, { childList: true } );
10360 } else {
10361 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
10362 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
10363 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
10364 }
10365 };
10366
10367 /**
10368 * @inheritdoc
10369 * @protected
10370 */
10371 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
10372 if ( this.getSaneType( config ) === 'number' ) {
10373 return $( '<input>' )
10374 .attr( 'step', 'any' )
10375 .attr( 'type', 'number' );
10376 } else {
10377 return $( '<input>' ).attr( 'type', this.getSaneType( config ) );
10378 }
10379 };
10380
10381 /**
10382 * Get sanitized value for 'type' for given config.
10383 *
10384 * @param {Object} config Configuration options
10385 * @return {string|null}
10386 * @protected
10387 */
10388 OO.ui.TextInputWidget.prototype.getSaneType = function ( config ) {
10389 var allowedTypes = [
10390 'text',
10391 'password',
10392 'email',
10393 'url',
10394 'number'
10395 ];
10396 return allowedTypes.indexOf( config.type ) !== -1 ? config.type : 'text';
10397 };
10398
10399 /**
10400 * Focus the input and select a specified range within the text.
10401 *
10402 * @param {number} from Select from offset
10403 * @param {number} [to] Select to offset, defaults to from
10404 * @chainable
10405 */
10406 OO.ui.TextInputWidget.prototype.selectRange = function ( from, to ) {
10407 var isBackwards, start, end,
10408 input = this.$input[ 0 ];
10409
10410 to = to || from;
10411
10412 isBackwards = to < from;
10413 start = isBackwards ? to : from;
10414 end = isBackwards ? from : to;
10415
10416 this.focus();
10417
10418 try {
10419 input.setSelectionRange( start, end, isBackwards ? 'backward' : 'forward' );
10420 } catch ( e ) {
10421 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
10422 // Rather than expensively check if the input is attached every time, just check
10423 // if it was the cause of an error being thrown. If not, rethrow the error.
10424 if ( this.getElementDocument().body.contains( input ) ) {
10425 throw e;
10426 }
10427 }
10428 return this;
10429 };
10430
10431 /**
10432 * Get an object describing the current selection range in a directional manner
10433 *
10434 * @return {Object} Object containing 'from' and 'to' offsets
10435 */
10436 OO.ui.TextInputWidget.prototype.getRange = function () {
10437 var input = this.$input[ 0 ],
10438 start = input.selectionStart,
10439 end = input.selectionEnd,
10440 isBackwards = input.selectionDirection === 'backward';
10441
10442 return {
10443 from: isBackwards ? end : start,
10444 to: isBackwards ? start : end
10445 };
10446 };
10447
10448 /**
10449 * Get the length of the text input value.
10450 *
10451 * This could differ from the length of #getValue if the
10452 * value gets filtered
10453 *
10454 * @return {number} Input length
10455 */
10456 OO.ui.TextInputWidget.prototype.getInputLength = function () {
10457 return this.$input[ 0 ].value.length;
10458 };
10459
10460 /**
10461 * Focus the input and select the entire text.
10462 *
10463 * @chainable
10464 */
10465 OO.ui.TextInputWidget.prototype.select = function () {
10466 return this.selectRange( 0, this.getInputLength() );
10467 };
10468
10469 /**
10470 * Focus the input and move the cursor to the start.
10471 *
10472 * @chainable
10473 */
10474 OO.ui.TextInputWidget.prototype.moveCursorToStart = function () {
10475 return this.selectRange( 0 );
10476 };
10477
10478 /**
10479 * Focus the input and move the cursor to the end.
10480 *
10481 * @chainable
10482 */
10483 OO.ui.TextInputWidget.prototype.moveCursorToEnd = function () {
10484 return this.selectRange( this.getInputLength() );
10485 };
10486
10487 /**
10488 * Insert new content into the input.
10489 *
10490 * @param {string} content Content to be inserted
10491 * @chainable
10492 */
10493 OO.ui.TextInputWidget.prototype.insertContent = function ( content ) {
10494 var start, end,
10495 range = this.getRange(),
10496 value = this.getValue();
10497
10498 start = Math.min( range.from, range.to );
10499 end = Math.max( range.from, range.to );
10500
10501 this.setValue( value.slice( 0, start ) + content + value.slice( end ) );
10502 this.selectRange( start + content.length );
10503 return this;
10504 };
10505
10506 /**
10507 * Insert new content either side of a selection.
10508 *
10509 * @param {string} pre Content to be inserted before the selection
10510 * @param {string} post Content to be inserted after the selection
10511 * @chainable
10512 */
10513 OO.ui.TextInputWidget.prototype.encapsulateContent = function ( pre, post ) {
10514 var start, end,
10515 range = this.getRange(),
10516 offset = pre.length;
10517
10518 start = Math.min( range.from, range.to );
10519 end = Math.max( range.from, range.to );
10520
10521 this.selectRange( start ).insertContent( pre );
10522 this.selectRange( offset + end ).insertContent( post );
10523
10524 this.selectRange( offset + start, offset + end );
10525 return this;
10526 };
10527
10528 /**
10529 * Set the validation pattern.
10530 *
10531 * The validation pattern is either a regular expression, a function, or the symbolic name of a
10532 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
10533 * value must contain only numbers).
10534 *
10535 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
10536 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
10537 */
10538 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
10539 if ( validate instanceof RegExp || validate instanceof Function ) {
10540 this.validate = validate;
10541 } else {
10542 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
10543 }
10544 };
10545
10546 /**
10547 * Sets the 'invalid' flag appropriately.
10548 *
10549 * @param {boolean} [isValid] Optionally override validation result
10550 */
10551 OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) {
10552 var widget = this,
10553 setFlag = function ( valid ) {
10554 if ( !valid ) {
10555 widget.$input.attr( 'aria-invalid', 'true' );
10556 } else {
10557 widget.$input.removeAttr( 'aria-invalid' );
10558 }
10559 widget.setFlags( { invalid: !valid } );
10560 };
10561
10562 if ( isValid !== undefined ) {
10563 setFlag( isValid );
10564 } else {
10565 this.getValidity().then( function () {
10566 setFlag( true );
10567 }, function () {
10568 setFlag( false );
10569 } );
10570 }
10571 };
10572
10573 /**
10574 * Get the validity of current value.
10575 *
10576 * This method returns a promise that resolves if the value is valid and rejects if
10577 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
10578 *
10579 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
10580 */
10581 OO.ui.TextInputWidget.prototype.getValidity = function () {
10582 var result;
10583
10584 function rejectOrResolve( valid ) {
10585 if ( valid ) {
10586 return $.Deferred().resolve().promise();
10587 } else {
10588 return $.Deferred().reject().promise();
10589 }
10590 }
10591
10592 // Check browser validity and reject if it is invalid
10593 if (
10594 this.$input[ 0 ].checkValidity !== undefined &&
10595 this.$input[ 0 ].checkValidity() === false
10596 ) {
10597 return rejectOrResolve( false );
10598 }
10599
10600 // Run our checks if the browser thinks the field is valid
10601 if ( this.validate instanceof Function ) {
10602 result = this.validate( this.getValue() );
10603 if ( result && $.isFunction( result.promise ) ) {
10604 return result.promise().then( function ( valid ) {
10605 return rejectOrResolve( valid );
10606 } );
10607 } else {
10608 return rejectOrResolve( result );
10609 }
10610 } else {
10611 return rejectOrResolve( this.getValue().match( this.validate ) );
10612 }
10613 };
10614
10615 /**
10616 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
10617 *
10618 * @param {string} labelPosition Label position, 'before' or 'after'
10619 * @chainable
10620 */
10621 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
10622 this.labelPosition = labelPosition;
10623 if ( this.label ) {
10624 // If there is no label and we only change the position, #updatePosition is a no-op,
10625 // but it takes really a lot of work to do nothing.
10626 this.updatePosition();
10627 }
10628 return this;
10629 };
10630
10631 /**
10632 * Update the position of the inline label.
10633 *
10634 * This method is called by #setLabelPosition, and can also be called on its own if
10635 * something causes the label to be mispositioned.
10636 *
10637 * @chainable
10638 */
10639 OO.ui.TextInputWidget.prototype.updatePosition = function () {
10640 var after = this.labelPosition === 'after';
10641
10642 this.$element
10643 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
10644 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
10645
10646 this.valCache = null;
10647 this.scrollWidth = null;
10648 this.positionLabel();
10649
10650 return this;
10651 };
10652
10653 /**
10654 * Position the label by setting the correct padding on the input.
10655 *
10656 * @private
10657 * @chainable
10658 */
10659 OO.ui.TextInputWidget.prototype.positionLabel = function () {
10660 var after, rtl, property, newCss;
10661
10662 if ( this.isWaitingToBeAttached ) {
10663 // #onElementAttach will be called soon, which calls this method
10664 return this;
10665 }
10666
10667 newCss = {
10668 'padding-right': '',
10669 'padding-left': ''
10670 };
10671
10672 if ( this.label ) {
10673 this.$element.append( this.$label );
10674 } else {
10675 this.$label.detach();
10676 // Clear old values if present
10677 this.$input.css( newCss );
10678 return;
10679 }
10680
10681 after = this.labelPosition === 'after';
10682 rtl = this.$element.css( 'direction' ) === 'rtl';
10683 property = after === rtl ? 'padding-left' : 'padding-right';
10684
10685 newCss[ property ] = this.$label.outerWidth( true ) + ( after ? this.scrollWidth : 0 );
10686 // We have to clear the padding on the other side, in case the element direction changed
10687 this.$input.css( newCss );
10688
10689 return this;
10690 };
10691
10692 /**
10693 * @class
10694 * @extends OO.ui.TextInputWidget
10695 *
10696 * @constructor
10697 * @param {Object} [config] Configuration options
10698 */
10699 OO.ui.SearchInputWidget = function OoUiSearchInputWidget( config ) {
10700 config = $.extend( {
10701 icon: 'search'
10702 }, config );
10703
10704 // Parent constructor
10705 OO.ui.SearchInputWidget.parent.call( this, config );
10706
10707 // Events
10708 this.connect( this, {
10709 change: 'onChange'
10710 } );
10711
10712 // Initialization
10713 this.updateSearchIndicator();
10714 this.connect( this, {
10715 disable: 'onDisable'
10716 } );
10717 };
10718
10719 /* Setup */
10720
10721 OO.inheritClass( OO.ui.SearchInputWidget, OO.ui.TextInputWidget );
10722
10723 /* Methods */
10724
10725 /**
10726 * @inheritdoc
10727 * @protected
10728 */
10729 OO.ui.SearchInputWidget.prototype.getSaneType = function () {
10730 return 'search';
10731 };
10732
10733 /**
10734 * @inheritdoc
10735 */
10736 OO.ui.SearchInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
10737 if ( e.which === OO.ui.MouseButtons.LEFT ) {
10738 // Clear the text field
10739 this.setValue( '' );
10740 this.focus();
10741 return false;
10742 }
10743 };
10744
10745 /**
10746 * Update the 'clear' indicator displayed on type: 'search' text
10747 * fields, hiding it when the field is already empty or when it's not
10748 * editable.
10749 */
10750 OO.ui.SearchInputWidget.prototype.updateSearchIndicator = function () {
10751 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
10752 this.setIndicator( null );
10753 } else {
10754 this.setIndicator( 'clear' );
10755 }
10756 };
10757
10758 /**
10759 * Handle change events.
10760 *
10761 * @private
10762 */
10763 OO.ui.SearchInputWidget.prototype.onChange = function () {
10764 this.updateSearchIndicator();
10765 };
10766
10767 /**
10768 * Handle disable events.
10769 *
10770 * @param {boolean} disabled Element is disabled
10771 * @private
10772 */
10773 OO.ui.SearchInputWidget.prototype.onDisable = function () {
10774 this.updateSearchIndicator();
10775 };
10776
10777 /**
10778 * @inheritdoc
10779 */
10780 OO.ui.SearchInputWidget.prototype.setReadOnly = function ( state ) {
10781 OO.ui.SearchInputWidget.parent.prototype.setReadOnly.call( this, state );
10782 this.updateSearchIndicator();
10783 return this;
10784 };
10785
10786 /**
10787 * @class
10788 * @extends OO.ui.TextInputWidget
10789 *
10790 * @constructor
10791 * @param {Object} [config] Configuration options
10792 * @cfg {number} [rows] Number of visible lines in textarea. If used with `autosize`,
10793 * specifies minimum number of rows to display.
10794 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
10795 * Use the #maxRows config to specify a maximum number of displayed rows.
10796 * @cfg {number} [maxRows] Maximum number of rows to display when #autosize is set to true.
10797 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
10798 */
10799 OO.ui.MultilineTextInputWidget = function OoUiMultilineTextInputWidget( config ) {
10800 config = $.extend( {
10801 type: 'text'
10802 }, config );
10803 config.multiline = false;
10804 // Parent constructor
10805 OO.ui.MultilineTextInputWidget.parent.call( this, config );
10806
10807 // Properties
10808 this.multiline = true;
10809 this.autosize = !!config.autosize;
10810 this.minRows = config.rows !== undefined ? config.rows : '';
10811 this.maxRows = config.maxRows || Math.max( 2 * ( this.minRows || 0 ), 10 );
10812
10813 // Clone for resizing
10814 if ( this.autosize ) {
10815 this.$clone = this.$input
10816 .clone()
10817 .insertAfter( this.$input )
10818 .attr( 'aria-hidden', 'true' )
10819 .addClass( 'oo-ui-element-hidden' );
10820 }
10821
10822 // Events
10823 this.connect( this, {
10824 change: 'onChange'
10825 } );
10826
10827 // Initialization
10828 if ( this.multiline && config.rows ) {
10829 this.$input.attr( 'rows', config.rows );
10830 }
10831 if ( this.autosize ) {
10832 this.$input.addClass( 'oo-ui-textInputWidget-autosized' );
10833 this.isWaitingToBeAttached = true;
10834 this.installParentChangeDetector();
10835 }
10836 };
10837
10838 /* Setup */
10839
10840 OO.inheritClass( OO.ui.MultilineTextInputWidget, OO.ui.TextInputWidget );
10841
10842 /* Static Methods */
10843
10844 /**
10845 * @inheritdoc
10846 */
10847 OO.ui.MultilineTextInputWidget.static.gatherPreInfuseState = function ( node, config ) {
10848 var state = OO.ui.MultilineTextInputWidget.parent.static.gatherPreInfuseState( node, config );
10849 state.scrollTop = config.$input.scrollTop();
10850 return state;
10851 };
10852
10853 /* Methods */
10854
10855 /**
10856 * @inheritdoc
10857 */
10858 OO.ui.MultilineTextInputWidget.prototype.onElementAttach = function () {
10859 OO.ui.MultilineTextInputWidget.parent.prototype.onElementAttach.call( this );
10860 this.adjustSize();
10861 };
10862
10863 /**
10864 * Handle change events.
10865 *
10866 * @private
10867 */
10868 OO.ui.MultilineTextInputWidget.prototype.onChange = function () {
10869 this.adjustSize();
10870 };
10871
10872 /**
10873 * @inheritdoc
10874 */
10875 OO.ui.MultilineTextInputWidget.prototype.updatePosition = function () {
10876 OO.ui.MultilineTextInputWidget.parent.prototype.updatePosition.call( this );
10877 this.adjustSize();
10878 };
10879
10880 /**
10881 * @inheritdoc
10882 *
10883 * Modify to emit 'enter' on Ctrl/Meta+Enter, instead of plain Enter
10884 */
10885 OO.ui.MultilineTextInputWidget.prototype.onKeyPress = function ( e ) {
10886 if (
10887 ( e.which === OO.ui.Keys.ENTER && ( e.ctrlKey || e.metaKey ) ) ||
10888 // Some platforms emit keycode 10 for ctrl+enter in a textarea
10889 e.which === 10
10890 ) {
10891 this.emit( 'enter', e );
10892 }
10893 };
10894
10895 /**
10896 * Automatically adjust the size of the text input.
10897 *
10898 * This only affects multiline inputs that are {@link #autosize autosized}.
10899 *
10900 * @chainable
10901 * @fires resize
10902 */
10903 OO.ui.MultilineTextInputWidget.prototype.adjustSize = function () {
10904 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError,
10905 idealHeight, newHeight, scrollWidth, property;
10906
10907 if ( this.$input.val() !== this.valCache ) {
10908 if ( this.autosize ) {
10909 this.$clone
10910 .val( this.$input.val() )
10911 .attr( 'rows', this.minRows )
10912 // Set inline height property to 0 to measure scroll height
10913 .css( 'height', 0 );
10914
10915 this.$clone.removeClass( 'oo-ui-element-hidden' );
10916
10917 this.valCache = this.$input.val();
10918
10919 scrollHeight = this.$clone[ 0 ].scrollHeight;
10920
10921 // Remove inline height property to measure natural heights
10922 this.$clone.css( 'height', '' );
10923 innerHeight = this.$clone.innerHeight();
10924 outerHeight = this.$clone.outerHeight();
10925
10926 // Measure max rows height
10927 this.$clone
10928 .attr( 'rows', this.maxRows )
10929 .css( 'height', 'auto' )
10930 .val( '' );
10931 maxInnerHeight = this.$clone.innerHeight();
10932
10933 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
10934 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
10935 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
10936 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
10937
10938 this.$clone.addClass( 'oo-ui-element-hidden' );
10939
10940 // Only apply inline height when expansion beyond natural height is needed
10941 // Use the difference between the inner and outer height as a buffer
10942 newHeight = idealHeight > innerHeight ? idealHeight + ( outerHeight - innerHeight ) : '';
10943 if ( newHeight !== this.styleHeight ) {
10944 this.$input.css( 'height', newHeight );
10945 this.styleHeight = newHeight;
10946 this.emit( 'resize' );
10947 }
10948 }
10949 scrollWidth = this.$input[ 0 ].offsetWidth - this.$input[ 0 ].clientWidth;
10950 if ( scrollWidth !== this.scrollWidth ) {
10951 property = this.$element.css( 'direction' ) === 'rtl' ? 'left' : 'right';
10952 // Reset
10953 this.$label.css( { right: '', left: '' } );
10954 this.$indicator.css( { right: '', left: '' } );
10955
10956 if ( scrollWidth ) {
10957 this.$indicator.css( property, scrollWidth );
10958 if ( this.labelPosition === 'after' ) {
10959 this.$label.css( property, scrollWidth );
10960 }
10961 }
10962
10963 this.scrollWidth = scrollWidth;
10964 this.positionLabel();
10965 }
10966 }
10967 return this;
10968 };
10969
10970 /**
10971 * @inheritdoc
10972 * @protected
10973 */
10974 OO.ui.MultilineTextInputWidget.prototype.getInputElement = function () {
10975 return $( '<textarea>' );
10976 };
10977
10978 /**
10979 * Check if the input supports multiple lines.
10980 *
10981 * @return {boolean}
10982 */
10983 OO.ui.MultilineTextInputWidget.prototype.isMultiline = function () {
10984 return !!this.multiline;
10985 };
10986
10987 /**
10988 * Check if the input automatically adjusts its size.
10989 *
10990 * @return {boolean}
10991 */
10992 OO.ui.MultilineTextInputWidget.prototype.isAutosizing = function () {
10993 return !!this.autosize;
10994 };
10995
10996 /**
10997 * @inheritdoc
10998 */
10999 OO.ui.MultilineTextInputWidget.prototype.restorePreInfuseState = function ( state ) {
11000 OO.ui.MultilineTextInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
11001 if ( state.scrollTop !== undefined ) {
11002 this.$input.scrollTop( state.scrollTop );
11003 }
11004 };
11005
11006 /**
11007 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
11008 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
11009 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
11010 *
11011 * - by typing a value in the text input field. If the value exactly matches the value of a menu
11012 * option, that option will appear to be selected.
11013 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
11014 * input field.
11015 *
11016 * After the user chooses an option, its `data` will be used as a new value for the widget.
11017 * A `label` also can be specified for each option: if given, it will be shown instead of the
11018 * `data` in the dropdown menu.
11019 *
11020 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
11021 *
11022 * For more information about menus and options, please see the [OOUI documentation on MediaWiki][1].
11023 *
11024 * @example
11025 * // Example: A ComboBoxInputWidget.
11026 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11027 * value: 'Option 1',
11028 * options: [
11029 * { data: 'Option 1' },
11030 * { data: 'Option 2' },
11031 * { data: 'Option 3' }
11032 * ]
11033 * } );
11034 * $( 'body' ).append( comboBox.$element );
11035 *
11036 * @example
11037 * // Example: A ComboBoxInputWidget with additional option labels.
11038 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11039 * value: 'Option 1',
11040 * options: [
11041 * {
11042 * data: 'Option 1',
11043 * label: 'Option One'
11044 * },
11045 * {
11046 * data: 'Option 2',
11047 * label: 'Option Two'
11048 * },
11049 * {
11050 * data: 'Option 3',
11051 * label: 'Option Three'
11052 * }
11053 * ]
11054 * } );
11055 * $( 'body' ).append( comboBox.$element );
11056 *
11057 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
11058 *
11059 * @class
11060 * @extends OO.ui.TextInputWidget
11061 *
11062 * @constructor
11063 * @param {Object} [config] Configuration options
11064 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
11065 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
11066 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
11067 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
11068 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
11069 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11070 */
11071 OO.ui.ComboBoxInputWidget = function OoUiComboBoxInputWidget( config ) {
11072 // Configuration initialization
11073 config = $.extend( {
11074 autocomplete: false
11075 }, config );
11076
11077 // ComboBoxInputWidget shouldn't support `multiline`
11078 config.multiline = false;
11079
11080 // See InputWidget#reusePreInfuseDOM about `config.$input`
11081 if ( config.$input ) {
11082 config.$input.removeAttr( 'list' );
11083 }
11084
11085 // Parent constructor
11086 OO.ui.ComboBoxInputWidget.parent.call( this, config );
11087
11088 // Properties
11089 this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
11090 this.dropdownButton = new OO.ui.ButtonWidget( {
11091 classes: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ],
11092 indicator: 'down',
11093 disabled: this.disabled
11094 } );
11095 this.menu = new OO.ui.MenuSelectWidget( $.extend(
11096 {
11097 widget: this,
11098 input: this,
11099 $floatableContainer: this.$element,
11100 disabled: this.isDisabled()
11101 },
11102 config.menu
11103 ) );
11104
11105 // Events
11106 this.connect( this, {
11107 change: 'onInputChange',
11108 enter: 'onInputEnter'
11109 } );
11110 this.dropdownButton.connect( this, {
11111 click: 'onDropdownButtonClick'
11112 } );
11113 this.menu.connect( this, {
11114 choose: 'onMenuChoose',
11115 add: 'onMenuItemsChange',
11116 remove: 'onMenuItemsChange',
11117 toggle: 'onMenuToggle'
11118 } );
11119
11120 // Initialization
11121 this.$input.attr( {
11122 role: 'combobox',
11123 'aria-owns': this.menu.getElementId(),
11124 'aria-autocomplete': 'list'
11125 } );
11126 // Do not override options set via config.menu.items
11127 if ( config.options !== undefined ) {
11128 this.setOptions( config.options );
11129 }
11130 this.$field = $( '<div>' )
11131 .addClass( 'oo-ui-comboBoxInputWidget-field' )
11132 .append( this.$input, this.dropdownButton.$element );
11133 this.$element
11134 .addClass( 'oo-ui-comboBoxInputWidget' )
11135 .append( this.$field );
11136 this.$overlay.append( this.menu.$element );
11137 this.onMenuItemsChange();
11138 };
11139
11140 /* Setup */
11141
11142 OO.inheritClass( OO.ui.ComboBoxInputWidget, OO.ui.TextInputWidget );
11143
11144 /* Methods */
11145
11146 /**
11147 * Get the combobox's menu.
11148 *
11149 * @return {OO.ui.MenuSelectWidget} Menu widget
11150 */
11151 OO.ui.ComboBoxInputWidget.prototype.getMenu = function () {
11152 return this.menu;
11153 };
11154
11155 /**
11156 * Get the combobox's text input widget.
11157 *
11158 * @return {OO.ui.TextInputWidget} Text input widget
11159 */
11160 OO.ui.ComboBoxInputWidget.prototype.getInput = function () {
11161 return this;
11162 };
11163
11164 /**
11165 * Handle input change events.
11166 *
11167 * @private
11168 * @param {string} value New value
11169 */
11170 OO.ui.ComboBoxInputWidget.prototype.onInputChange = function ( value ) {
11171 var match = this.menu.findItemFromData( value );
11172
11173 this.menu.selectItem( match );
11174 if ( this.menu.findHighlightedItem() ) {
11175 this.menu.highlightItem( match );
11176 }
11177
11178 if ( !this.isDisabled() ) {
11179 this.menu.toggle( true );
11180 }
11181 };
11182
11183 /**
11184 * Handle input enter events.
11185 *
11186 * @private
11187 */
11188 OO.ui.ComboBoxInputWidget.prototype.onInputEnter = function () {
11189 if ( !this.isDisabled() ) {
11190 this.menu.toggle( false );
11191 }
11192 };
11193
11194 /**
11195 * Handle button click events.
11196 *
11197 * @private
11198 */
11199 OO.ui.ComboBoxInputWidget.prototype.onDropdownButtonClick = function () {
11200 this.menu.toggle();
11201 this.focus();
11202 };
11203
11204 /**
11205 * Handle menu choose events.
11206 *
11207 * @private
11208 * @param {OO.ui.OptionWidget} item Chosen item
11209 */
11210 OO.ui.ComboBoxInputWidget.prototype.onMenuChoose = function ( item ) {
11211 this.setValue( item.getData() );
11212 };
11213
11214 /**
11215 * Handle menu item change events.
11216 *
11217 * @private
11218 */
11219 OO.ui.ComboBoxInputWidget.prototype.onMenuItemsChange = function () {
11220 var match = this.menu.findItemFromData( this.getValue() );
11221 this.menu.selectItem( match );
11222 if ( this.menu.findHighlightedItem() ) {
11223 this.menu.highlightItem( match );
11224 }
11225 this.$element.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu.isEmpty() );
11226 };
11227
11228 /**
11229 * Handle menu toggle events.
11230 *
11231 * @private
11232 * @param {boolean} isVisible Open state of the menu
11233 */
11234 OO.ui.ComboBoxInputWidget.prototype.onMenuToggle = function ( isVisible ) {
11235 this.$element.toggleClass( 'oo-ui-comboBoxInputWidget-open', isVisible );
11236 };
11237
11238 /**
11239 * @inheritdoc
11240 */
11241 OO.ui.ComboBoxInputWidget.prototype.setDisabled = function ( disabled ) {
11242 // Parent method
11243 OO.ui.ComboBoxInputWidget.parent.prototype.setDisabled.call( this, disabled );
11244
11245 if ( this.dropdownButton ) {
11246 this.dropdownButton.setDisabled( this.isDisabled() );
11247 }
11248 if ( this.menu ) {
11249 this.menu.setDisabled( this.isDisabled() );
11250 }
11251
11252 return this;
11253 };
11254
11255 /**
11256 * Set the options available for this input.
11257 *
11258 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
11259 * @chainable
11260 */
11261 OO.ui.ComboBoxInputWidget.prototype.setOptions = function ( options ) {
11262 this.getMenu()
11263 .clearItems()
11264 .addItems( options.map( function ( opt ) {
11265 return new OO.ui.MenuOptionWidget( {
11266 data: opt.data,
11267 label: opt.label !== undefined ? opt.label : opt.data
11268 } );
11269 } ) );
11270
11271 return this;
11272 };
11273
11274 /**
11275 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
11276 * which is a widget that is specified by reference before any optional configuration settings.
11277 *
11278 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
11279 *
11280 * - **left**: The label is placed before the field-widget and aligned with the left margin.
11281 * A left-alignment is used for forms with many fields.
11282 * - **right**: The label is placed before the field-widget and aligned to the right margin.
11283 * A right-alignment is used for long but familiar forms which users tab through,
11284 * verifying the current field with a quick glance at the label.
11285 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
11286 * that users fill out from top to bottom.
11287 * - **inline**: The label is placed after the field-widget and aligned to the left.
11288 * An inline-alignment is best used with checkboxes or radio buttons.
11289 *
11290 * Help text can either be:
11291 *
11292 * - accessed via a help icon that appears in the upper right corner of the rendered field layout, or
11293 * - shown as a subtle explanation below the label.
11294 *
11295 * If the help text is brief, or is essential to always espose it, set `helpInline` to `true`. If it
11296 * is long or not essential, leave `helpInline` to its default, `false`.
11297 *
11298 * Please see the [OOUI documentation on MediaWiki] [1] for examples and more information.
11299 *
11300 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
11301 *
11302 * @class
11303 * @extends OO.ui.Layout
11304 * @mixins OO.ui.mixin.LabelElement
11305 * @mixins OO.ui.mixin.TitledElement
11306 *
11307 * @constructor
11308 * @param {OO.ui.Widget} fieldWidget Field widget
11309 * @param {Object} [config] Configuration options
11310 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top'
11311 * or 'inline'
11312 * @cfg {Array} [errors] Error messages about the widget, which will be
11313 * displayed below the widget.
11314 * The array may contain strings or OO.ui.HtmlSnippet instances.
11315 * @cfg {Array} [notices] Notices about the widget, which will be displayed
11316 * below the widget.
11317 * The array may contain strings or OO.ui.HtmlSnippet instances.
11318 * These are more visible than `help` messages when `helpInline` is set, and so
11319 * might be good for transient messages.
11320 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified
11321 * and `helpInline` is `false`, a "help" icon will appear in the upper-right
11322 * corner of the rendered field; clicking it will display the text in a popup.
11323 * If `helpInline` is `true`, then a subtle description will be shown after the
11324 * label.
11325 * @cfg {boolean} [helpInline=false] Whether or not the help should be inline,
11326 * or shown when the "help" icon is clicked.
11327 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if
11328 * `help` is given.
11329 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11330 *
11331 * @throws {Error} An error is thrown if no widget is specified
11332 */
11333 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
11334 // Allow passing positional parameters inside the config object
11335 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
11336 config = fieldWidget;
11337 fieldWidget = config.fieldWidget;
11338 }
11339
11340 // Make sure we have required constructor arguments
11341 if ( fieldWidget === undefined ) {
11342 throw new Error( 'Widget not found' );
11343 }
11344
11345 // Configuration initialization
11346 config = $.extend( { align: 'left', helpInline: false }, config );
11347
11348 // Parent constructor
11349 OO.ui.FieldLayout.parent.call( this, config );
11350
11351 // Mixin constructors
11352 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, {
11353 $label: $( '<label>' )
11354 } ) );
11355 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
11356
11357 // Properties
11358 this.fieldWidget = fieldWidget;
11359 this.errors = [];
11360 this.notices = [];
11361 this.$field = this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
11362 this.$messages = $( '<ul>' );
11363 this.$header = $( '<span>' );
11364 this.$body = $( '<div>' );
11365 this.align = null;
11366 this.helpInline = config.helpInline;
11367
11368 if ( config.help ) {
11369 if ( this.helpInline ) {
11370 this.$help = new OO.ui.LabelWidget( {
11371 label: config.help,
11372 classes: [ 'oo-ui-inline-help' ]
11373 } ).$element;
11374 } else {
11375 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
11376 $overlay: config.$overlay,
11377 popup: {
11378 padded: true
11379 },
11380 classes: [ 'oo-ui-fieldLayout-help' ],
11381 framed: false,
11382 icon: 'info',
11383 label: OO.ui.msg( 'ooui-field-help' )
11384 } );
11385 if ( config.help instanceof OO.ui.HtmlSnippet ) {
11386 this.popupButtonWidget.getPopup().$body.html( config.help.toString() );
11387 } else {
11388 this.popupButtonWidget.getPopup().$body.text( config.help );
11389 }
11390 this.$help = this.popupButtonWidget.$element;
11391 }
11392 } else {
11393 this.$help = $( [] );
11394 }
11395
11396 // Events
11397 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
11398
11399 // Initialization
11400 if ( config.help && !config.helpInline ) {
11401 // Set the 'aria-describedby' attribute on the fieldWidget
11402 // Preference given to an input or a button
11403 (
11404 this.fieldWidget.$input ||
11405 this.fieldWidget.$button ||
11406 this.fieldWidget.$element
11407 ).attr(
11408 'aria-describedby',
11409 this.popupButtonWidget.getPopup().getBodyId()
11410 );
11411 }
11412 if ( this.fieldWidget.getInputId() ) {
11413 this.$label.attr( 'for', this.fieldWidget.getInputId() );
11414 } else {
11415 this.$label.on( 'click', function () {
11416 this.fieldWidget.simulateLabelClick();
11417 }.bind( this ) );
11418 }
11419 this.$element
11420 .addClass( 'oo-ui-fieldLayout' )
11421 .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget.isDisabled() )
11422 .append( this.$body );
11423 this.$body.addClass( 'oo-ui-fieldLayout-body' );
11424 this.$header.addClass( 'oo-ui-fieldLayout-header' );
11425 this.$messages.addClass( 'oo-ui-fieldLayout-messages' );
11426 this.$field
11427 .addClass( 'oo-ui-fieldLayout-field' )
11428 .append( this.fieldWidget.$element );
11429
11430 this.setErrors( config.errors || [] );
11431 this.setNotices( config.notices || [] );
11432 this.setAlignment( config.align );
11433 // Call this again to take into account the widget's accessKey
11434 this.updateTitle();
11435 };
11436
11437 /* Setup */
11438
11439 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
11440 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.LabelElement );
11441 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.TitledElement );
11442
11443 /* Methods */
11444
11445 /**
11446 * Handle field disable events.
11447 *
11448 * @private
11449 * @param {boolean} value Field is disabled
11450 */
11451 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
11452 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
11453 };
11454
11455 /**
11456 * Get the widget contained by the field.
11457 *
11458 * @return {OO.ui.Widget} Field widget
11459 */
11460 OO.ui.FieldLayout.prototype.getField = function () {
11461 return this.fieldWidget;
11462 };
11463
11464 /**
11465 * Return `true` if the given field widget can be used with `'inline'` alignment (see
11466 * #setAlignment). Return `false` if it can't or if this can't be determined.
11467 *
11468 * @return {boolean}
11469 */
11470 OO.ui.FieldLayout.prototype.isFieldInline = function () {
11471 // This is very simplistic, but should be good enough.
11472 return this.getField().$element.prop( 'tagName' ).toLowerCase() === 'span';
11473 };
11474
11475 /**
11476 * @protected
11477 * @param {string} kind 'error' or 'notice'
11478 * @param {string|OO.ui.HtmlSnippet} text
11479 * @return {jQuery}
11480 */
11481 OO.ui.FieldLayout.prototype.makeMessage = function ( kind, text ) {
11482 var $listItem, $icon, message;
11483 $listItem = $( '<li>' );
11484 if ( kind === 'error' ) {
11485 $icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'warning' ] } ).$element;
11486 $listItem.attr( 'role', 'alert' );
11487 } else if ( kind === 'notice' ) {
11488 $icon = new OO.ui.IconWidget( { icon: 'notice' } ).$element;
11489 } else {
11490 $icon = '';
11491 }
11492 message = new OO.ui.LabelWidget( { label: text } );
11493 $listItem
11494 .append( $icon, message.$element )
11495 .addClass( 'oo-ui-fieldLayout-messages-' + kind );
11496 return $listItem;
11497 };
11498
11499 /**
11500 * Set the field alignment mode.
11501 *
11502 * @private
11503 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
11504 * @chainable
11505 */
11506 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
11507 if ( value !== this.align ) {
11508 // Default to 'left'
11509 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
11510 value = 'left';
11511 }
11512 // Validate
11513 if ( value === 'inline' && !this.isFieldInline() ) {
11514 value = 'top';
11515 }
11516 // Reorder elements
11517
11518 if ( this.helpInline ) {
11519 if ( value === 'inline' ) {
11520 this.$header.append( this.$label, this.$help );
11521 this.$body.append( this.$field, this.$header );
11522 } else {
11523 this.$header.append( this.$label, this.$help );
11524 this.$body.append( this.$header, this.$field );
11525 }
11526 } else {
11527 if ( value === 'top' ) {
11528 this.$header.append( this.$help, this.$label );
11529 this.$body.append( this.$header, this.$field );
11530 } else if ( value === 'inline' ) {
11531 this.$header.append( this.$help, this.$label );
11532 this.$body.append( this.$field, this.$header );
11533 } else {
11534 this.$header.append( this.$label );
11535 this.$body.append( this.$header, this.$help, this.$field );
11536 }
11537 }
11538 // Set classes. The following classes can be used here:
11539 // * oo-ui-fieldLayout-align-left
11540 // * oo-ui-fieldLayout-align-right
11541 // * oo-ui-fieldLayout-align-top
11542 // * oo-ui-fieldLayout-align-inline
11543 if ( this.align ) {
11544 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
11545 }
11546 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
11547 this.align = value;
11548 }
11549
11550 return this;
11551 };
11552
11553 /**
11554 * Set the list of error messages.
11555 *
11556 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
11557 * The array may contain strings or OO.ui.HtmlSnippet instances.
11558 * @chainable
11559 */
11560 OO.ui.FieldLayout.prototype.setErrors = function ( errors ) {
11561 this.errors = errors.slice();
11562 this.updateMessages();
11563 return this;
11564 };
11565
11566 /**
11567 * Set the list of notice messages.
11568 *
11569 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
11570 * The array may contain strings or OO.ui.HtmlSnippet instances.
11571 * @chainable
11572 */
11573 OO.ui.FieldLayout.prototype.setNotices = function ( notices ) {
11574 this.notices = notices.slice();
11575 this.updateMessages();
11576 return this;
11577 };
11578
11579 /**
11580 * Update the rendering of error and notice messages.
11581 *
11582 * @private
11583 */
11584 OO.ui.FieldLayout.prototype.updateMessages = function () {
11585 var i;
11586 this.$messages.empty();
11587
11588 if ( this.errors.length || this.notices.length ) {
11589 this.$body.after( this.$messages );
11590 } else {
11591 this.$messages.remove();
11592 return;
11593 }
11594
11595 for ( i = 0; i < this.notices.length; i++ ) {
11596 this.$messages.append( this.makeMessage( 'notice', this.notices[ i ] ) );
11597 }
11598 for ( i = 0; i < this.errors.length; i++ ) {
11599 this.$messages.append( this.makeMessage( 'error', this.errors[ i ] ) );
11600 }
11601 };
11602
11603 /**
11604 * Include information about the widget's accessKey in our title. TitledElement calls this method.
11605 * (This is a bit of a hack.)
11606 *
11607 * @protected
11608 * @param {string} title Tooltip label for 'title' attribute
11609 * @return {string}
11610 */
11611 OO.ui.FieldLayout.prototype.formatTitleWithAccessKey = function ( title ) {
11612 if ( this.fieldWidget && this.fieldWidget.formatTitleWithAccessKey ) {
11613 return this.fieldWidget.formatTitleWithAccessKey( title );
11614 }
11615 return title;
11616 };
11617
11618 /**
11619 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
11620 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
11621 * is required and is specified before any optional configuration settings.
11622 *
11623 * Labels can be aligned in one of four ways:
11624 *
11625 * - **left**: The label is placed before the field-widget and aligned with the left margin.
11626 * A left-alignment is used for forms with many fields.
11627 * - **right**: The label is placed before the field-widget and aligned to the right margin.
11628 * A right-alignment is used for long but familiar forms which users tab through,
11629 * verifying the current field with a quick glance at the label.
11630 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
11631 * that users fill out from top to bottom.
11632 * - **inline**: The label is placed after the field-widget and aligned to the left.
11633 * An inline-alignment is best used with checkboxes or radio buttons.
11634 *
11635 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
11636 * text is specified.
11637 *
11638 * @example
11639 * // Example of an ActionFieldLayout
11640 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
11641 * new OO.ui.TextInputWidget( {
11642 * placeholder: 'Field widget'
11643 * } ),
11644 * new OO.ui.ButtonWidget( {
11645 * label: 'Button'
11646 * } ),
11647 * {
11648 * label: 'An ActionFieldLayout. This label is aligned top',
11649 * align: 'top',
11650 * help: 'This is help text'
11651 * }
11652 * );
11653 *
11654 * $( 'body' ).append( actionFieldLayout.$element );
11655 *
11656 * @class
11657 * @extends OO.ui.FieldLayout
11658 *
11659 * @constructor
11660 * @param {OO.ui.Widget} fieldWidget Field widget
11661 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
11662 * @param {Object} config
11663 */
11664 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
11665 // Allow passing positional parameters inside the config object
11666 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
11667 config = fieldWidget;
11668 fieldWidget = config.fieldWidget;
11669 buttonWidget = config.buttonWidget;
11670 }
11671
11672 // Parent constructor
11673 OO.ui.ActionFieldLayout.parent.call( this, fieldWidget, config );
11674
11675 // Properties
11676 this.buttonWidget = buttonWidget;
11677 this.$button = $( '<span>' );
11678 this.$input = this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
11679
11680 // Initialization
11681 this.$element
11682 .addClass( 'oo-ui-actionFieldLayout' );
11683 this.$button
11684 .addClass( 'oo-ui-actionFieldLayout-button' )
11685 .append( this.buttonWidget.$element );
11686 this.$input
11687 .addClass( 'oo-ui-actionFieldLayout-input' )
11688 .append( this.fieldWidget.$element );
11689 this.$field
11690 .append( this.$input, this.$button );
11691 };
11692
11693 /* Setup */
11694
11695 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
11696
11697 /**
11698 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
11699 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
11700 * configured with a label as well. For more information and examples,
11701 * please see the [OOUI documentation on MediaWiki][1].
11702 *
11703 * @example
11704 * // Example of a fieldset layout
11705 * var input1 = new OO.ui.TextInputWidget( {
11706 * placeholder: 'A text input field'
11707 * } );
11708 *
11709 * var input2 = new OO.ui.TextInputWidget( {
11710 * placeholder: 'A text input field'
11711 * } );
11712 *
11713 * var fieldset = new OO.ui.FieldsetLayout( {
11714 * label: 'Example of a fieldset layout'
11715 * } );
11716 *
11717 * fieldset.addItems( [
11718 * new OO.ui.FieldLayout( input1, {
11719 * label: 'Field One'
11720 * } ),
11721 * new OO.ui.FieldLayout( input2, {
11722 * label: 'Field Two'
11723 * } )
11724 * ] );
11725 * $( 'body' ).append( fieldset.$element );
11726 *
11727 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
11728 *
11729 * @class
11730 * @extends OO.ui.Layout
11731 * @mixins OO.ui.mixin.IconElement
11732 * @mixins OO.ui.mixin.LabelElement
11733 * @mixins OO.ui.mixin.GroupElement
11734 *
11735 * @constructor
11736 * @param {Object} [config] Configuration options
11737 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
11738 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
11739 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
11740 * For important messages, you are advised to use `notices`, as they are always shown.
11741 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
11742 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11743 */
11744 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
11745 // Configuration initialization
11746 config = config || {};
11747
11748 // Parent constructor
11749 OO.ui.FieldsetLayout.parent.call( this, config );
11750
11751 // Mixin constructors
11752 OO.ui.mixin.IconElement.call( this, config );
11753 OO.ui.mixin.LabelElement.call( this, config );
11754 OO.ui.mixin.GroupElement.call( this, config );
11755
11756 // Properties
11757 this.$header = $( '<legend>' );
11758 if ( config.help ) {
11759 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
11760 $overlay: config.$overlay,
11761 popup: {
11762 padded: true
11763 },
11764 classes: [ 'oo-ui-fieldsetLayout-help' ],
11765 framed: false,
11766 icon: 'info',
11767 label: OO.ui.msg( 'ooui-field-help' )
11768 } );
11769 if ( config.help instanceof OO.ui.HtmlSnippet ) {
11770 this.popupButtonWidget.getPopup().$body.html( config.help.toString() );
11771 } else {
11772 this.popupButtonWidget.getPopup().$body.text( config.help );
11773 }
11774 this.$help = this.popupButtonWidget.$element;
11775 } else {
11776 this.$help = $( [] );
11777 }
11778
11779 // Initialization
11780 this.$header
11781 .addClass( 'oo-ui-fieldsetLayout-header' )
11782 .append( this.$icon, this.$label, this.$help );
11783 this.$group.addClass( 'oo-ui-fieldsetLayout-group' );
11784 this.$element
11785 .addClass( 'oo-ui-fieldsetLayout' )
11786 .prepend( this.$header, this.$group );
11787 if ( Array.isArray( config.items ) ) {
11788 this.addItems( config.items );
11789 }
11790 };
11791
11792 /* Setup */
11793
11794 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
11795 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.IconElement );
11796 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.LabelElement );
11797 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.GroupElement );
11798
11799 /* Static Properties */
11800
11801 /**
11802 * @static
11803 * @inheritdoc
11804 */
11805 OO.ui.FieldsetLayout.static.tagName = 'fieldset';
11806
11807 /**
11808 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
11809 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
11810 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
11811 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
11812 *
11813 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
11814 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
11815 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
11816 * some fancier controls. Some controls have both regular and InputWidget variants, for example
11817 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
11818 * often have simplified APIs to match the capabilities of HTML forms.
11819 * See the [OOUI documentation on MediaWiki] [2] for more information about InputWidgets.
11820 *
11821 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Forms
11822 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
11823 *
11824 * @example
11825 * // Example of a form layout that wraps a fieldset layout
11826 * var input1 = new OO.ui.TextInputWidget( {
11827 * placeholder: 'Username'
11828 * } );
11829 * var input2 = new OO.ui.TextInputWidget( {
11830 * placeholder: 'Password',
11831 * type: 'password'
11832 * } );
11833 * var submit = new OO.ui.ButtonInputWidget( {
11834 * label: 'Submit'
11835 * } );
11836 *
11837 * var fieldset = new OO.ui.FieldsetLayout( {
11838 * label: 'A form layout'
11839 * } );
11840 * fieldset.addItems( [
11841 * new OO.ui.FieldLayout( input1, {
11842 * label: 'Username',
11843 * align: 'top'
11844 * } ),
11845 * new OO.ui.FieldLayout( input2, {
11846 * label: 'Password',
11847 * align: 'top'
11848 * } ),
11849 * new OO.ui.FieldLayout( submit )
11850 * ] );
11851 * var form = new OO.ui.FormLayout( {
11852 * items: [ fieldset ],
11853 * action: '/api/formhandler',
11854 * method: 'get'
11855 * } )
11856 * $( 'body' ).append( form.$element );
11857 *
11858 * @class
11859 * @extends OO.ui.Layout
11860 * @mixins OO.ui.mixin.GroupElement
11861 *
11862 * @constructor
11863 * @param {Object} [config] Configuration options
11864 * @cfg {string} [method] HTML form `method` attribute
11865 * @cfg {string} [action] HTML form `action` attribute
11866 * @cfg {string} [enctype] HTML form `enctype` attribute
11867 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
11868 */
11869 OO.ui.FormLayout = function OoUiFormLayout( config ) {
11870 var action;
11871
11872 // Configuration initialization
11873 config = config || {};
11874
11875 // Parent constructor
11876 OO.ui.FormLayout.parent.call( this, config );
11877
11878 // Mixin constructors
11879 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
11880
11881 // Events
11882 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
11883
11884 // Make sure the action is safe
11885 action = config.action;
11886 if ( action !== undefined && !OO.ui.isSafeUrl( action ) ) {
11887 action = './' + action;
11888 }
11889
11890 // Initialization
11891 this.$element
11892 .addClass( 'oo-ui-formLayout' )
11893 .attr( {
11894 method: config.method,
11895 action: action,
11896 enctype: config.enctype
11897 } );
11898 if ( Array.isArray( config.items ) ) {
11899 this.addItems( config.items );
11900 }
11901 };
11902
11903 /* Setup */
11904
11905 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
11906 OO.mixinClass( OO.ui.FormLayout, OO.ui.mixin.GroupElement );
11907
11908 /* Events */
11909
11910 /**
11911 * A 'submit' event is emitted when the form is submitted.
11912 *
11913 * @event submit
11914 */
11915
11916 /* Static Properties */
11917
11918 /**
11919 * @static
11920 * @inheritdoc
11921 */
11922 OO.ui.FormLayout.static.tagName = 'form';
11923
11924 /* Methods */
11925
11926 /**
11927 * Handle form submit events.
11928 *
11929 * @private
11930 * @param {jQuery.Event} e Submit event
11931 * @fires submit
11932 */
11933 OO.ui.FormLayout.prototype.onFormSubmit = function () {
11934 if ( this.emit( 'submit' ) ) {
11935 return false;
11936 }
11937 };
11938
11939 /**
11940 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
11941 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
11942 *
11943 * @example
11944 * // Example of a panel layout
11945 * var panel = new OO.ui.PanelLayout( {
11946 * expanded: false,
11947 * framed: true,
11948 * padded: true,
11949 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
11950 * } );
11951 * $( 'body' ).append( panel.$element );
11952 *
11953 * @class
11954 * @extends OO.ui.Layout
11955 *
11956 * @constructor
11957 * @param {Object} [config] Configuration options
11958 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
11959 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
11960 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
11961 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
11962 */
11963 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
11964 // Configuration initialization
11965 config = $.extend( {
11966 scrollable: false,
11967 padded: false,
11968 expanded: true,
11969 framed: false
11970 }, config );
11971
11972 // Parent constructor
11973 OO.ui.PanelLayout.parent.call( this, config );
11974
11975 // Initialization
11976 this.$element.addClass( 'oo-ui-panelLayout' );
11977 if ( config.scrollable ) {
11978 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
11979 }
11980 if ( config.padded ) {
11981 this.$element.addClass( 'oo-ui-panelLayout-padded' );
11982 }
11983 if ( config.expanded ) {
11984 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
11985 }
11986 if ( config.framed ) {
11987 this.$element.addClass( 'oo-ui-panelLayout-framed' );
11988 }
11989 };
11990
11991 /* Setup */
11992
11993 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
11994
11995 /* Methods */
11996
11997 /**
11998 * Focus the panel layout
11999 *
12000 * The default implementation just focuses the first focusable element in the panel
12001 */
12002 OO.ui.PanelLayout.prototype.focus = function () {
12003 OO.ui.findFocusable( this.$element ).focus();
12004 };
12005
12006 /**
12007 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
12008 * items), with small margins between them. Convenient when you need to put a number of block-level
12009 * widgets on a single line next to each other.
12010 *
12011 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
12012 *
12013 * @example
12014 * // HorizontalLayout with a text input and a label
12015 * var layout = new OO.ui.HorizontalLayout( {
12016 * items: [
12017 * new OO.ui.LabelWidget( { label: 'Label' } ),
12018 * new OO.ui.TextInputWidget( { value: 'Text' } )
12019 * ]
12020 * } );
12021 * $( 'body' ).append( layout.$element );
12022 *
12023 * @class
12024 * @extends OO.ui.Layout
12025 * @mixins OO.ui.mixin.GroupElement
12026 *
12027 * @constructor
12028 * @param {Object} [config] Configuration options
12029 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
12030 */
12031 OO.ui.HorizontalLayout = function OoUiHorizontalLayout( config ) {
12032 // Configuration initialization
12033 config = config || {};
12034
12035 // Parent constructor
12036 OO.ui.HorizontalLayout.parent.call( this, config );
12037
12038 // Mixin constructors
12039 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
12040
12041 // Initialization
12042 this.$element.addClass( 'oo-ui-horizontalLayout' );
12043 if ( Array.isArray( config.items ) ) {
12044 this.addItems( config.items );
12045 }
12046 };
12047
12048 /* Setup */
12049
12050 OO.inheritClass( OO.ui.HorizontalLayout, OO.ui.Layout );
12051 OO.mixinClass( OO.ui.HorizontalLayout, OO.ui.mixin.GroupElement );
12052
12053 /**
12054 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
12055 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
12056 * (to adjust the value in increments) to allow the user to enter a number.
12057 *
12058 * @example
12059 * // Example: A NumberInputWidget.
12060 * var numberInput = new OO.ui.NumberInputWidget( {
12061 * label: 'NumberInputWidget',
12062 * input: { value: 5 },
12063 * min: 1,
12064 * max: 10
12065 * } );
12066 * $( 'body' ).append( numberInput.$element );
12067 *
12068 * @class
12069 * @extends OO.ui.TextInputWidget
12070 *
12071 * @constructor
12072 * @param {Object} [config] Configuration options
12073 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
12074 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
12075 * @cfg {boolean} [allowInteger=false] Whether the field accepts only integer values.
12076 * @cfg {number} [min=-Infinity] Minimum allowed value
12077 * @cfg {number} [max=Infinity] Maximum allowed value
12078 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
12079 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
12080 * @cfg {boolean} [showButtons=true] Whether to show the plus and minus buttons.
12081 */
12082 OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
12083 var $field = $( '<div>' )
12084 .addClass( 'oo-ui-numberInputWidget-field' );
12085
12086 // Configuration initialization
12087 config = $.extend( {
12088 allowInteger: false,
12089 min: -Infinity,
12090 max: Infinity,
12091 step: 1,
12092 pageStep: null,
12093 showButtons: true
12094 }, config );
12095
12096 // For backward compatibility
12097 $.extend( config, config.input );
12098 this.input = this;
12099
12100 // Parent constructor
12101 OO.ui.NumberInputWidget.parent.call( this, $.extend( config, {
12102 type: 'number'
12103 } ) );
12104
12105 if ( config.showButtons ) {
12106 this.minusButton = new OO.ui.ButtonWidget( $.extend(
12107 {
12108 disabled: this.isDisabled(),
12109 tabIndex: -1,
12110 classes: [ 'oo-ui-numberInputWidget-minusButton' ],
12111 icon: 'subtract'
12112 },
12113 config.minusButton
12114 ) );
12115 this.minusButton.$element.attr( 'aria-hidden', 'true' );
12116 this.plusButton = new OO.ui.ButtonWidget( $.extend(
12117 {
12118 disabled: this.isDisabled(),
12119 tabIndex: -1,
12120 classes: [ 'oo-ui-numberInputWidget-plusButton' ],
12121 icon: 'add'
12122 },
12123 config.plusButton
12124 ) );
12125 this.plusButton.$element.attr( 'aria-hidden', 'true' );
12126 }
12127
12128 // Events
12129 this.$input.on( {
12130 keydown: this.onKeyDown.bind( this ),
12131 'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
12132 } );
12133 if ( config.showButtons ) {
12134 this.plusButton.connect( this, {
12135 click: [ 'onButtonClick', +1 ]
12136 } );
12137 this.minusButton.connect( this, {
12138 click: [ 'onButtonClick', -1 ]
12139 } );
12140 }
12141
12142 // Build the field
12143 $field.append( this.$input );
12144 if ( config.showButtons ) {
12145 $field
12146 .prepend( this.minusButton.$element )
12147 .append( this.plusButton.$element );
12148 }
12149
12150 // Initialization
12151 this.setAllowInteger( config.allowInteger || config.isInteger );
12152 this.setRange( config.min, config.max );
12153 this.setStep( config.step, config.pageStep );
12154 // Set the validation method after we set allowInteger and range
12155 // so that it doesn't immediately call setValidityFlag
12156 this.setValidation( this.validateNumber.bind( this ) );
12157
12158 this.$element
12159 .addClass( 'oo-ui-numberInputWidget' )
12160 .toggleClass( 'oo-ui-numberInputWidget-buttoned', config.showButtons )
12161 .append( $field );
12162 };
12163
12164 /* Setup */
12165
12166 OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.TextInputWidget );
12167
12168 /* Methods */
12169
12170 /**
12171 * Set whether only integers are allowed
12172 *
12173 * @param {boolean} flag
12174 */
12175 OO.ui.NumberInputWidget.prototype.setAllowInteger = function ( flag ) {
12176 this.allowInteger = !!flag;
12177 this.setValidityFlag();
12178 };
12179 // Backward compatibility
12180 OO.ui.NumberInputWidget.prototype.setIsInteger = OO.ui.NumberInputWidget.prototype.setAllowInteger;
12181
12182 /**
12183 * Get whether only integers are allowed
12184 *
12185 * @return {boolean} Flag value
12186 */
12187 OO.ui.NumberInputWidget.prototype.getAllowInteger = function () {
12188 return this.allowInteger;
12189 };
12190 // Backward compatibility
12191 OO.ui.NumberInputWidget.prototype.getIsInteger = OO.ui.NumberInputWidget.prototype.getAllowInteger;
12192
12193 /**
12194 * Set the range of allowed values
12195 *
12196 * @param {number} min Minimum allowed value
12197 * @param {number} max Maximum allowed value
12198 */
12199 OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
12200 if ( min > max ) {
12201 throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
12202 }
12203 this.min = min;
12204 this.max = max;
12205 this.$input.attr( 'min', this.min );
12206 this.$input.attr( 'max', this.max );
12207 this.setValidityFlag();
12208 };
12209
12210 /**
12211 * Get the current range
12212 *
12213 * @return {number[]} Minimum and maximum values
12214 */
12215 OO.ui.NumberInputWidget.prototype.getRange = function () {
12216 return [ this.min, this.max ];
12217 };
12218
12219 /**
12220 * Set the stepping deltas
12221 *
12222 * @param {number} step Normal step
12223 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
12224 */
12225 OO.ui.NumberInputWidget.prototype.setStep = function ( step, pageStep ) {
12226 if ( step <= 0 ) {
12227 throw new Error( 'Step value must be positive' );
12228 }
12229 if ( pageStep === null ) {
12230 pageStep = step * 10;
12231 } else if ( pageStep <= 0 ) {
12232 throw new Error( 'Page step value must be positive' );
12233 }
12234 this.step = step;
12235 this.pageStep = pageStep;
12236 this.$input.attr( 'step', this.step );
12237 };
12238
12239 /**
12240 * @inheritdoc
12241 */
12242 OO.ui.NumberInputWidget.prototype.setValue = function ( value ) {
12243 if ( value === '' ) {
12244 // Some browsers allow a value in the input even if there isn't one reported by $input.val()
12245 // so here we make sure an 'empty' value is actually displayed as such.
12246 this.$input.val( '' );
12247 }
12248 return OO.ui.NumberInputWidget.parent.prototype.setValue.call( this, value );
12249 };
12250
12251 /**
12252 * Get the current stepping values
12253 *
12254 * @return {number[]} Step and page step
12255 */
12256 OO.ui.NumberInputWidget.prototype.getStep = function () {
12257 return [ this.step, this.pageStep ];
12258 };
12259
12260 /**
12261 * Get the current value of the widget as a number
12262 *
12263 * @return {number} May be NaN, or an invalid number
12264 */
12265 OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
12266 return +this.getValue();
12267 };
12268
12269 /**
12270 * Adjust the value of the widget
12271 *
12272 * @param {number} delta Adjustment amount
12273 */
12274 OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
12275 var n, v = this.getNumericValue();
12276
12277 delta = +delta;
12278 if ( isNaN( delta ) || !isFinite( delta ) ) {
12279 throw new Error( 'Delta must be a finite number' );
12280 }
12281
12282 if ( isNaN( v ) ) {
12283 n = 0;
12284 } else {
12285 n = v + delta;
12286 n = Math.max( Math.min( n, this.max ), this.min );
12287 if ( this.allowInteger ) {
12288 n = Math.round( n );
12289 }
12290 }
12291
12292 if ( n !== v ) {
12293 this.setValue( n );
12294 }
12295 };
12296 /**
12297 * Validate input
12298 *
12299 * @private
12300 * @param {string} value Field value
12301 * @return {boolean}
12302 */
12303 OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
12304 var n = +value;
12305 if ( value === '' ) {
12306 return !this.isRequired();
12307 }
12308
12309 if ( isNaN( n ) || !isFinite( n ) ) {
12310 return false;
12311 }
12312
12313 if ( this.allowInteger && Math.floor( n ) !== n ) {
12314 return false;
12315 }
12316
12317 if ( n < this.min || n > this.max ) {
12318 return false;
12319 }
12320
12321 return true;
12322 };
12323
12324 /**
12325 * Handle mouse click events.
12326 *
12327 * @private
12328 * @param {number} dir +1 or -1
12329 */
12330 OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
12331 this.adjustValue( dir * this.step );
12332 };
12333
12334 /**
12335 * Handle mouse wheel events.
12336 *
12337 * @private
12338 * @param {jQuery.Event} event
12339 */
12340 OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
12341 var delta = 0;
12342
12343 if ( !this.isDisabled() && this.$input.is( ':focus' ) ) {
12344 // Standard 'wheel' event
12345 if ( event.originalEvent.deltaMode !== undefined ) {
12346 this.sawWheelEvent = true;
12347 }
12348 if ( event.originalEvent.deltaY ) {
12349 delta = -event.originalEvent.deltaY;
12350 } else if ( event.originalEvent.deltaX ) {
12351 delta = event.originalEvent.deltaX;
12352 }
12353
12354 // Non-standard events
12355 if ( !this.sawWheelEvent ) {
12356 if ( event.originalEvent.wheelDeltaX ) {
12357 delta = -event.originalEvent.wheelDeltaX;
12358 } else if ( event.originalEvent.wheelDeltaY ) {
12359 delta = event.originalEvent.wheelDeltaY;
12360 } else if ( event.originalEvent.wheelDelta ) {
12361 delta = event.originalEvent.wheelDelta;
12362 } else if ( event.originalEvent.detail ) {
12363 delta = -event.originalEvent.detail;
12364 }
12365 }
12366
12367 if ( delta ) {
12368 delta = delta < 0 ? -1 : 1;
12369 this.adjustValue( delta * this.step );
12370 }
12371
12372 return false;
12373 }
12374 };
12375
12376 /**
12377 * Handle key down events.
12378 *
12379 * @private
12380 * @param {jQuery.Event} e Key down event
12381 */
12382 OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
12383 if ( !this.isDisabled() ) {
12384 switch ( e.which ) {
12385 case OO.ui.Keys.UP:
12386 this.adjustValue( this.step );
12387 return false;
12388 case OO.ui.Keys.DOWN:
12389 this.adjustValue( -this.step );
12390 return false;
12391 case OO.ui.Keys.PAGEUP:
12392 this.adjustValue( this.pageStep );
12393 return false;
12394 case OO.ui.Keys.PAGEDOWN:
12395 this.adjustValue( -this.pageStep );
12396 return false;
12397 }
12398 }
12399 };
12400
12401 /**
12402 * @inheritdoc
12403 */
12404 OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
12405 // Parent method
12406 OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
12407
12408 if ( this.minusButton ) {
12409 this.minusButton.setDisabled( this.isDisabled() );
12410 }
12411 if ( this.plusButton ) {
12412 this.plusButton.setDisabled( this.isDisabled() );
12413 }
12414
12415 return this;
12416 };
12417
12418 }( OO ) );
12419
12420 //# sourceMappingURL=oojs-ui-core.js.map.json