Merge "Update OOUI to v0.29.3"
[lhc/web/wiklou.git] / resources / lib / ooui / oojs-ui-core.js
1 /*!
2 * OOUI v0.29.3
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-11-01T02:03:33Z
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 // Label for the help icon attached to a form field
389 'ooui-field-help': 'Help'
390 };
391
392 /**
393 * Get a localized message.
394 *
395 * After the message key, message parameters may optionally be passed. In the default implementation,
396 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
397 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
398 * they support unnamed, ordered message parameters.
399 *
400 * In environments that provide a localization system, this function should be overridden to
401 * return the message translated in the user's language. The default implementation always returns
402 * English messages. An example of doing this with [jQuery.i18n](https://github.com/wikimedia/jquery.i18n)
403 * follows.
404 *
405 * @example
406 * var i, iLen, button,
407 * messagePath = 'oojs-ui/dist/i18n/',
408 * languages = [ $.i18n().locale, 'ur', 'en' ],
409 * languageMap = {};
410 *
411 * for ( i = 0, iLen = languages.length; i < iLen; i++ ) {
412 * languageMap[ languages[ i ] ] = messagePath + languages[ i ].toLowerCase() + '.json';
413 * }
414 *
415 * $.i18n().load( languageMap ).done( function() {
416 * // Replace the built-in `msg` only once we've loaded the internationalization.
417 * // OOUI uses `OO.ui.deferMsg` for all initially-loaded messages. So long as
418 * // you put off creating any widgets until this promise is complete, no English
419 * // will be displayed.
420 * OO.ui.msg = $.i18n;
421 *
422 * // A button displaying "OK" in the default locale
423 * button = new OO.ui.ButtonWidget( {
424 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
425 * icon: 'check'
426 * } );
427 * $( 'body' ).append( button.$element );
428 *
429 * // A button displaying "OK" in Urdu
430 * $.i18n().locale = 'ur';
431 * button = new OO.ui.ButtonWidget( {
432 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
433 * icon: 'check'
434 * } );
435 * $( 'body' ).append( button.$element );
436 * } );
437 *
438 * @param {string} key Message key
439 * @param {...Mixed} [params] Message parameters
440 * @return {string} Translated message with parameters substituted
441 */
442 OO.ui.msg = function ( key ) {
443 var message = messages[ key ],
444 params = Array.prototype.slice.call( arguments, 1 );
445 if ( typeof message === 'string' ) {
446 // Perform $1 substitution
447 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
448 var i = parseInt( n, 10 );
449 return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n;
450 } );
451 } else {
452 // Return placeholder if message not found
453 message = '[' + key + ']';
454 }
455 return message;
456 };
457 }() );
458
459 /**
460 * Package a message and arguments for deferred resolution.
461 *
462 * Use this when you are statically specifying a message and the message may not yet be present.
463 *
464 * @param {string} key Message key
465 * @param {...Mixed} [params] Message parameters
466 * @return {Function} Function that returns the resolved message when executed
467 */
468 OO.ui.deferMsg = function () {
469 var args = arguments;
470 return function () {
471 return OO.ui.msg.apply( OO.ui, args );
472 };
473 };
474
475 /**
476 * Resolve a message.
477 *
478 * If the message is a function it will be executed, otherwise it will pass through directly.
479 *
480 * @param {Function|string} msg Deferred message, or message text
481 * @return {string} Resolved message
482 */
483 OO.ui.resolveMsg = function ( msg ) {
484 if ( $.isFunction( msg ) ) {
485 return msg();
486 }
487 return msg;
488 };
489
490 /**
491 * @param {string} url
492 * @return {boolean}
493 */
494 OO.ui.isSafeUrl = function ( url ) {
495 // Keep this function in sync with php/Tag.php
496 var i, protocolWhitelist;
497
498 function stringStartsWith( haystack, needle ) {
499 return haystack.substr( 0, needle.length ) === needle;
500 }
501
502 protocolWhitelist = [
503 'bitcoin', 'ftp', 'ftps', 'geo', 'git', 'gopher', 'http', 'https', 'irc', 'ircs',
504 'magnet', 'mailto', 'mms', 'news', 'nntp', 'redis', 'sftp', 'sip', 'sips', 'sms', 'ssh',
505 'svn', 'tel', 'telnet', 'urn', 'worldwind', 'xmpp'
506 ];
507
508 if ( url === '' ) {
509 return true;
510 }
511
512 for ( i = 0; i < protocolWhitelist.length; i++ ) {
513 if ( stringStartsWith( url, protocolWhitelist[ i ] + ':' ) ) {
514 return true;
515 }
516 }
517
518 // This matches '//' too
519 if ( stringStartsWith( url, '/' ) || stringStartsWith( url, './' ) ) {
520 return true;
521 }
522 if ( stringStartsWith( url, '?' ) || stringStartsWith( url, '#' ) ) {
523 return true;
524 }
525
526 return false;
527 };
528
529 /**
530 * Check if the user has a 'mobile' device.
531 *
532 * For our purposes this means the user is primarily using an
533 * on-screen keyboard, touch input instead of a mouse and may
534 * have a physically small display.
535 *
536 * It is left up to implementors to decide how to compute this
537 * so the default implementation always returns false.
538 *
539 * @return {boolean} User is on a mobile device
540 */
541 OO.ui.isMobile = function () {
542 return false;
543 };
544
545 /**
546 * Get the additional spacing that should be taken into account when displaying elements that are
547 * clipped to the viewport, e.g. dropdown menus and popups. This is meant to be overridden to avoid
548 * such menus overlapping any fixed headers/toolbars/navigation used by the site.
549 *
550 * @return {Object} Object with the properties 'top', 'right', 'bottom', 'left', each representing
551 * the extra spacing from that edge of viewport (in pixels)
552 */
553 OO.ui.getViewportSpacing = function () {
554 return {
555 top: 0,
556 right: 0,
557 bottom: 0,
558 left: 0
559 };
560 };
561
562 /**
563 * Get the default overlay, which is used by various widgets when they are passed `$overlay: true`.
564 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
565 *
566 * @return {jQuery} Default overlay node
567 */
568 OO.ui.getDefaultOverlay = function () {
569 if ( !OO.ui.$defaultOverlay ) {
570 OO.ui.$defaultOverlay = $( '<div>' ).addClass( 'oo-ui-defaultOverlay' );
571 $( 'body' ).append( OO.ui.$defaultOverlay );
572 }
573 return OO.ui.$defaultOverlay;
574 };
575
576 /*!
577 * Mixin namespace.
578 */
579
580 /**
581 * Namespace for OOUI mixins.
582 *
583 * Mixins are named according to the type of object they are intended to
584 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
585 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
586 * is intended to be mixed in to an instance of OO.ui.Widget.
587 *
588 * @class
589 * @singleton
590 */
591 OO.ui.mixin = {};
592
593 /**
594 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
595 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
596 * connected to them and can't be interacted with.
597 *
598 * @abstract
599 * @class
600 *
601 * @constructor
602 * @param {Object} [config] Configuration options
603 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
604 * to the top level (e.g., the outermost div) of the element. See the [OOUI documentation on MediaWiki][2]
605 * for an example.
606 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches#cssExample
607 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
608 * @cfg {string} [text] Text to insert
609 * @cfg {Array} [content] An array of content elements to append (after #text).
610 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
611 * Instances of OO.ui.Element will have their $element appended.
612 * @cfg {jQuery} [$content] Content elements to append (after #text).
613 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
614 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
615 * Data can also be specified with the #setData method.
616 */
617 OO.ui.Element = function OoUiElement( config ) {
618 if ( OO.ui.isDemo ) {
619 this.initialConfig = config;
620 }
621 // Configuration initialization
622 config = config || {};
623
624 // Properties
625 this.$ = $;
626 this.elementId = null;
627 this.visible = true;
628 this.data = config.data;
629 this.$element = config.$element ||
630 $( document.createElement( this.getTagName() ) );
631 this.elementGroup = null;
632
633 // Initialization
634 if ( Array.isArray( config.classes ) ) {
635 this.$element.addClass( config.classes );
636 }
637 if ( config.id ) {
638 this.setElementId( config.id );
639 }
640 if ( config.text ) {
641 this.$element.text( config.text );
642 }
643 if ( config.content ) {
644 // The `content` property treats plain strings as text; use an
645 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
646 // appropriate $element appended.
647 this.$element.append( config.content.map( function ( v ) {
648 if ( typeof v === 'string' ) {
649 // Escape string so it is properly represented in HTML.
650 return document.createTextNode( v );
651 } else if ( v instanceof OO.ui.HtmlSnippet ) {
652 // Bypass escaping.
653 return v.toString();
654 } else if ( v instanceof OO.ui.Element ) {
655 return v.$element;
656 }
657 return v;
658 } ) );
659 }
660 if ( config.$content ) {
661 // The `$content` property treats plain strings as HTML.
662 this.$element.append( config.$content );
663 }
664 };
665
666 /* Setup */
667
668 OO.initClass( OO.ui.Element );
669
670 /* Static Properties */
671
672 /**
673 * The name of the HTML tag used by the element.
674 *
675 * The static value may be ignored if the #getTagName method is overridden.
676 *
677 * @static
678 * @inheritable
679 * @property {string}
680 */
681 OO.ui.Element.static.tagName = 'div';
682
683 /* Static Methods */
684
685 /**
686 * Reconstitute a JavaScript object corresponding to a widget created
687 * by the PHP implementation.
688 *
689 * @param {string|HTMLElement|jQuery} idOrNode
690 * A DOM id (if a string) or node for the widget to infuse.
691 * @param {Object} [config] Configuration options
692 * @return {OO.ui.Element}
693 * The `OO.ui.Element` corresponding to this (infusable) document node.
694 * For `Tag` objects emitted on the HTML side (used occasionally for content)
695 * the value returned is a newly-created Element wrapping around the existing
696 * DOM node.
697 */
698 OO.ui.Element.static.infuse = function ( idOrNode, config ) {
699 var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, config, false );
700 // Verify that the type matches up.
701 // FIXME: uncomment after T89721 is fixed, see T90929.
702 /*
703 if ( !( obj instanceof this['class'] ) ) {
704 throw new Error( 'Infusion type mismatch!' );
705 }
706 */
707 return obj;
708 };
709
710 /**
711 * Implementation helper for `infuse`; skips the type check and has an
712 * extra property so that only the top-level invocation touches the DOM.
713 *
714 * @private
715 * @param {string|HTMLElement|jQuery} idOrNode
716 * @param {Object} [config] Configuration options
717 * @param {jQuery.Promise} [domPromise] A promise that will be resolved
718 * when the top-level widget of this infusion is inserted into DOM,
719 * replacing the original node; only used internally.
720 * @return {OO.ui.Element}
721 */
722 OO.ui.Element.static.unsafeInfuse = function ( idOrNode, config, domPromise ) {
723 // look for a cached result of a previous infusion.
724 var id, $elem, error, data, cls, parts, parent, obj, top, state, infusedChildren;
725 if ( typeof idOrNode === 'string' ) {
726 id = idOrNode;
727 $elem = $( document.getElementById( id ) );
728 } else {
729 $elem = $( idOrNode );
730 id = $elem.attr( 'id' );
731 }
732 if ( !$elem.length ) {
733 if ( typeof idOrNode === 'string' ) {
734 error = 'Widget not found: ' + idOrNode;
735 } else if ( idOrNode && idOrNode.selector ) {
736 error = 'Widget not found: ' + idOrNode.selector;
737 } else {
738 error = 'Widget not found';
739 }
740 throw new Error( error );
741 }
742 if ( $elem[ 0 ].oouiInfused ) {
743 $elem = $elem[ 0 ].oouiInfused;
744 }
745 data = $elem.data( 'ooui-infused' );
746 if ( data ) {
747 // cached!
748 if ( data === true ) {
749 throw new Error( 'Circular dependency! ' + id );
750 }
751 if ( domPromise ) {
752 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
753 state = data.constructor.static.gatherPreInfuseState( $elem, data );
754 // restore dynamic state after the new element is re-inserted into DOM under infused parent
755 domPromise.done( data.restorePreInfuseState.bind( data, state ) );
756 infusedChildren = $elem.data( 'ooui-infused-children' );
757 if ( infusedChildren && infusedChildren.length ) {
758 infusedChildren.forEach( function ( data ) {
759 var state = data.constructor.static.gatherPreInfuseState( $elem, data );
760 domPromise.done( data.restorePreInfuseState.bind( data, state ) );
761 } );
762 }
763 }
764 return data;
765 }
766 data = $elem.attr( 'data-ooui' );
767 if ( !data ) {
768 throw new Error( 'No infusion data found: ' + id );
769 }
770 try {
771 data = JSON.parse( data );
772 } catch ( _ ) {
773 data = null;
774 }
775 if ( !( data && data._ ) ) {
776 throw new Error( 'No valid infusion data found: ' + id );
777 }
778 if ( data._ === 'Tag' ) {
779 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
780 return new OO.ui.Element( $.extend( {}, config, { $element: $elem } ) );
781 }
782 parts = data._.split( '.' );
783 cls = OO.getProp.apply( OO, [ window ].concat( parts ) );
784 if ( cls === undefined ) {
785 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
786 }
787
788 // Verify that we're creating an OO.ui.Element instance
789 parent = cls.parent;
790
791 while ( parent !== undefined ) {
792 if ( parent === OO.ui.Element ) {
793 // Safe
794 break;
795 }
796
797 parent = parent.parent;
798 }
799
800 if ( parent !== OO.ui.Element ) {
801 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
802 }
803
804 if ( !domPromise ) {
805 top = $.Deferred();
806 domPromise = top.promise();
807 }
808 $elem.data( 'ooui-infused', true ); // prevent loops
809 data.id = id; // implicit
810 infusedChildren = [];
811 data = OO.copy( data, null, function deserialize( value ) {
812 var infused;
813 if ( OO.isPlainObject( value ) ) {
814 if ( value.tag ) {
815 infused = OO.ui.Element.static.unsafeInfuse( value.tag, config, domPromise );
816 infusedChildren.push( infused );
817 // Flatten the structure
818 infusedChildren.push.apply( infusedChildren, infused.$element.data( 'ooui-infused-children' ) || [] );
819 infused.$element.removeData( 'ooui-infused-children' );
820 return infused;
821 }
822 if ( value.html !== undefined ) {
823 return new OO.ui.HtmlSnippet( value.html );
824 }
825 }
826 } );
827 // allow widgets to reuse parts of the DOM
828 data = cls.static.reusePreInfuseDOM( $elem[ 0 ], data );
829 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
830 state = cls.static.gatherPreInfuseState( $elem[ 0 ], data );
831 // rebuild widget
832 // eslint-disable-next-line new-cap
833 obj = new cls( $.extend( {}, config, data ) );
834 // If anyone is holding a reference to the old DOM element,
835 // let's allow them to OO.ui.infuse() it and do what they expect, see T105828.
836 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
837 $elem[ 0 ].oouiInfused = obj.$element;
838 // now replace old DOM with this new DOM.
839 if ( top ) {
840 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
841 // so only mutate the DOM if we need to.
842 if ( $elem[ 0 ] !== obj.$element[ 0 ] ) {
843 $elem.replaceWith( obj.$element );
844 }
845 top.resolve();
846 }
847 obj.$element.data( 'ooui-infused', obj );
848 obj.$element.data( 'ooui-infused-children', infusedChildren );
849 // set the 'data-ooui' attribute so we can identify infused widgets
850 obj.$element.attr( 'data-ooui', '' );
851 // restore dynamic state after the new element is inserted into DOM
852 domPromise.done( obj.restorePreInfuseState.bind( obj, state ) );
853 return obj;
854 };
855
856 /**
857 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
858 *
859 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
860 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
861 * constructor, which will be given the enhanced config.
862 *
863 * @protected
864 * @param {HTMLElement} node
865 * @param {Object} config
866 * @return {Object}
867 */
868 OO.ui.Element.static.reusePreInfuseDOM = function ( node, config ) {
869 return config;
870 };
871
872 /**
873 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of an HTML DOM node
874 * (and its children) that represent an Element of the same class and the given configuration,
875 * generated by the PHP implementation.
876 *
877 * This method is called just before `node` is detached from the DOM. The return value of this
878 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
879 * is inserted into DOM to replace `node`.
880 *
881 * @protected
882 * @param {HTMLElement} node
883 * @param {Object} config
884 * @return {Object}
885 */
886 OO.ui.Element.static.gatherPreInfuseState = function () {
887 return {};
888 };
889
890 /**
891 * Get a jQuery function within a specific document.
892 *
893 * @static
894 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
895 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
896 * not in an iframe
897 * @return {Function} Bound jQuery function
898 */
899 OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
900 function wrapper( selector ) {
901 return $( selector, wrapper.context );
902 }
903
904 wrapper.context = this.getDocument( context );
905
906 if ( $iframe ) {
907 wrapper.$iframe = $iframe;
908 }
909
910 return wrapper;
911 };
912
913 /**
914 * Get the document of an element.
915 *
916 * @static
917 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
918 * @return {HTMLDocument|null} Document object
919 */
920 OO.ui.Element.static.getDocument = function ( obj ) {
921 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
922 return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
923 // Empty jQuery selections might have a context
924 obj.context ||
925 // HTMLElement
926 obj.ownerDocument ||
927 // Window
928 obj.document ||
929 // HTMLDocument
930 ( obj.nodeType === Node.DOCUMENT_NODE && obj ) ||
931 null;
932 };
933
934 /**
935 * Get the window of an element or document.
936 *
937 * @static
938 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
939 * @return {Window} Window object
940 */
941 OO.ui.Element.static.getWindow = function ( obj ) {
942 var doc = this.getDocument( obj );
943 return doc.defaultView;
944 };
945
946 /**
947 * Get the direction of an element or document.
948 *
949 * @static
950 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
951 * @return {string} Text direction, either 'ltr' or 'rtl'
952 */
953 OO.ui.Element.static.getDir = function ( obj ) {
954 var isDoc, isWin;
955
956 if ( obj instanceof jQuery ) {
957 obj = obj[ 0 ];
958 }
959 isDoc = obj.nodeType === Node.DOCUMENT_NODE;
960 isWin = obj.document !== undefined;
961 if ( isDoc || isWin ) {
962 if ( isWin ) {
963 obj = obj.document;
964 }
965 obj = obj.body;
966 }
967 return $( obj ).css( 'direction' );
968 };
969
970 /**
971 * Get the offset between two frames.
972 *
973 * TODO: Make this function not use recursion.
974 *
975 * @static
976 * @param {Window} from Window of the child frame
977 * @param {Window} [to=window] Window of the parent frame
978 * @param {Object} [offset] Offset to start with, used internally
979 * @return {Object} Offset object, containing left and top properties
980 */
981 OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
982 var i, len, frames, frame, rect;
983
984 if ( !to ) {
985 to = window;
986 }
987 if ( !offset ) {
988 offset = { top: 0, left: 0 };
989 }
990 if ( from.parent === from ) {
991 return offset;
992 }
993
994 // Get iframe element
995 frames = from.parent.document.getElementsByTagName( 'iframe' );
996 for ( i = 0, len = frames.length; i < len; i++ ) {
997 if ( frames[ i ].contentWindow === from ) {
998 frame = frames[ i ];
999 break;
1000 }
1001 }
1002
1003 // Recursively accumulate offset values
1004 if ( frame ) {
1005 rect = frame.getBoundingClientRect();
1006 offset.left += rect.left;
1007 offset.top += rect.top;
1008 if ( from !== to ) {
1009 this.getFrameOffset( from.parent, offset );
1010 }
1011 }
1012 return offset;
1013 };
1014
1015 /**
1016 * Get the offset between two elements.
1017 *
1018 * The two elements may be in a different frame, but in that case the frame $element is in must
1019 * be contained in the frame $anchor is in.
1020 *
1021 * @static
1022 * @param {jQuery} $element Element whose position to get
1023 * @param {jQuery} $anchor Element to get $element's position relative to
1024 * @return {Object} Translated position coordinates, containing top and left properties
1025 */
1026 OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
1027 var iframe, iframePos,
1028 pos = $element.offset(),
1029 anchorPos = $anchor.offset(),
1030 elementDocument = this.getDocument( $element ),
1031 anchorDocument = this.getDocument( $anchor );
1032
1033 // If $element isn't in the same document as $anchor, traverse up
1034 while ( elementDocument !== anchorDocument ) {
1035 iframe = elementDocument.defaultView.frameElement;
1036 if ( !iframe ) {
1037 throw new Error( '$element frame is not contained in $anchor frame' );
1038 }
1039 iframePos = $( iframe ).offset();
1040 pos.left += iframePos.left;
1041 pos.top += iframePos.top;
1042 elementDocument = iframe.ownerDocument;
1043 }
1044 pos.left -= anchorPos.left;
1045 pos.top -= anchorPos.top;
1046 return pos;
1047 };
1048
1049 /**
1050 * Get element border sizes.
1051 *
1052 * @static
1053 * @param {HTMLElement} el Element to measure
1054 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1055 */
1056 OO.ui.Element.static.getBorders = function ( el ) {
1057 var doc = el.ownerDocument,
1058 win = doc.defaultView,
1059 style = win.getComputedStyle( el, null ),
1060 $el = $( el ),
1061 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
1062 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
1063 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
1064 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
1065
1066 return {
1067 top: top,
1068 left: left,
1069 bottom: bottom,
1070 right: right
1071 };
1072 };
1073
1074 /**
1075 * Get dimensions of an element or window.
1076 *
1077 * @static
1078 * @param {HTMLElement|Window} el Element to measure
1079 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1080 */
1081 OO.ui.Element.static.getDimensions = function ( el ) {
1082 var $el, $win,
1083 doc = el.ownerDocument || el.document,
1084 win = doc.defaultView;
1085
1086 if ( win === el || el === doc.documentElement ) {
1087 $win = $( win );
1088 return {
1089 borders: { top: 0, left: 0, bottom: 0, right: 0 },
1090 scroll: {
1091 top: $win.scrollTop(),
1092 left: $win.scrollLeft()
1093 },
1094 scrollbar: { right: 0, bottom: 0 },
1095 rect: {
1096 top: 0,
1097 left: 0,
1098 bottom: $win.innerHeight(),
1099 right: $win.innerWidth()
1100 }
1101 };
1102 } else {
1103 $el = $( el );
1104 return {
1105 borders: this.getBorders( el ),
1106 scroll: {
1107 top: $el.scrollTop(),
1108 left: $el.scrollLeft()
1109 },
1110 scrollbar: {
1111 right: $el.innerWidth() - el.clientWidth,
1112 bottom: $el.innerHeight() - el.clientHeight
1113 },
1114 rect: el.getBoundingClientRect()
1115 };
1116 }
1117 };
1118
1119 /**
1120 * Get the number of pixels that an element's content is scrolled to the left.
1121 *
1122 * Adapted from <https://github.com/othree/jquery.rtl-scroll-type>.
1123 * Original code copyright 2012 Wei-Ko Kao, licensed under the MIT License.
1124 *
1125 * This function smooths out browser inconsistencies (nicely described in the README at
1126 * <https://github.com/othree/jquery.rtl-scroll-type>) and produces a result consistent
1127 * with Firefox's 'scrollLeft', which seems the sanest.
1128 *
1129 * @static
1130 * @method
1131 * @param {HTMLElement|Window} el Element to measure
1132 * @return {number} Scroll position from the left.
1133 * If the element's direction is LTR, this is a positive number between `0` (initial scroll position)
1134 * and `el.scrollWidth - el.clientWidth` (furthest possible scroll position).
1135 * If the element's direction is RTL, this is a negative number between `0` (initial scroll position)
1136 * and `-el.scrollWidth + el.clientWidth` (furthest possible scroll position).
1137 */
1138 OO.ui.Element.static.getScrollLeft = ( function () {
1139 var rtlScrollType = null;
1140
1141 function test() {
1142 var $definer = $( '<div dir="rtl" style="font-size: 14px; width: 1px; height: 1px; position: absolute; top: -1000px; overflow: scroll">A</div>' ),
1143 definer = $definer[ 0 ];
1144
1145 $definer.appendTo( 'body' );
1146 if ( definer.scrollLeft > 0 ) {
1147 // Safari, Chrome
1148 rtlScrollType = 'default';
1149 } else {
1150 definer.scrollLeft = 1;
1151 if ( definer.scrollLeft === 0 ) {
1152 // Firefox, old Opera
1153 rtlScrollType = 'negative';
1154 } else {
1155 // Internet Explorer, Edge
1156 rtlScrollType = 'reverse';
1157 }
1158 }
1159 $definer.remove();
1160 }
1161
1162 return function getScrollLeft( el ) {
1163 var isRoot = el.window === el ||
1164 el === el.ownerDocument.body ||
1165 el === el.ownerDocument.documentElement,
1166 scrollLeft = isRoot ? $( window ).scrollLeft() : el.scrollLeft,
1167 // All browsers use the correct scroll type ('negative') on the root, so don't
1168 // do any fixups when looking at the root element
1169 direction = isRoot ? 'ltr' : $( el ).css( 'direction' );
1170
1171 if ( direction === 'rtl' ) {
1172 if ( rtlScrollType === null ) {
1173 test();
1174 }
1175 if ( rtlScrollType === 'reverse' ) {
1176 scrollLeft = -scrollLeft;
1177 } else if ( rtlScrollType === 'default' ) {
1178 scrollLeft = scrollLeft - el.scrollWidth + el.clientWidth;
1179 }
1180 }
1181
1182 return scrollLeft;
1183 };
1184 }() );
1185
1186 /**
1187 * Get the root scrollable element of given element's document.
1188 *
1189 * On Blink-based browsers (Chrome etc.), `document.documentElement` can't be used to get or set
1190 * the scrollTop property; instead we have to use `document.body`. Changing and testing the value
1191 * lets us use 'body' or 'documentElement' based on what is working.
1192 *
1193 * https://code.google.com/p/chromium/issues/detail?id=303131
1194 *
1195 * @static
1196 * @param {HTMLElement} el Element to find root scrollable parent for
1197 * @return {HTMLElement} Scrollable parent, `document.body` or `document.documentElement`
1198 * depending on browser
1199 */
1200 OO.ui.Element.static.getRootScrollableElement = function ( el ) {
1201 var scrollTop, body;
1202
1203 if ( OO.ui.scrollableElement === undefined ) {
1204 body = el.ownerDocument.body;
1205 scrollTop = body.scrollTop;
1206 body.scrollTop = 1;
1207
1208 // In some browsers (observed in Chrome 56 on Linux Mint 18.1),
1209 // body.scrollTop doesn't become exactly 1, but a fractional value like 0.76
1210 if ( Math.round( body.scrollTop ) === 1 ) {
1211 body.scrollTop = scrollTop;
1212 OO.ui.scrollableElement = 'body';
1213 } else {
1214 OO.ui.scrollableElement = 'documentElement';
1215 }
1216 }
1217
1218 return el.ownerDocument[ OO.ui.scrollableElement ];
1219 };
1220
1221 /**
1222 * Get closest scrollable container.
1223 *
1224 * Traverses up until either a scrollable element or the root is reached, in which case the root
1225 * scrollable element will be returned (see #getRootScrollableElement).
1226 *
1227 * @static
1228 * @param {HTMLElement} el Element to find scrollable container for
1229 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1230 * @return {HTMLElement} Closest scrollable container
1231 */
1232 OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
1233 var i, val,
1234 // Browsers do not correctly return the computed value of 'overflow' when 'overflow-x' and
1235 // 'overflow-y' have different values, so we need to check the separate properties.
1236 props = [ 'overflow-x', 'overflow-y' ],
1237 $parent = $( el ).parent();
1238
1239 if ( dimension === 'x' || dimension === 'y' ) {
1240 props = [ 'overflow-' + dimension ];
1241 }
1242
1243 // Special case for the document root (which doesn't really have any scrollable container, since
1244 // it is the ultimate scrollable container, but this is probably saner than null or exception)
1245 if ( $( el ).is( 'html, body' ) ) {
1246 return this.getRootScrollableElement( el );
1247 }
1248
1249 while ( $parent.length ) {
1250 if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
1251 return $parent[ 0 ];
1252 }
1253 i = props.length;
1254 while ( i-- ) {
1255 val = $parent.css( props[ i ] );
1256 // We assume that elements with 'overflow' (in any direction) set to 'hidden' will never be
1257 // scrolled in that direction, but they can actually be scrolled programatically. The user can
1258 // unintentionally perform a scroll in such case even if the application doesn't scroll
1259 // programatically, e.g. when jumping to an anchor, or when using built-in find functionality.
1260 // This could cause funny issues...
1261 if ( val === 'auto' || val === 'scroll' ) {
1262 return $parent[ 0 ];
1263 }
1264 }
1265 $parent = $parent.parent();
1266 }
1267 // The element is unattached... return something mostly sane
1268 return this.getRootScrollableElement( el );
1269 };
1270
1271 /**
1272 * Scroll element into view.
1273 *
1274 * @static
1275 * @param {HTMLElement} el Element to scroll into view
1276 * @param {Object} [config] Configuration options
1277 * @param {string} [config.duration='fast'] jQuery animation duration value
1278 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1279 * to scroll in both directions
1280 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1281 */
1282 OO.ui.Element.static.scrollIntoView = function ( el, config ) {
1283 var position, animations, container, $container, elementDimensions, containerDimensions, $window,
1284 deferred = $.Deferred();
1285
1286 // Configuration initialization
1287 config = config || {};
1288
1289 animations = {};
1290 container = this.getClosestScrollableContainer( el, config.direction );
1291 $container = $( container );
1292 elementDimensions = this.getDimensions( el );
1293 containerDimensions = this.getDimensions( container );
1294 $window = $( this.getWindow( el ) );
1295
1296 // Compute the element's position relative to the container
1297 if ( $container.is( 'html, body' ) ) {
1298 // If the scrollable container is the root, this is easy
1299 position = {
1300 top: elementDimensions.rect.top,
1301 bottom: $window.innerHeight() - elementDimensions.rect.bottom,
1302 left: elementDimensions.rect.left,
1303 right: $window.innerWidth() - elementDimensions.rect.right
1304 };
1305 } else {
1306 // Otherwise, we have to subtract el's coordinates from container's coordinates
1307 position = {
1308 top: elementDimensions.rect.top - ( containerDimensions.rect.top + containerDimensions.borders.top ),
1309 bottom: containerDimensions.rect.bottom - containerDimensions.borders.bottom - containerDimensions.scrollbar.bottom - elementDimensions.rect.bottom,
1310 left: elementDimensions.rect.left - ( containerDimensions.rect.left + containerDimensions.borders.left ),
1311 right: containerDimensions.rect.right - containerDimensions.borders.right - containerDimensions.scrollbar.right - elementDimensions.rect.right
1312 };
1313 }
1314
1315 if ( !config.direction || config.direction === 'y' ) {
1316 if ( position.top < 0 ) {
1317 animations.scrollTop = containerDimensions.scroll.top + position.top;
1318 } else if ( position.top > 0 && position.bottom < 0 ) {
1319 animations.scrollTop = containerDimensions.scroll.top + Math.min( position.top, -position.bottom );
1320 }
1321 }
1322 if ( !config.direction || config.direction === 'x' ) {
1323 if ( position.left < 0 ) {
1324 animations.scrollLeft = containerDimensions.scroll.left + position.left;
1325 } else if ( position.left > 0 && position.right < 0 ) {
1326 animations.scrollLeft = containerDimensions.scroll.left + Math.min( position.left, -position.right );
1327 }
1328 }
1329 if ( !$.isEmptyObject( animations ) ) {
1330 $container.stop( true ).animate( animations, config.duration === undefined ? 'fast' : config.duration );
1331 $container.queue( function ( next ) {
1332 deferred.resolve();
1333 next();
1334 } );
1335 } else {
1336 deferred.resolve();
1337 }
1338 return deferred.promise();
1339 };
1340
1341 /**
1342 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1343 * and reserve space for them, because it probably doesn't.
1344 *
1345 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1346 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1347 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1348 * and then reattach (or show) them back.
1349 *
1350 * @static
1351 * @param {HTMLElement} el Element to reconsider the scrollbars on
1352 */
1353 OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
1354 var i, len, scrollLeft, scrollTop, nodes = [];
1355 // Save scroll position
1356 scrollLeft = el.scrollLeft;
1357 scrollTop = el.scrollTop;
1358 // Detach all children
1359 while ( el.firstChild ) {
1360 nodes.push( el.firstChild );
1361 el.removeChild( el.firstChild );
1362 }
1363 // Force reflow
1364 void el.offsetHeight;
1365 // Reattach all children
1366 for ( i = 0, len = nodes.length; i < len; i++ ) {
1367 el.appendChild( nodes[ i ] );
1368 }
1369 // Restore scroll position (no-op if scrollbars disappeared)
1370 el.scrollLeft = scrollLeft;
1371 el.scrollTop = scrollTop;
1372 };
1373
1374 /* Methods */
1375
1376 /**
1377 * Toggle visibility of an element.
1378 *
1379 * @param {boolean} [show] Make element visible, omit to toggle visibility
1380 * @fires visible
1381 * @chainable
1382 */
1383 OO.ui.Element.prototype.toggle = function ( show ) {
1384 show = show === undefined ? !this.visible : !!show;
1385
1386 if ( show !== this.isVisible() ) {
1387 this.visible = show;
1388 this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
1389 this.emit( 'toggle', show );
1390 }
1391
1392 return this;
1393 };
1394
1395 /**
1396 * Check if element is visible.
1397 *
1398 * @return {boolean} element is visible
1399 */
1400 OO.ui.Element.prototype.isVisible = function () {
1401 return this.visible;
1402 };
1403
1404 /**
1405 * Get element data.
1406 *
1407 * @return {Mixed} Element data
1408 */
1409 OO.ui.Element.prototype.getData = function () {
1410 return this.data;
1411 };
1412
1413 /**
1414 * Set element data.
1415 *
1416 * @param {Mixed} data Element data
1417 * @chainable
1418 */
1419 OO.ui.Element.prototype.setData = function ( data ) {
1420 this.data = data;
1421 return this;
1422 };
1423
1424 /**
1425 * Set the element has an 'id' attribute.
1426 *
1427 * @param {string} id
1428 * @chainable
1429 */
1430 OO.ui.Element.prototype.setElementId = function ( id ) {
1431 this.elementId = id;
1432 this.$element.attr( 'id', id );
1433 return this;
1434 };
1435
1436 /**
1437 * Ensure that the element has an 'id' attribute, setting it to an unique value if it's missing,
1438 * and return its value.
1439 *
1440 * @return {string}
1441 */
1442 OO.ui.Element.prototype.getElementId = function () {
1443 if ( this.elementId === null ) {
1444 this.setElementId( OO.ui.generateElementId() );
1445 }
1446 return this.elementId;
1447 };
1448
1449 /**
1450 * Check if element supports one or more methods.
1451 *
1452 * @param {string|string[]} methods Method or list of methods to check
1453 * @return {boolean} All methods are supported
1454 */
1455 OO.ui.Element.prototype.supports = function ( methods ) {
1456 var i, len,
1457 support = 0;
1458
1459 methods = Array.isArray( methods ) ? methods : [ methods ];
1460 for ( i = 0, len = methods.length; i < len; i++ ) {
1461 if ( $.isFunction( this[ methods[ i ] ] ) ) {
1462 support++;
1463 }
1464 }
1465
1466 return methods.length === support;
1467 };
1468
1469 /**
1470 * Update the theme-provided classes.
1471 *
1472 * @localdoc This is called in element mixins and widget classes any time state changes.
1473 * Updating is debounced, minimizing overhead of changing multiple attributes and
1474 * guaranteeing that theme updates do not occur within an element's constructor
1475 */
1476 OO.ui.Element.prototype.updateThemeClasses = function () {
1477 OO.ui.theme.queueUpdateElementClasses( this );
1478 };
1479
1480 /**
1481 * Get the HTML tag name.
1482 *
1483 * Override this method to base the result on instance information.
1484 *
1485 * @return {string} HTML tag name
1486 */
1487 OO.ui.Element.prototype.getTagName = function () {
1488 return this.constructor.static.tagName;
1489 };
1490
1491 /**
1492 * Check if the element is attached to the DOM
1493 *
1494 * @return {boolean} The element is attached to the DOM
1495 */
1496 OO.ui.Element.prototype.isElementAttached = function () {
1497 return $.contains( this.getElementDocument(), this.$element[ 0 ] );
1498 };
1499
1500 /**
1501 * Get the DOM document.
1502 *
1503 * @return {HTMLDocument} Document object
1504 */
1505 OO.ui.Element.prototype.getElementDocument = function () {
1506 // Don't cache this in other ways either because subclasses could can change this.$element
1507 return OO.ui.Element.static.getDocument( this.$element );
1508 };
1509
1510 /**
1511 * Get the DOM window.
1512 *
1513 * @return {Window} Window object
1514 */
1515 OO.ui.Element.prototype.getElementWindow = function () {
1516 return OO.ui.Element.static.getWindow( this.$element );
1517 };
1518
1519 /**
1520 * Get closest scrollable container.
1521 *
1522 * @return {HTMLElement} Closest scrollable container
1523 */
1524 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1525 return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
1526 };
1527
1528 /**
1529 * Get group element is in.
1530 *
1531 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1532 */
1533 OO.ui.Element.prototype.getElementGroup = function () {
1534 return this.elementGroup;
1535 };
1536
1537 /**
1538 * Set group element is in.
1539 *
1540 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1541 * @chainable
1542 */
1543 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1544 this.elementGroup = group;
1545 return this;
1546 };
1547
1548 /**
1549 * Scroll element into view.
1550 *
1551 * @param {Object} [config] Configuration options
1552 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1553 */
1554 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
1555 if (
1556 !this.isElementAttached() ||
1557 !this.isVisible() ||
1558 ( this.getElementGroup() && !this.getElementGroup().isVisible() )
1559 ) {
1560 return $.Deferred().resolve();
1561 }
1562 return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
1563 };
1564
1565 /**
1566 * Restore the pre-infusion dynamic state for this widget.
1567 *
1568 * This method is called after #$element has been inserted into DOM. The parameter is the return
1569 * value of #gatherPreInfuseState.
1570 *
1571 * @protected
1572 * @param {Object} state
1573 */
1574 OO.ui.Element.prototype.restorePreInfuseState = function () {
1575 };
1576
1577 /**
1578 * Wraps an HTML snippet for use with configuration values which default
1579 * to strings. This bypasses the default html-escaping done to string
1580 * values.
1581 *
1582 * @class
1583 *
1584 * @constructor
1585 * @param {string} [content] HTML content
1586 */
1587 OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
1588 // Properties
1589 this.content = content;
1590 };
1591
1592 /* Setup */
1593
1594 OO.initClass( OO.ui.HtmlSnippet );
1595
1596 /* Methods */
1597
1598 /**
1599 * Render into HTML.
1600 *
1601 * @return {string} Unchanged HTML snippet.
1602 */
1603 OO.ui.HtmlSnippet.prototype.toString = function () {
1604 return this.content;
1605 };
1606
1607 /**
1608 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1609 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1610 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1611 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1612 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1613 *
1614 * @abstract
1615 * @class
1616 * @extends OO.ui.Element
1617 * @mixins OO.EventEmitter
1618 *
1619 * @constructor
1620 * @param {Object} [config] Configuration options
1621 */
1622 OO.ui.Layout = function OoUiLayout( config ) {
1623 // Configuration initialization
1624 config = config || {};
1625
1626 // Parent constructor
1627 OO.ui.Layout.parent.call( this, config );
1628
1629 // Mixin constructors
1630 OO.EventEmitter.call( this );
1631
1632 // Initialization
1633 this.$element.addClass( 'oo-ui-layout' );
1634 };
1635
1636 /* Setup */
1637
1638 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1639 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1640
1641 /* Methods */
1642
1643 /**
1644 * Reset scroll offsets
1645 *
1646 * @chainable
1647 */
1648 OO.ui.Layout.prototype.resetScroll = function () {
1649 this.$element[ 0 ].scrollTop = 0;
1650 // TODO: Reset scrollLeft in an RTL-aware manner, see OO.ui.Element.static.getScrollLeft.
1651
1652 return this;
1653 };
1654
1655 /**
1656 * Widgets are compositions of one or more OOUI elements that users can both view
1657 * and interact with. All widgets can be configured and modified via a standard API,
1658 * and their state can change dynamically according to a model.
1659 *
1660 * @abstract
1661 * @class
1662 * @extends OO.ui.Element
1663 * @mixins OO.EventEmitter
1664 *
1665 * @constructor
1666 * @param {Object} [config] Configuration options
1667 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1668 * appearance reflects this state.
1669 */
1670 OO.ui.Widget = function OoUiWidget( config ) {
1671 // Initialize config
1672 config = $.extend( { disabled: false }, config );
1673
1674 // Parent constructor
1675 OO.ui.Widget.parent.call( this, config );
1676
1677 // Mixin constructors
1678 OO.EventEmitter.call( this );
1679
1680 // Properties
1681 this.disabled = null;
1682 this.wasDisabled = null;
1683
1684 // Initialization
1685 this.$element.addClass( 'oo-ui-widget' );
1686 this.setDisabled( !!config.disabled );
1687 };
1688
1689 /* Setup */
1690
1691 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
1692 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
1693
1694 /* Events */
1695
1696 /**
1697 * @event disable
1698 *
1699 * A 'disable' event is emitted when the disabled state of the widget changes
1700 * (i.e. on disable **and** enable).
1701 *
1702 * @param {boolean} disabled Widget is disabled
1703 */
1704
1705 /**
1706 * @event toggle
1707 *
1708 * A 'toggle' event is emitted when the visibility of the widget changes.
1709 *
1710 * @param {boolean} visible Widget is visible
1711 */
1712
1713 /* Methods */
1714
1715 /**
1716 * Check if the widget is disabled.
1717 *
1718 * @return {boolean} Widget is disabled
1719 */
1720 OO.ui.Widget.prototype.isDisabled = function () {
1721 return this.disabled;
1722 };
1723
1724 /**
1725 * Set the 'disabled' state of the widget.
1726 *
1727 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1728 *
1729 * @param {boolean} disabled Disable widget
1730 * @chainable
1731 */
1732 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
1733 var isDisabled;
1734
1735 this.disabled = !!disabled;
1736 isDisabled = this.isDisabled();
1737 if ( isDisabled !== this.wasDisabled ) {
1738 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
1739 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
1740 this.$element.attr( 'aria-disabled', isDisabled.toString() );
1741 this.emit( 'disable', isDisabled );
1742 this.updateThemeClasses();
1743 }
1744 this.wasDisabled = isDisabled;
1745
1746 return this;
1747 };
1748
1749 /**
1750 * Update the disabled state, in case of changes in parent widget.
1751 *
1752 * @chainable
1753 */
1754 OO.ui.Widget.prototype.updateDisabled = function () {
1755 this.setDisabled( this.disabled );
1756 return this;
1757 };
1758
1759 /**
1760 * Get an ID of a labelable node which is part of this widget, if any, to be used for `<label for>`
1761 * value.
1762 *
1763 * If this function returns null, the widget should have a meaningful #simulateLabelClick method
1764 * instead.
1765 *
1766 * @return {string|null} The ID of the labelable element
1767 */
1768 OO.ui.Widget.prototype.getInputId = function () {
1769 return null;
1770 };
1771
1772 /**
1773 * Simulate the behavior of clicking on a label (a HTML `<label>` element) bound to this input.
1774 * HTML only allows `<label>` to act on specific "labelable" elements; complex widgets might need to
1775 * override this method to provide intuitive, accessible behavior.
1776 *
1777 * By default, this does nothing. OO.ui.mixin.TabIndexedElement overrides it for focusable widgets.
1778 * Individual widgets may override it too.
1779 *
1780 * This method is called by OO.ui.LabelWidget and OO.ui.FieldLayout. It should not be called
1781 * directly.
1782 */
1783 OO.ui.Widget.prototype.simulateLabelClick = function () {
1784 };
1785
1786 /**
1787 * Theme logic.
1788 *
1789 * @abstract
1790 * @class
1791 *
1792 * @constructor
1793 */
1794 OO.ui.Theme = function OoUiTheme() {
1795 this.elementClassesQueue = [];
1796 this.debouncedUpdateQueuedElementClasses = OO.ui.debounce( this.updateQueuedElementClasses );
1797 };
1798
1799 /* Setup */
1800
1801 OO.initClass( OO.ui.Theme );
1802
1803 /* Methods */
1804
1805 /**
1806 * Get a list of classes to be applied to a widget.
1807 *
1808 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
1809 * otherwise state transitions will not work properly.
1810 *
1811 * @param {OO.ui.Element} element Element for which to get classes
1812 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1813 */
1814 OO.ui.Theme.prototype.getElementClasses = function () {
1815 return { on: [], off: [] };
1816 };
1817
1818 /**
1819 * Update CSS classes provided by the theme.
1820 *
1821 * For elements with theme logic hooks, this should be called any time there's a state change.
1822 *
1823 * @param {OO.ui.Element} element Element for which to update classes
1824 */
1825 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
1826 var $elements = $( [] ),
1827 classes = this.getElementClasses( element );
1828
1829 if ( element.$icon ) {
1830 $elements = $elements.add( element.$icon );
1831 }
1832 if ( element.$indicator ) {
1833 $elements = $elements.add( element.$indicator );
1834 }
1835
1836 $elements
1837 .removeClass( classes.off )
1838 .addClass( classes.on );
1839 };
1840
1841 /**
1842 * @private
1843 */
1844 OO.ui.Theme.prototype.updateQueuedElementClasses = function () {
1845 var i;
1846 for ( i = 0; i < this.elementClassesQueue.length; i++ ) {
1847 this.updateElementClasses( this.elementClassesQueue[ i ] );
1848 }
1849 // Clear the queue
1850 this.elementClassesQueue = [];
1851 };
1852
1853 /**
1854 * Queue #updateElementClasses to be called for this element.
1855 *
1856 * @localdoc QUnit tests override this method to directly call #queueUpdateElementClasses,
1857 * to make them synchronous.
1858 *
1859 * @param {OO.ui.Element} element Element for which to update classes
1860 */
1861 OO.ui.Theme.prototype.queueUpdateElementClasses = function ( element ) {
1862 // Keep items in the queue unique. Use lastIndexOf to start checking from the end because that's
1863 // the most common case (this method is often called repeatedly for the same element).
1864 if ( this.elementClassesQueue.lastIndexOf( element ) !== -1 ) {
1865 return;
1866 }
1867 this.elementClassesQueue.push( element );
1868 this.debouncedUpdateQueuedElementClasses();
1869 };
1870
1871 /**
1872 * Get the transition duration in milliseconds for dialogs opening/closing
1873 *
1874 * The dialog should be fully rendered this many milliseconds after the
1875 * ready process has executed.
1876 *
1877 * @return {number} Transition duration in milliseconds
1878 */
1879 OO.ui.Theme.prototype.getDialogTransitionDuration = function () {
1880 return 0;
1881 };
1882
1883 /**
1884 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
1885 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
1886 * order in which users will navigate through the focusable elements via the "tab" key.
1887 *
1888 * @example
1889 * // TabIndexedElement is mixed into the ButtonWidget class
1890 * // to provide a tabIndex property.
1891 * var button1 = new OO.ui.ButtonWidget( {
1892 * label: 'fourth',
1893 * tabIndex: 4
1894 * } );
1895 * var button2 = new OO.ui.ButtonWidget( {
1896 * label: 'second',
1897 * tabIndex: 2
1898 * } );
1899 * var button3 = new OO.ui.ButtonWidget( {
1900 * label: 'third',
1901 * tabIndex: 3
1902 * } );
1903 * var button4 = new OO.ui.ButtonWidget( {
1904 * label: 'first',
1905 * tabIndex: 1
1906 * } );
1907 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
1908 *
1909 * @abstract
1910 * @class
1911 *
1912 * @constructor
1913 * @param {Object} [config] Configuration options
1914 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
1915 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
1916 * functionality will be applied to it instead.
1917 * @cfg {string|number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
1918 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
1919 * to remove the element from the tab-navigation flow.
1920 */
1921 OO.ui.mixin.TabIndexedElement = function OoUiMixinTabIndexedElement( config ) {
1922 // Configuration initialization
1923 config = $.extend( { tabIndex: 0 }, config );
1924
1925 // Properties
1926 this.$tabIndexed = null;
1927 this.tabIndex = null;
1928
1929 // Events
1930 this.connect( this, { disable: 'onTabIndexedElementDisable' } );
1931
1932 // Initialization
1933 this.setTabIndex( config.tabIndex );
1934 this.setTabIndexedElement( config.$tabIndexed || this.$element );
1935 };
1936
1937 /* Setup */
1938
1939 OO.initClass( OO.ui.mixin.TabIndexedElement );
1940
1941 /* Methods */
1942
1943 /**
1944 * Set the element that should use the tabindex functionality.
1945 *
1946 * This method is used to retarget a tabindex mixin so that its functionality applies
1947 * to the specified element. If an element is currently using the functionality, the mixin’s
1948 * effect on that element is removed before the new element is set up.
1949 *
1950 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
1951 * @chainable
1952 */
1953 OO.ui.mixin.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
1954 var tabIndex = this.tabIndex;
1955 // Remove attributes from old $tabIndexed
1956 this.setTabIndex( null );
1957 // Force update of new $tabIndexed
1958 this.$tabIndexed = $tabIndexed;
1959 this.tabIndex = tabIndex;
1960 return this.updateTabIndex();
1961 };
1962
1963 /**
1964 * Set the value of the tabindex.
1965 *
1966 * @param {string|number|null} tabIndex Tabindex value, or `null` for no tabindex
1967 * @chainable
1968 */
1969 OO.ui.mixin.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
1970 tabIndex = /^-?\d+$/.test( tabIndex ) ? Number( tabIndex ) : null;
1971
1972 if ( this.tabIndex !== tabIndex ) {
1973 this.tabIndex = tabIndex;
1974 this.updateTabIndex();
1975 }
1976
1977 return this;
1978 };
1979
1980 /**
1981 * Update the `tabindex` attribute, in case of changes to tab index or
1982 * disabled state.
1983 *
1984 * @private
1985 * @chainable
1986 */
1987 OO.ui.mixin.TabIndexedElement.prototype.updateTabIndex = function () {
1988 if ( this.$tabIndexed ) {
1989 if ( this.tabIndex !== null ) {
1990 // Do not index over disabled elements
1991 this.$tabIndexed.attr( {
1992 tabindex: this.isDisabled() ? -1 : this.tabIndex,
1993 // Support: ChromeVox and NVDA
1994 // These do not seem to inherit aria-disabled from parent elements
1995 'aria-disabled': this.isDisabled().toString()
1996 } );
1997 } else {
1998 this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
1999 }
2000 }
2001 return this;
2002 };
2003
2004 /**
2005 * Handle disable events.
2006 *
2007 * @private
2008 * @param {boolean} disabled Element is disabled
2009 */
2010 OO.ui.mixin.TabIndexedElement.prototype.onTabIndexedElementDisable = function () {
2011 this.updateTabIndex();
2012 };
2013
2014 /**
2015 * Get the value of the tabindex.
2016 *
2017 * @return {number|null} Tabindex value
2018 */
2019 OO.ui.mixin.TabIndexedElement.prototype.getTabIndex = function () {
2020 return this.tabIndex;
2021 };
2022
2023 /**
2024 * Get an ID of a focusable element of this widget, if any, to be used for `<label for>` value.
2025 *
2026 * If the element already has an ID then that is returned, otherwise unique ID is
2027 * generated, set on the element, and returned.
2028 *
2029 * @return {string|null} The ID of the focusable element
2030 */
2031 OO.ui.mixin.TabIndexedElement.prototype.getInputId = function () {
2032 var id;
2033
2034 if ( !this.$tabIndexed ) {
2035 return null;
2036 }
2037 if ( !this.isLabelableNode( this.$tabIndexed ) ) {
2038 return null;
2039 }
2040
2041 id = this.$tabIndexed.attr( 'id' );
2042 if ( id === undefined ) {
2043 id = OO.ui.generateElementId();
2044 this.$tabIndexed.attr( 'id', id );
2045 }
2046
2047 return id;
2048 };
2049
2050 /**
2051 * Whether the node is 'labelable' according to the HTML spec
2052 * (i.e., whether it can be interacted with through a `<label for="…">`).
2053 * See: <https://html.spec.whatwg.org/multipage/forms.html#category-label>.
2054 *
2055 * @private
2056 * @param {jQuery} $node
2057 * @return {boolean}
2058 */
2059 OO.ui.mixin.TabIndexedElement.prototype.isLabelableNode = function ( $node ) {
2060 var
2061 labelableTags = [ 'button', 'meter', 'output', 'progress', 'select', 'textarea' ],
2062 tagName = $node.prop( 'tagName' ).toLowerCase();
2063
2064 if ( tagName === 'input' && $node.attr( 'type' ) !== 'hidden' ) {
2065 return true;
2066 }
2067 if ( labelableTags.indexOf( tagName ) !== -1 ) {
2068 return true;
2069 }
2070 return false;
2071 };
2072
2073 /**
2074 * Focus this element.
2075 *
2076 * @chainable
2077 */
2078 OO.ui.mixin.TabIndexedElement.prototype.focus = function () {
2079 if ( !this.isDisabled() ) {
2080 this.$tabIndexed.focus();
2081 }
2082 return this;
2083 };
2084
2085 /**
2086 * Blur this element.
2087 *
2088 * @chainable
2089 */
2090 OO.ui.mixin.TabIndexedElement.prototype.blur = function () {
2091 this.$tabIndexed.blur();
2092 return this;
2093 };
2094
2095 /**
2096 * @inheritdoc OO.ui.Widget
2097 */
2098 OO.ui.mixin.TabIndexedElement.prototype.simulateLabelClick = function () {
2099 this.focus();
2100 };
2101
2102 /**
2103 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
2104 * interface element that can be configured with access keys for accessibility.
2105 * See the [OOUI documentation on MediaWiki] [1] for examples.
2106 *
2107 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches#Buttons
2108 *
2109 * @abstract
2110 * @class
2111 *
2112 * @constructor
2113 * @param {Object} [config] Configuration options
2114 * @cfg {jQuery} [$button] The button element created by the class.
2115 * If this configuration is omitted, the button element will use a generated `<a>`.
2116 * @cfg {boolean} [framed=true] Render the button with a frame
2117 */
2118 OO.ui.mixin.ButtonElement = function OoUiMixinButtonElement( config ) {
2119 // Configuration initialization
2120 config = config || {};
2121
2122 // Properties
2123 this.$button = null;
2124 this.framed = null;
2125 this.active = config.active !== undefined && config.active;
2126 this.onDocumentMouseUpHandler = this.onDocumentMouseUp.bind( this );
2127 this.onMouseDownHandler = this.onMouseDown.bind( this );
2128 this.onDocumentKeyUpHandler = this.onDocumentKeyUp.bind( this );
2129 this.onKeyDownHandler = this.onKeyDown.bind( this );
2130 this.onClickHandler = this.onClick.bind( this );
2131 this.onKeyPressHandler = this.onKeyPress.bind( this );
2132
2133 // Initialization
2134 this.$element.addClass( 'oo-ui-buttonElement' );
2135 this.toggleFramed( config.framed === undefined || config.framed );
2136 this.setButtonElement( config.$button || $( '<a>' ) );
2137 };
2138
2139 /* Setup */
2140
2141 OO.initClass( OO.ui.mixin.ButtonElement );
2142
2143 /* Static Properties */
2144
2145 /**
2146 * Cancel mouse down events.
2147 *
2148 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
2149 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
2150 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
2151 * parent widget.
2152 *
2153 * @static
2154 * @inheritable
2155 * @property {boolean}
2156 */
2157 OO.ui.mixin.ButtonElement.static.cancelButtonMouseDownEvents = true;
2158
2159 /* Events */
2160
2161 /**
2162 * A 'click' event is emitted when the button element is clicked.
2163 *
2164 * @event click
2165 */
2166
2167 /* Methods */
2168
2169 /**
2170 * Set the button element.
2171 *
2172 * This method is used to retarget a button mixin so that its functionality applies to
2173 * the specified button element instead of the one created by the class. If a button element
2174 * is already set, the method will remove the mixin’s effect on that element.
2175 *
2176 * @param {jQuery} $button Element to use as button
2177 */
2178 OO.ui.mixin.ButtonElement.prototype.setButtonElement = function ( $button ) {
2179 if ( this.$button ) {
2180 this.$button
2181 .removeClass( 'oo-ui-buttonElement-button' )
2182 .removeAttr( 'role accesskey' )
2183 .off( {
2184 mousedown: this.onMouseDownHandler,
2185 keydown: this.onKeyDownHandler,
2186 click: this.onClickHandler,
2187 keypress: this.onKeyPressHandler
2188 } );
2189 }
2190
2191 this.$button = $button
2192 .addClass( 'oo-ui-buttonElement-button' )
2193 .on( {
2194 mousedown: this.onMouseDownHandler,
2195 keydown: this.onKeyDownHandler,
2196 click: this.onClickHandler,
2197 keypress: this.onKeyPressHandler
2198 } );
2199
2200 // Add `role="button"` on `<a>` elements, where it's needed
2201 // `toUpperCase()` is added for XHTML documents
2202 if ( this.$button.prop( 'tagName' ).toUpperCase() === 'A' ) {
2203 this.$button.attr( 'role', 'button' );
2204 }
2205 };
2206
2207 /**
2208 * Handles mouse down events.
2209 *
2210 * @protected
2211 * @param {jQuery.Event} e Mouse down event
2212 */
2213 OO.ui.mixin.ButtonElement.prototype.onMouseDown = function ( e ) {
2214 if ( this.isDisabled() || e.which !== OO.ui.MouseButtons.LEFT ) {
2215 return;
2216 }
2217 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
2218 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
2219 // reliably remove the pressed class
2220 this.getElementDocument().addEventListener( 'mouseup', this.onDocumentMouseUpHandler, true );
2221 // Prevent change of focus unless specifically configured otherwise
2222 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
2223 return false;
2224 }
2225 };
2226
2227 /**
2228 * Handles document mouse up events.
2229 *
2230 * @protected
2231 * @param {MouseEvent} e Mouse up event
2232 */
2233 OO.ui.mixin.ButtonElement.prototype.onDocumentMouseUp = function ( e ) {
2234 if ( this.isDisabled() || e.which !== OO.ui.MouseButtons.LEFT ) {
2235 return;
2236 }
2237 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
2238 // Stop listening for mouseup, since we only needed this once
2239 this.getElementDocument().removeEventListener( 'mouseup', this.onDocumentMouseUpHandler, true );
2240 };
2241
2242 // Deprecated alias since 0.28.3
2243 OO.ui.mixin.ButtonElement.prototype.onMouseUp = function () {
2244 OO.ui.warnDeprecation( 'onMouseUp is deprecated, use onDocumentMouseUp instead' );
2245 this.onDocumentMouseUp.apply( this, arguments );
2246 };
2247
2248 /**
2249 * Handles mouse click events.
2250 *
2251 * @protected
2252 * @param {jQuery.Event} e Mouse click event
2253 * @fires click
2254 */
2255 OO.ui.mixin.ButtonElement.prototype.onClick = function ( e ) {
2256 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
2257 if ( this.emit( 'click' ) ) {
2258 return false;
2259 }
2260 }
2261 };
2262
2263 /**
2264 * Handles key down events.
2265 *
2266 * @protected
2267 * @param {jQuery.Event} e Key down event
2268 */
2269 OO.ui.mixin.ButtonElement.prototype.onKeyDown = function ( e ) {
2270 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
2271 return;
2272 }
2273 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
2274 // Run the keyup handler no matter where the key is when the button is let go, so we can
2275 // reliably remove the pressed class
2276 this.getElementDocument().addEventListener( 'keyup', this.onDocumentKeyUpHandler, true );
2277 };
2278
2279 /**
2280 * Handles document key up events.
2281 *
2282 * @protected
2283 * @param {KeyboardEvent} e Key up event
2284 */
2285 OO.ui.mixin.ButtonElement.prototype.onDocumentKeyUp = function ( e ) {
2286 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
2287 return;
2288 }
2289 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
2290 // Stop listening for keyup, since we only needed this once
2291 this.getElementDocument().removeEventListener( 'keyup', this.onDocumentKeyUpHandler, true );
2292 };
2293
2294 // Deprecated alias since 0.28.3
2295 OO.ui.mixin.ButtonElement.prototype.onKeyUp = function () {
2296 OO.ui.warnDeprecation( 'onKeyUp is deprecated, use onDocumentKeyUp instead' );
2297 this.onDocumentKeyUp.apply( this, arguments );
2298 };
2299
2300 /**
2301 * Handles key press events.
2302 *
2303 * @protected
2304 * @param {jQuery.Event} e Key press event
2305 * @fires click
2306 */
2307 OO.ui.mixin.ButtonElement.prototype.onKeyPress = function ( e ) {
2308 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
2309 if ( this.emit( 'click' ) ) {
2310 return false;
2311 }
2312 }
2313 };
2314
2315 /**
2316 * Check if button has a frame.
2317 *
2318 * @return {boolean} Button is framed
2319 */
2320 OO.ui.mixin.ButtonElement.prototype.isFramed = function () {
2321 return this.framed;
2322 };
2323
2324 /**
2325 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
2326 *
2327 * @param {boolean} [framed] Make button framed, omit to toggle
2328 * @chainable
2329 */
2330 OO.ui.mixin.ButtonElement.prototype.toggleFramed = function ( framed ) {
2331 framed = framed === undefined ? !this.framed : !!framed;
2332 if ( framed !== this.framed ) {
2333 this.framed = framed;
2334 this.$element
2335 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
2336 .toggleClass( 'oo-ui-buttonElement-framed', framed );
2337 this.updateThemeClasses();
2338 }
2339
2340 return this;
2341 };
2342
2343 /**
2344 * Set the button's active state.
2345 *
2346 * The active state can be set on:
2347 *
2348 * - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected
2349 * - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on
2350 * - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page
2351 *
2352 * @protected
2353 * @param {boolean} value Make button active
2354 * @chainable
2355 */
2356 OO.ui.mixin.ButtonElement.prototype.setActive = function ( value ) {
2357 this.active = !!value;
2358 this.$element.toggleClass( 'oo-ui-buttonElement-active', this.active );
2359 this.updateThemeClasses();
2360 return this;
2361 };
2362
2363 /**
2364 * Check if the button is active
2365 *
2366 * @protected
2367 * @return {boolean} The button is active
2368 */
2369 OO.ui.mixin.ButtonElement.prototype.isActive = function () {
2370 return this.active;
2371 };
2372
2373 /**
2374 * Any OOUI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
2375 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
2376 * items from the group is done through the interface the class provides.
2377 * For more information, please see the [OOUI documentation on MediaWiki] [1].
2378 *
2379 * [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Groups
2380 *
2381 * @abstract
2382 * @mixins OO.EmitterList
2383 * @class
2384 *
2385 * @constructor
2386 * @param {Object} [config] Configuration options
2387 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
2388 * is omitted, the group element will use a generated `<div>`.
2389 */
2390 OO.ui.mixin.GroupElement = function OoUiMixinGroupElement( config ) {
2391 // Configuration initialization
2392 config = config || {};
2393
2394 // Mixin constructors
2395 OO.EmitterList.call( this, config );
2396
2397 // Properties
2398 this.$group = null;
2399
2400 // Initialization
2401 this.setGroupElement( config.$group || $( '<div>' ) );
2402 };
2403
2404 /* Setup */
2405
2406 OO.mixinClass( OO.ui.mixin.GroupElement, OO.EmitterList );
2407
2408 /* Events */
2409
2410 /**
2411 * @event change
2412 *
2413 * A change event is emitted when the set of selected items changes.
2414 *
2415 * @param {OO.ui.Element[]} items Items currently in the group
2416 */
2417
2418 /* Methods */
2419
2420 /**
2421 * Set the group element.
2422 *
2423 * If an element is already set, items will be moved to the new element.
2424 *
2425 * @param {jQuery} $group Element to use as group
2426 */
2427 OO.ui.mixin.GroupElement.prototype.setGroupElement = function ( $group ) {
2428 var i, len;
2429
2430 this.$group = $group;
2431 for ( i = 0, len = this.items.length; i < len; i++ ) {
2432 this.$group.append( this.items[ i ].$element );
2433 }
2434 };
2435
2436 /**
2437 * Find an item by its data.
2438 *
2439 * Only the first item with matching data will be returned. To return all matching items,
2440 * use the #findItemsFromData method.
2441 *
2442 * @param {Object} data Item data to search for
2443 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2444 */
2445 OO.ui.mixin.GroupElement.prototype.findItemFromData = function ( data ) {
2446 var i, len, item,
2447 hash = OO.getHash( data );
2448
2449 for ( i = 0, len = this.items.length; i < len; i++ ) {
2450 item = this.items[ i ];
2451 if ( hash === OO.getHash( item.getData() ) ) {
2452 return item;
2453 }
2454 }
2455
2456 return null;
2457 };
2458
2459 /**
2460 * Find items by their data.
2461 *
2462 * All items with matching data will be returned. To return only the first match, use the #findItemFromData method instead.
2463 *
2464 * @param {Object} data Item data to search for
2465 * @return {OO.ui.Element[]} Items with equivalent data
2466 */
2467 OO.ui.mixin.GroupElement.prototype.findItemsFromData = function ( data ) {
2468 var i, len, item,
2469 hash = OO.getHash( data ),
2470 items = [];
2471
2472 for ( i = 0, len = this.items.length; i < len; i++ ) {
2473 item = this.items[ i ];
2474 if ( hash === OO.getHash( item.getData() ) ) {
2475 items.push( item );
2476 }
2477 }
2478
2479 return items;
2480 };
2481
2482 /**
2483 * Add items to the group.
2484 *
2485 * Items will be added to the end of the group array unless the optional `index` parameter specifies
2486 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
2487 *
2488 * @param {OO.ui.Element[]} items An array of items to add to the group
2489 * @param {number} [index] Index of the insertion point
2490 * @chainable
2491 */
2492 OO.ui.mixin.GroupElement.prototype.addItems = function ( items, index ) {
2493 // Mixin method
2494 OO.EmitterList.prototype.addItems.call( this, items, index );
2495
2496 this.emit( 'change', this.getItems() );
2497 return this;
2498 };
2499
2500 /**
2501 * @inheritdoc
2502 */
2503 OO.ui.mixin.GroupElement.prototype.moveItem = function ( items, newIndex ) {
2504 // insertItemElements expects this.items to not have been modified yet, so call before the mixin
2505 this.insertItemElements( items, newIndex );
2506
2507 // Mixin method
2508 newIndex = OO.EmitterList.prototype.moveItem.call( this, items, newIndex );
2509
2510 return newIndex;
2511 };
2512
2513 /**
2514 * @inheritdoc
2515 */
2516 OO.ui.mixin.GroupElement.prototype.insertItem = function ( item, index ) {
2517 item.setElementGroup( this );
2518 this.insertItemElements( item, index );
2519
2520 // Mixin method
2521 index = OO.EmitterList.prototype.insertItem.call( this, item, index );
2522
2523 return index;
2524 };
2525
2526 /**
2527 * Insert elements into the group
2528 *
2529 * @private
2530 * @param {OO.ui.Element} itemWidget Item to insert
2531 * @param {number} index Insertion index
2532 */
2533 OO.ui.mixin.GroupElement.prototype.insertItemElements = function ( itemWidget, index ) {
2534 if ( index === undefined || index < 0 || index >= this.items.length ) {
2535 this.$group.append( itemWidget.$element );
2536 } else if ( index === 0 ) {
2537 this.$group.prepend( itemWidget.$element );
2538 } else {
2539 this.items[ index ].$element.before( itemWidget.$element );
2540 }
2541 };
2542
2543 /**
2544 * Remove the specified items from a group.
2545 *
2546 * Removed items are detached (not removed) from the DOM so that they may be reused.
2547 * To remove all items from a group, you may wish to use the #clearItems method instead.
2548 *
2549 * @param {OO.ui.Element[]} items An array of items to remove
2550 * @chainable
2551 */
2552 OO.ui.mixin.GroupElement.prototype.removeItems = function ( items ) {
2553 var i, len, item, index;
2554
2555 // Remove specific items elements
2556 for ( i = 0, len = items.length; i < len; i++ ) {
2557 item = items[ i ];
2558 index = this.items.indexOf( item );
2559 if ( index !== -1 ) {
2560 item.setElementGroup( null );
2561 item.$element.detach();
2562 }
2563 }
2564
2565 // Mixin method
2566 OO.EmitterList.prototype.removeItems.call( this, items );
2567
2568 this.emit( 'change', this.getItems() );
2569 return this;
2570 };
2571
2572 /**
2573 * Clear all items from the group.
2574 *
2575 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2576 * To remove only a subset of items from a group, use the #removeItems method.
2577 *
2578 * @chainable
2579 */
2580 OO.ui.mixin.GroupElement.prototype.clearItems = function () {
2581 var i, len;
2582
2583 // Remove all item elements
2584 for ( i = 0, len = this.items.length; i < len; i++ ) {
2585 this.items[ i ].setElementGroup( null );
2586 this.items[ i ].$element.detach();
2587 }
2588
2589 // Mixin method
2590 OO.EmitterList.prototype.clearItems.call( this );
2591
2592 this.emit( 'change', this.getItems() );
2593 return this;
2594 };
2595
2596 /**
2597 * LabelElement is often mixed into other classes to generate a label, which
2598 * helps identify the function of an interface element.
2599 * See the [OOUI documentation on MediaWiki] [1] for more information.
2600 *
2601 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
2602 *
2603 * @abstract
2604 * @class
2605 *
2606 * @constructor
2607 * @param {Object} [config] Configuration options
2608 * @cfg {jQuery} [$label] The label element created by the class. If this
2609 * configuration is omitted, the label element will use a generated `<span>`.
2610 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
2611 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
2612 * in the future. See the [OOUI documentation on MediaWiki] [2] for examples.
2613 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
2614 * @cfg {boolean} [invisibleLabel] Whether the label should be visually hidden (but still accessible
2615 * to screen-readers).
2616 */
2617 OO.ui.mixin.LabelElement = function OoUiMixinLabelElement( config ) {
2618 // Configuration initialization
2619 config = config || {};
2620
2621 // Properties
2622 this.$label = null;
2623 this.label = null;
2624 this.invisibleLabel = null;
2625
2626 // Initialization
2627 this.setLabel( config.label || this.constructor.static.label );
2628 this.setLabelElement( config.$label || $( '<span>' ) );
2629 this.setInvisibleLabel( config.invisibleLabel );
2630 };
2631
2632 /* Setup */
2633
2634 OO.initClass( OO.ui.mixin.LabelElement );
2635
2636 /* Events */
2637
2638 /**
2639 * @event labelChange
2640 * @param {string} value
2641 */
2642
2643 /* Static Properties */
2644
2645 /**
2646 * The label text. The label can be specified as a plaintext string, a function that will
2647 * produce a string in the future, or `null` for no label. The static value will
2648 * be overridden if a label is specified with the #label config option.
2649 *
2650 * @static
2651 * @inheritable
2652 * @property {string|Function|null}
2653 */
2654 OO.ui.mixin.LabelElement.static.label = null;
2655
2656 /* Static methods */
2657
2658 /**
2659 * Highlight the first occurrence of the query in the given text
2660 *
2661 * @param {string} text Text
2662 * @param {string} query Query to find
2663 * @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
2664 * @return {jQuery} Text with the first match of the query
2665 * sub-string wrapped in highlighted span
2666 */
2667 OO.ui.mixin.LabelElement.static.highlightQuery = function ( text, query, compare ) {
2668 var i, tLen, qLen,
2669 offset = -1,
2670 $result = $( '<span>' );
2671
2672 if ( compare ) {
2673 tLen = text.length;
2674 qLen = query.length;
2675 for ( i = 0; offset === -1 && i <= tLen - qLen; i++ ) {
2676 if ( compare( query, text.slice( i, i + qLen ) ) === 0 ) {
2677 offset = i;
2678 }
2679 }
2680 } else {
2681 offset = text.toLowerCase().indexOf( query.toLowerCase() );
2682 }
2683
2684 if ( !query.length || offset === -1 ) {
2685 $result.text( text );
2686 } else {
2687 $result.append(
2688 document.createTextNode( text.slice( 0, offset ) ),
2689 $( '<span>' )
2690 .addClass( 'oo-ui-labelElement-label-highlight' )
2691 .text( text.slice( offset, offset + query.length ) ),
2692 document.createTextNode( text.slice( offset + query.length ) )
2693 );
2694 }
2695 return $result.contents();
2696 };
2697
2698 /* Methods */
2699
2700 /**
2701 * Set the label element.
2702 *
2703 * If an element is already set, it will be cleaned up before setting up the new element.
2704 *
2705 * @param {jQuery} $label Element to use as label
2706 */
2707 OO.ui.mixin.LabelElement.prototype.setLabelElement = function ( $label ) {
2708 if ( this.$label ) {
2709 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
2710 }
2711
2712 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
2713 this.setLabelContent( this.label );
2714 };
2715
2716 /**
2717 * Set the label.
2718 *
2719 * An empty string will result in the label being hidden. A string containing only whitespace will
2720 * be converted to a single `&nbsp;`.
2721 *
2722 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
2723 * text; or null for no label
2724 * @chainable
2725 */
2726 OO.ui.mixin.LabelElement.prototype.setLabel = function ( label ) {
2727 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
2728 label = ( ( typeof label === 'string' || label instanceof jQuery ) && label.length ) || ( label instanceof OO.ui.HtmlSnippet && label.toString().length ) ? label : null;
2729
2730 if ( this.label !== label ) {
2731 if ( this.$label ) {
2732 this.setLabelContent( label );
2733 }
2734 this.label = label;
2735 this.emit( 'labelChange' );
2736 }
2737
2738 this.$element.toggleClass( 'oo-ui-labelElement', !!this.label && !this.invisibleLabel );
2739
2740 return this;
2741 };
2742
2743 /**
2744 * Set whether the label should be visually hidden (but still accessible to screen-readers).
2745 *
2746 * @param {boolean} invisibleLabel
2747 * @chainable
2748 */
2749 OO.ui.mixin.LabelElement.prototype.setInvisibleLabel = function ( invisibleLabel ) {
2750 invisibleLabel = !!invisibleLabel;
2751
2752 if ( this.invisibleLabel !== invisibleLabel ) {
2753 this.invisibleLabel = invisibleLabel;
2754 this.emit( 'labelChange' );
2755 }
2756
2757 this.$label.toggleClass( 'oo-ui-labelElement-invisible', this.invisibleLabel );
2758 // Pretend that there is no label, a lot of CSS has been written with this assumption
2759 this.$element.toggleClass( 'oo-ui-labelElement', !!this.label && !this.invisibleLabel );
2760
2761 return this;
2762 };
2763
2764 /**
2765 * Set the label as plain text with a highlighted query
2766 *
2767 * @param {string} text Text label to set
2768 * @param {string} query Substring of text to highlight
2769 * @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
2770 * @chainable
2771 */
2772 OO.ui.mixin.LabelElement.prototype.setHighlightedQuery = function ( text, query, compare ) {
2773 return this.setLabel( this.constructor.static.highlightQuery( text, query, compare ) );
2774 };
2775
2776 /**
2777 * Get the label.
2778 *
2779 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
2780 * text; or null for no label
2781 */
2782 OO.ui.mixin.LabelElement.prototype.getLabel = function () {
2783 return this.label;
2784 };
2785
2786 /**
2787 * Set the content of the label.
2788 *
2789 * Do not call this method until after the label element has been set by #setLabelElement.
2790 *
2791 * @private
2792 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
2793 * text; or null for no label
2794 */
2795 OO.ui.mixin.LabelElement.prototype.setLabelContent = function ( label ) {
2796 if ( typeof label === 'string' ) {
2797 if ( label.match( /^\s*$/ ) ) {
2798 // Convert whitespace only string to a single non-breaking space
2799 this.$label.html( '&nbsp;' );
2800 } else {
2801 this.$label.text( label );
2802 }
2803 } else if ( label instanceof OO.ui.HtmlSnippet ) {
2804 this.$label.html( label.toString() );
2805 } else if ( label instanceof jQuery ) {
2806 this.$label.empty().append( label );
2807 } else {
2808 this.$label.empty();
2809 }
2810 };
2811
2812 /**
2813 * IconElement is often mixed into other classes to generate an icon.
2814 * Icons are graphics, about the size of normal text. They are used to aid the user
2815 * in locating a control or to convey information in a space-efficient way. See the
2816 * [OOUI documentation on MediaWiki] [1] for a list of icons
2817 * included in the library.
2818 *
2819 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
2820 *
2821 * @abstract
2822 * @class
2823 *
2824 * @constructor
2825 * @param {Object} [config] Configuration options
2826 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2827 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2828 * the icon element be set to an existing icon instead of the one generated by this class, set a
2829 * value using a jQuery selection. For example:
2830 *
2831 * // Use a <div> tag instead of a <span>
2832 * $icon: $("<div>")
2833 * // Use an existing icon element instead of the one generated by the class
2834 * $icon: this.$element
2835 * // Use an icon element from a child widget
2836 * $icon: this.childwidget.$element
2837 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
2838 * symbolic names. A map is used for i18n purposes and contains a `default` icon
2839 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
2840 * by the user's language.
2841 *
2842 * Example of an i18n map:
2843 *
2844 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2845 * See the [OOUI documentation on MediaWiki] [2] for a list of icons included in the library.
2846 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
2847 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
2848 * text. The icon title is displayed when users move the mouse over the icon.
2849 */
2850 OO.ui.mixin.IconElement = function OoUiMixinIconElement( config ) {
2851 // Configuration initialization
2852 config = config || {};
2853
2854 // Properties
2855 this.$icon = null;
2856 this.icon = null;
2857 this.iconTitle = null;
2858
2859 // Initialization
2860 this.setIcon( config.icon || this.constructor.static.icon );
2861 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
2862 this.setIconElement( config.$icon || $( '<span>' ) );
2863 };
2864
2865 /* Setup */
2866
2867 OO.initClass( OO.ui.mixin.IconElement );
2868
2869 /* Static Properties */
2870
2871 /**
2872 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
2873 * for i18n purposes and contains a `default` icon name and additional names keyed by
2874 * language code. The `default` name is used when no icon is keyed by the user's language.
2875 *
2876 * Example of an i18n map:
2877 *
2878 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2879 *
2880 * Note: the static property will be overridden if the #icon configuration is used.
2881 *
2882 * @static
2883 * @inheritable
2884 * @property {Object|string}
2885 */
2886 OO.ui.mixin.IconElement.static.icon = null;
2887
2888 /**
2889 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2890 * function that returns title text, or `null` for no title.
2891 *
2892 * The static property will be overridden if the #iconTitle configuration is used.
2893 *
2894 * @static
2895 * @inheritable
2896 * @property {string|Function|null}
2897 */
2898 OO.ui.mixin.IconElement.static.iconTitle = null;
2899
2900 /* Methods */
2901
2902 /**
2903 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2904 * applies to the specified icon element instead of the one created by the class. If an icon
2905 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2906 * and mixin methods will no longer affect the element.
2907 *
2908 * @param {jQuery} $icon Element to use as icon
2909 */
2910 OO.ui.mixin.IconElement.prototype.setIconElement = function ( $icon ) {
2911 if ( this.$icon ) {
2912 this.$icon
2913 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
2914 .removeAttr( 'title' );
2915 }
2916
2917 this.$icon = $icon
2918 .addClass( 'oo-ui-iconElement-icon' )
2919 .toggleClass( 'oo-ui-iconElement-noIcon', !this.icon )
2920 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
2921 if ( this.iconTitle !== null ) {
2922 this.$icon.attr( 'title', this.iconTitle );
2923 }
2924
2925 this.updateThemeClasses();
2926 };
2927
2928 /**
2929 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
2930 * The icon parameter can also be set to a map of icon names. See the #icon config setting
2931 * for an example.
2932 *
2933 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
2934 * by language code, or `null` to remove the icon.
2935 * @chainable
2936 */
2937 OO.ui.mixin.IconElement.prototype.setIcon = function ( icon ) {
2938 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
2939 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
2940
2941 if ( this.icon !== icon ) {
2942 if ( this.$icon ) {
2943 if ( this.icon !== null ) {
2944 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
2945 }
2946 if ( icon !== null ) {
2947 this.$icon.addClass( 'oo-ui-icon-' + icon );
2948 }
2949 }
2950 this.icon = icon;
2951 }
2952
2953 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
2954 if ( this.$icon ) {
2955 this.$icon.toggleClass( 'oo-ui-iconElement-noIcon', !this.icon );
2956 }
2957 this.updateThemeClasses();
2958
2959 return this;
2960 };
2961
2962 /**
2963 * Set the icon title. Use `null` to remove the title.
2964 *
2965 * @param {string|Function|null} iconTitle A text string used as the icon title,
2966 * a function that returns title text, or `null` for no title.
2967 * @chainable
2968 */
2969 OO.ui.mixin.IconElement.prototype.setIconTitle = function ( iconTitle ) {
2970 iconTitle =
2971 ( typeof iconTitle === 'function' || ( typeof iconTitle === 'string' && iconTitle.length ) ) ?
2972 OO.ui.resolveMsg( iconTitle ) : null;
2973
2974 if ( this.iconTitle !== iconTitle ) {
2975 this.iconTitle = iconTitle;
2976 if ( this.$icon ) {
2977 if ( this.iconTitle !== null ) {
2978 this.$icon.attr( 'title', iconTitle );
2979 } else {
2980 this.$icon.removeAttr( 'title' );
2981 }
2982 }
2983 }
2984
2985 return this;
2986 };
2987
2988 /**
2989 * Get the symbolic name of the icon.
2990 *
2991 * @return {string} Icon name
2992 */
2993 OO.ui.mixin.IconElement.prototype.getIcon = function () {
2994 return this.icon;
2995 };
2996
2997 /**
2998 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
2999 *
3000 * @return {string} Icon title text
3001 */
3002 OO.ui.mixin.IconElement.prototype.getIconTitle = function () {
3003 return this.iconTitle;
3004 };
3005
3006 /**
3007 * IndicatorElement is often mixed into other classes to generate an indicator.
3008 * Indicators are small graphics that are generally used in two ways:
3009 *
3010 * - To draw attention to the status of an item. For example, an indicator might be
3011 * used to show that an item in a list has errors that need to be resolved.
3012 * - To clarify the function of a control that acts in an exceptional way (a button
3013 * that opens a menu instead of performing an action directly, for example).
3014 *
3015 * For a list of indicators included in the library, please see the
3016 * [OOUI documentation on MediaWiki] [1].
3017 *
3018 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3019 *
3020 * @abstract
3021 * @class
3022 *
3023 * @constructor
3024 * @param {Object} [config] Configuration options
3025 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
3026 * configuration is omitted, the indicator element will use a generated `<span>`.
3027 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3028 * See the [OOUI documentation on MediaWiki][2] for a list of indicators included
3029 * in the library.
3030 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3031 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
3032 * or a function that returns title text. The indicator title is displayed when users move
3033 * the mouse over the indicator.
3034 */
3035 OO.ui.mixin.IndicatorElement = function OoUiMixinIndicatorElement( config ) {
3036 // Configuration initialization
3037 config = config || {};
3038
3039 // Properties
3040 this.$indicator = null;
3041 this.indicator = null;
3042 this.indicatorTitle = null;
3043
3044 // Initialization
3045 this.setIndicator( config.indicator || this.constructor.static.indicator );
3046 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
3047 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
3048 };
3049
3050 /* Setup */
3051
3052 OO.initClass( OO.ui.mixin.IndicatorElement );
3053
3054 /* Static Properties */
3055
3056 /**
3057 * Symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3058 * The static property will be overridden if the #indicator configuration is used.
3059 *
3060 * @static
3061 * @inheritable
3062 * @property {string|null}
3063 */
3064 OO.ui.mixin.IndicatorElement.static.indicator = null;
3065
3066 /**
3067 * A text string used as the indicator title, a function that returns title text, or `null`
3068 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
3069 *
3070 * @static
3071 * @inheritable
3072 * @property {string|Function|null}
3073 */
3074 OO.ui.mixin.IndicatorElement.static.indicatorTitle = null;
3075
3076 /* Methods */
3077
3078 /**
3079 * Set the indicator element.
3080 *
3081 * If an element is already set, it will be cleaned up before setting up the new element.
3082 *
3083 * @param {jQuery} $indicator Element to use as indicator
3084 */
3085 OO.ui.mixin.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
3086 if ( this.$indicator ) {
3087 this.$indicator
3088 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
3089 .removeAttr( 'title' );
3090 }
3091
3092 this.$indicator = $indicator
3093 .addClass( 'oo-ui-indicatorElement-indicator' )
3094 .toggleClass( 'oo-ui-indicatorElement-noIndicator', !this.indicator )
3095 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
3096 if ( this.indicatorTitle !== null ) {
3097 this.$indicator.attr( 'title', this.indicatorTitle );
3098 }
3099
3100 this.updateThemeClasses();
3101 };
3102
3103 /**
3104 * Set the indicator by its symbolic name: ‘clear’, ‘down’, ‘required’, ‘search’, ‘up’. Use `null` to remove the indicator.
3105 *
3106 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
3107 * @chainable
3108 */
3109 OO.ui.mixin.IndicatorElement.prototype.setIndicator = function ( indicator ) {
3110 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
3111
3112 if ( this.indicator !== indicator ) {
3113 if ( this.$indicator ) {
3114 if ( this.indicator !== null ) {
3115 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
3116 }
3117 if ( indicator !== null ) {
3118 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
3119 }
3120 }
3121 this.indicator = indicator;
3122 }
3123
3124 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
3125 if ( this.$indicator ) {
3126 this.$indicator.toggleClass( 'oo-ui-indicatorElement-noIndicator', !this.indicator );
3127 }
3128 this.updateThemeClasses();
3129
3130 return this;
3131 };
3132
3133 /**
3134 * Set the indicator title.
3135 *
3136 * The title is displayed when a user moves the mouse over the indicator.
3137 *
3138 * @param {string|Function|null} indicatorTitle Indicator title text, a function that returns text, or
3139 * `null` for no indicator title
3140 * @chainable
3141 */
3142 OO.ui.mixin.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
3143 indicatorTitle =
3144 ( typeof indicatorTitle === 'function' || ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ) ?
3145 OO.ui.resolveMsg( indicatorTitle ) : null;
3146
3147 if ( this.indicatorTitle !== indicatorTitle ) {
3148 this.indicatorTitle = indicatorTitle;
3149 if ( this.$indicator ) {
3150 if ( this.indicatorTitle !== null ) {
3151 this.$indicator.attr( 'title', indicatorTitle );
3152 } else {
3153 this.$indicator.removeAttr( 'title' );
3154 }
3155 }
3156 }
3157
3158 return this;
3159 };
3160
3161 /**
3162 * Get the symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3163 *
3164 * @return {string} Symbolic name of indicator
3165 */
3166 OO.ui.mixin.IndicatorElement.prototype.getIndicator = function () {
3167 return this.indicator;
3168 };
3169
3170 /**
3171 * Get the indicator title.
3172 *
3173 * The title is displayed when a user moves the mouse over the indicator.
3174 *
3175 * @return {string} Indicator title text
3176 */
3177 OO.ui.mixin.IndicatorElement.prototype.getIndicatorTitle = function () {
3178 return this.indicatorTitle;
3179 };
3180
3181 /**
3182 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
3183 * additional functionality to an element created by another class. The class provides
3184 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
3185 * which are used to customize the look and feel of a widget to better describe its
3186 * importance and functionality.
3187 *
3188 * The library currently contains the following styling flags for general use:
3189 *
3190 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
3191 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
3192 *
3193 * The flags affect the appearance of the buttons:
3194 *
3195 * @example
3196 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
3197 * var button1 = new OO.ui.ButtonWidget( {
3198 * label: 'Progressive',
3199 * flags: 'progressive'
3200 * } );
3201 * var button2 = new OO.ui.ButtonWidget( {
3202 * label: 'Destructive',
3203 * flags: 'destructive'
3204 * } );
3205 * $( 'body' ).append( button1.$element, button2.$element );
3206 *
3207 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
3208 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
3209 *
3210 * [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
3211 *
3212 * @abstract
3213 * @class
3214 *
3215 * @constructor
3216 * @param {Object} [config] Configuration options
3217 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'progressive' or 'primary') to apply.
3218 * Please see the [OOUI documentation on MediaWiki] [2] for more information about available flags.
3219 * [2]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
3220 * @cfg {jQuery} [$flagged] The flagged element. By default,
3221 * the flagged functionality is applied to the element created by the class ($element).
3222 * If a different element is specified, the flagged functionality will be applied to it instead.
3223 */
3224 OO.ui.mixin.FlaggedElement = function OoUiMixinFlaggedElement( config ) {
3225 // Configuration initialization
3226 config = config || {};
3227
3228 // Properties
3229 this.flags = {};
3230 this.$flagged = null;
3231
3232 // Initialization
3233 this.setFlags( config.flags );
3234 this.setFlaggedElement( config.$flagged || this.$element );
3235 };
3236
3237 /* Events */
3238
3239 /**
3240 * @event flag
3241 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
3242 * parameter contains the name of each modified flag and indicates whether it was
3243 * added or removed.
3244 *
3245 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
3246 * that the flag was added, `false` that the flag was removed.
3247 */
3248
3249 /* Methods */
3250
3251 /**
3252 * Set the flagged element.
3253 *
3254 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
3255 * If an element is already set, the method will remove the mixin’s effect on that element.
3256 *
3257 * @param {jQuery} $flagged Element that should be flagged
3258 */
3259 OO.ui.mixin.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
3260 var classNames = Object.keys( this.flags ).map( function ( flag ) {
3261 return 'oo-ui-flaggedElement-' + flag;
3262 } );
3263
3264 if ( this.$flagged ) {
3265 this.$flagged.removeClass( classNames );
3266 }
3267
3268 this.$flagged = $flagged.addClass( classNames );
3269 };
3270
3271 /**
3272 * Check if the specified flag is set.
3273 *
3274 * @param {string} flag Name of flag
3275 * @return {boolean} The flag is set
3276 */
3277 OO.ui.mixin.FlaggedElement.prototype.hasFlag = function ( flag ) {
3278 // This may be called before the constructor, thus before this.flags is set
3279 return this.flags && ( flag in this.flags );
3280 };
3281
3282 /**
3283 * Get the names of all flags set.
3284 *
3285 * @return {string[]} Flag names
3286 */
3287 OO.ui.mixin.FlaggedElement.prototype.getFlags = function () {
3288 // This may be called before the constructor, thus before this.flags is set
3289 return Object.keys( this.flags || {} );
3290 };
3291
3292 /**
3293 * Clear all flags.
3294 *
3295 * @chainable
3296 * @fires flag
3297 */
3298 OO.ui.mixin.FlaggedElement.prototype.clearFlags = function () {
3299 var flag, className,
3300 changes = {},
3301 remove = [],
3302 classPrefix = 'oo-ui-flaggedElement-';
3303
3304 for ( flag in this.flags ) {
3305 className = classPrefix + flag;
3306 changes[ flag ] = false;
3307 delete this.flags[ flag ];
3308 remove.push( className );
3309 }
3310
3311 if ( this.$flagged ) {
3312 this.$flagged.removeClass( remove );
3313 }
3314
3315 this.updateThemeClasses();
3316 this.emit( 'flag', changes );
3317
3318 return this;
3319 };
3320
3321 /**
3322 * Add one or more flags.
3323 *
3324 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
3325 * or an object keyed by flag name with a boolean value that indicates whether the flag should
3326 * be added (`true`) or removed (`false`).
3327 * @chainable
3328 * @fires flag
3329 */
3330 OO.ui.mixin.FlaggedElement.prototype.setFlags = function ( flags ) {
3331 var i, len, flag, className,
3332 changes = {},
3333 add = [],
3334 remove = [],
3335 classPrefix = 'oo-ui-flaggedElement-';
3336
3337 if ( typeof flags === 'string' ) {
3338 className = classPrefix + flags;
3339 // Set
3340 if ( !this.flags[ flags ] ) {
3341 this.flags[ flags ] = true;
3342 add.push( className );
3343 }
3344 } else if ( Array.isArray( flags ) ) {
3345 for ( i = 0, len = flags.length; i < len; i++ ) {
3346 flag = flags[ i ];
3347 className = classPrefix + flag;
3348 // Set
3349 if ( !this.flags[ flag ] ) {
3350 changes[ flag ] = true;
3351 this.flags[ flag ] = true;
3352 add.push( className );
3353 }
3354 }
3355 } else if ( OO.isPlainObject( flags ) ) {
3356 for ( flag in flags ) {
3357 className = classPrefix + flag;
3358 if ( flags[ flag ] ) {
3359 // Set
3360 if ( !this.flags[ flag ] ) {
3361 changes[ flag ] = true;
3362 this.flags[ flag ] = true;
3363 add.push( className );
3364 }
3365 } else {
3366 // Remove
3367 if ( this.flags[ flag ] ) {
3368 changes[ flag ] = false;
3369 delete this.flags[ flag ];
3370 remove.push( className );
3371 }
3372 }
3373 }
3374 }
3375
3376 if ( this.$flagged ) {
3377 this.$flagged
3378 .addClass( add )
3379 .removeClass( remove );
3380 }
3381
3382 this.updateThemeClasses();
3383 this.emit( 'flag', changes );
3384
3385 return this;
3386 };
3387
3388 /**
3389 * TitledElement is mixed into other classes to provide a `title` attribute.
3390 * Titles are rendered by the browser and are made visible when the user moves
3391 * the mouse over the element. Titles are not visible on touch devices.
3392 *
3393 * @example
3394 * // TitledElement provides a 'title' attribute to the
3395 * // ButtonWidget class
3396 * var button = new OO.ui.ButtonWidget( {
3397 * label: 'Button with Title',
3398 * title: 'I am a button'
3399 * } );
3400 * $( 'body' ).append( button.$element );
3401 *
3402 * @abstract
3403 * @class
3404 *
3405 * @constructor
3406 * @param {Object} [config] Configuration options
3407 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
3408 * If this config is omitted, the title functionality is applied to $element, the
3409 * element created by the class.
3410 * @cfg {string|Function} [title] The title text or a function that returns text. If
3411 * this config is omitted, the value of the {@link #static-title static title} property is used.
3412 */
3413 OO.ui.mixin.TitledElement = function OoUiMixinTitledElement( config ) {
3414 // Configuration initialization
3415 config = config || {};
3416
3417 // Properties
3418 this.$titled = null;
3419 this.title = null;
3420
3421 // Initialization
3422 this.setTitle( config.title !== undefined ? config.title : this.constructor.static.title );
3423 this.setTitledElement( config.$titled || this.$element );
3424 };
3425
3426 /* Setup */
3427
3428 OO.initClass( OO.ui.mixin.TitledElement );
3429
3430 /* Static Properties */
3431
3432 /**
3433 * The title text, a function that returns text, or `null` for no title. The value of the static property
3434 * is overridden if the #title config option is used.
3435 *
3436 * @static
3437 * @inheritable
3438 * @property {string|Function|null}
3439 */
3440 OO.ui.mixin.TitledElement.static.title = null;
3441
3442 /* Methods */
3443
3444 /**
3445 * Set the titled element.
3446 *
3447 * This method is used to retarget a TitledElement mixin so that its functionality applies to the specified element.
3448 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
3449 *
3450 * @param {jQuery} $titled Element that should use the 'titled' functionality
3451 */
3452 OO.ui.mixin.TitledElement.prototype.setTitledElement = function ( $titled ) {
3453 if ( this.$titled ) {
3454 this.$titled.removeAttr( 'title' );
3455 }
3456
3457 this.$titled = $titled;
3458 if ( this.title ) {
3459 this.updateTitle();
3460 }
3461 };
3462
3463 /**
3464 * Set title.
3465 *
3466 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
3467 * @chainable
3468 */
3469 OO.ui.mixin.TitledElement.prototype.setTitle = function ( title ) {
3470 title = typeof title === 'function' ? OO.ui.resolveMsg( title ) : title;
3471 title = ( typeof title === 'string' && title.length ) ? title : null;
3472
3473 if ( this.title !== title ) {
3474 this.title = title;
3475 this.updateTitle();
3476 }
3477
3478 return this;
3479 };
3480
3481 /**
3482 * Update the title attribute, in case of changes to title or accessKey.
3483 *
3484 * @protected
3485 * @chainable
3486 */
3487 OO.ui.mixin.TitledElement.prototype.updateTitle = function () {
3488 var title = this.getTitle();
3489 if ( this.$titled ) {
3490 if ( title !== null ) {
3491 // Only if this is an AccessKeyedElement
3492 if ( this.formatTitleWithAccessKey ) {
3493 title = this.formatTitleWithAccessKey( title );
3494 }
3495 this.$titled.attr( 'title', title );
3496 } else {
3497 this.$titled.removeAttr( 'title' );
3498 }
3499 }
3500 return this;
3501 };
3502
3503 /**
3504 * Get title.
3505 *
3506 * @return {string} Title string
3507 */
3508 OO.ui.mixin.TitledElement.prototype.getTitle = function () {
3509 return this.title;
3510 };
3511
3512 /**
3513 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
3514 * Accesskeys allow an user to go to a specific element by using
3515 * a shortcut combination of a browser specific keys + the key
3516 * set to the field.
3517 *
3518 * @example
3519 * // AccessKeyedElement provides an 'accesskey' attribute to the
3520 * // ButtonWidget class
3521 * var button = new OO.ui.ButtonWidget( {
3522 * label: 'Button with Accesskey',
3523 * accessKey: 'k'
3524 * } );
3525 * $( 'body' ).append( button.$element );
3526 *
3527 * @abstract
3528 * @class
3529 *
3530 * @constructor
3531 * @param {Object} [config] Configuration options
3532 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3533 * If this config is omitted, the accesskey functionality is applied to $element, the
3534 * element created by the class.
3535 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3536 * this config is omitted, no accesskey will be added.
3537 */
3538 OO.ui.mixin.AccessKeyedElement = function OoUiMixinAccessKeyedElement( config ) {
3539 // Configuration initialization
3540 config = config || {};
3541
3542 // Properties
3543 this.$accessKeyed = null;
3544 this.accessKey = null;
3545
3546 // Initialization
3547 this.setAccessKey( config.accessKey || null );
3548 this.setAccessKeyedElement( config.$accessKeyed || this.$element );
3549
3550 // If this is also a TitledElement and it initialized before we did, we may have
3551 // to update the title with the access key
3552 if ( this.updateTitle ) {
3553 this.updateTitle();
3554 }
3555 };
3556
3557 /* Setup */
3558
3559 OO.initClass( OO.ui.mixin.AccessKeyedElement );
3560
3561 /* Static Properties */
3562
3563 /**
3564 * The access key, a function that returns a key, or `null` for no accesskey.
3565 *
3566 * @static
3567 * @inheritable
3568 * @property {string|Function|null}
3569 */
3570 OO.ui.mixin.AccessKeyedElement.static.accessKey = null;
3571
3572 /* Methods */
3573
3574 /**
3575 * Set the accesskeyed element.
3576 *
3577 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
3578 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
3579 *
3580 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyed' functionality
3581 */
3582 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKeyedElement = function ( $accessKeyed ) {
3583 if ( this.$accessKeyed ) {
3584 this.$accessKeyed.removeAttr( 'accesskey' );
3585 }
3586
3587 this.$accessKeyed = $accessKeyed;
3588 if ( this.accessKey ) {
3589 this.$accessKeyed.attr( 'accesskey', this.accessKey );
3590 }
3591 };
3592
3593 /**
3594 * Set accesskey.
3595 *
3596 * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no accesskey
3597 * @chainable
3598 */
3599 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKey = function ( accessKey ) {
3600 accessKey = typeof accessKey === 'string' ? OO.ui.resolveMsg( accessKey ) : null;
3601
3602 if ( this.accessKey !== accessKey ) {
3603 if ( this.$accessKeyed ) {
3604 if ( accessKey !== null ) {
3605 this.$accessKeyed.attr( 'accesskey', accessKey );
3606 } else {
3607 this.$accessKeyed.removeAttr( 'accesskey' );
3608 }
3609 }
3610 this.accessKey = accessKey;
3611
3612 // Only if this is a TitledElement
3613 if ( this.updateTitle ) {
3614 this.updateTitle();
3615 }
3616 }
3617
3618 return this;
3619 };
3620
3621 /**
3622 * Get accesskey.
3623 *
3624 * @return {string} accessKey string
3625 */
3626 OO.ui.mixin.AccessKeyedElement.prototype.getAccessKey = function () {
3627 return this.accessKey;
3628 };
3629
3630 /**
3631 * Add information about the access key to the element's tooltip label.
3632 * (This is only public for hacky usage in FieldLayout.)
3633 *
3634 * @param {string} title Tooltip label for `title` attribute
3635 * @return {string}
3636 */
3637 OO.ui.mixin.AccessKeyedElement.prototype.formatTitleWithAccessKey = function ( title ) {
3638 var accessKey;
3639
3640 if ( !this.$accessKeyed ) {
3641 // Not initialized yet; the constructor will call updateTitle() which will rerun this function
3642 return title;
3643 }
3644 // Use jquery.accessKeyLabel if available to show modifiers, otherwise just display the single key
3645 if ( $.fn.updateTooltipAccessKeys && $.fn.updateTooltipAccessKeys.getAccessKeyLabel ) {
3646 accessKey = $.fn.updateTooltipAccessKeys.getAccessKeyLabel( this.$accessKeyed[ 0 ] );
3647 } else {
3648 accessKey = this.getAccessKey();
3649 }
3650 if ( accessKey ) {
3651 title += ' [' + accessKey + ']';
3652 }
3653 return title;
3654 };
3655
3656 /**
3657 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3658 * feels, and functionality can be customized via the class’s configuration options
3659 * and methods. Please see the [OOUI documentation on MediaWiki] [1] for more information
3660 * and examples.
3661 *
3662 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches
3663 *
3664 * @example
3665 * // A button widget
3666 * var button = new OO.ui.ButtonWidget( {
3667 * label: 'Button with Icon',
3668 * icon: 'trash',
3669 * title: 'Remove'
3670 * } );
3671 * $( 'body' ).append( button.$element );
3672 *
3673 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3674 *
3675 * @class
3676 * @extends OO.ui.Widget
3677 * @mixins OO.ui.mixin.ButtonElement
3678 * @mixins OO.ui.mixin.IconElement
3679 * @mixins OO.ui.mixin.IndicatorElement
3680 * @mixins OO.ui.mixin.LabelElement
3681 * @mixins OO.ui.mixin.TitledElement
3682 * @mixins OO.ui.mixin.FlaggedElement
3683 * @mixins OO.ui.mixin.TabIndexedElement
3684 * @mixins OO.ui.mixin.AccessKeyedElement
3685 *
3686 * @constructor
3687 * @param {Object} [config] Configuration options
3688 * @cfg {boolean} [active=false] Whether button should be shown as active
3689 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3690 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3691 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3692 */
3693 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
3694 // Configuration initialization
3695 config = config || {};
3696
3697 // Parent constructor
3698 OO.ui.ButtonWidget.parent.call( this, config );
3699
3700 // Mixin constructors
3701 OO.ui.mixin.ButtonElement.call( this, config );
3702 OO.ui.mixin.IconElement.call( this, config );
3703 OO.ui.mixin.IndicatorElement.call( this, config );
3704 OO.ui.mixin.LabelElement.call( this, config );
3705 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
3706 OO.ui.mixin.FlaggedElement.call( this, config );
3707 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
3708 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$button } ) );
3709
3710 // Properties
3711 this.href = null;
3712 this.target = null;
3713 this.noFollow = false;
3714
3715 // Events
3716 this.connect( this, { disable: 'onDisable' } );
3717
3718 // Initialization
3719 this.$button.append( this.$icon, this.$label, this.$indicator );
3720 this.$element
3721 .addClass( 'oo-ui-buttonWidget' )
3722 .append( this.$button );
3723 this.setActive( config.active );
3724 this.setHref( config.href );
3725 this.setTarget( config.target );
3726 this.setNoFollow( config.noFollow );
3727 };
3728
3729 /* Setup */
3730
3731 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
3732 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.ButtonElement );
3733 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IconElement );
3734 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IndicatorElement );
3735 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.LabelElement );
3736 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TitledElement );
3737 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.FlaggedElement );
3738 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TabIndexedElement );
3739 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.AccessKeyedElement );
3740
3741 /* Static Properties */
3742
3743 /**
3744 * @static
3745 * @inheritdoc
3746 */
3747 OO.ui.ButtonWidget.static.cancelButtonMouseDownEvents = false;
3748
3749 /**
3750 * @static
3751 * @inheritdoc
3752 */
3753 OO.ui.ButtonWidget.static.tagName = 'span';
3754
3755 /* Methods */
3756
3757 /**
3758 * Get hyperlink location.
3759 *
3760 * @return {string} Hyperlink location
3761 */
3762 OO.ui.ButtonWidget.prototype.getHref = function () {
3763 return this.href;
3764 };
3765
3766 /**
3767 * Get hyperlink target.
3768 *
3769 * @return {string} Hyperlink target
3770 */
3771 OO.ui.ButtonWidget.prototype.getTarget = function () {
3772 return this.target;
3773 };
3774
3775 /**
3776 * Get search engine traversal hint.
3777 *
3778 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3779 */
3780 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
3781 return this.noFollow;
3782 };
3783
3784 /**
3785 * Set hyperlink location.
3786 *
3787 * @param {string|null} href Hyperlink location, null to remove
3788 */
3789 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
3790 href = typeof href === 'string' ? href : null;
3791 if ( href !== null && !OO.ui.isSafeUrl( href ) ) {
3792 href = './' + href;
3793 }
3794
3795 if ( href !== this.href ) {
3796 this.href = href;
3797 this.updateHref();
3798 }
3799
3800 return this;
3801 };
3802
3803 /**
3804 * Update the `href` attribute, in case of changes to href or
3805 * disabled state.
3806 *
3807 * @private
3808 * @chainable
3809 */
3810 OO.ui.ButtonWidget.prototype.updateHref = function () {
3811 if ( this.href !== null && !this.isDisabled() ) {
3812 this.$button.attr( 'href', this.href );
3813 } else {
3814 this.$button.removeAttr( 'href' );
3815 }
3816
3817 return this;
3818 };
3819
3820 /**
3821 * Handle disable events.
3822 *
3823 * @private
3824 * @param {boolean} disabled Element is disabled
3825 */
3826 OO.ui.ButtonWidget.prototype.onDisable = function () {
3827 this.updateHref();
3828 };
3829
3830 /**
3831 * Set hyperlink target.
3832 *
3833 * @param {string|null} target Hyperlink target, null to remove
3834 */
3835 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
3836 target = typeof target === 'string' ? target : null;
3837
3838 if ( target !== this.target ) {
3839 this.target = target;
3840 if ( target !== null ) {
3841 this.$button.attr( 'target', target );
3842 } else {
3843 this.$button.removeAttr( 'target' );
3844 }
3845 }
3846
3847 return this;
3848 };
3849
3850 /**
3851 * Set search engine traversal hint.
3852 *
3853 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3854 */
3855 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
3856 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
3857
3858 if ( noFollow !== this.noFollow ) {
3859 this.noFollow = noFollow;
3860 if ( noFollow ) {
3861 this.$button.attr( 'rel', 'nofollow' );
3862 } else {
3863 this.$button.removeAttr( 'rel' );
3864 }
3865 }
3866
3867 return this;
3868 };
3869
3870 // Override method visibility hints from ButtonElement
3871 /**
3872 * @method setActive
3873 * @inheritdoc
3874 */
3875 /**
3876 * @method isActive
3877 * @inheritdoc
3878 */
3879
3880 /**
3881 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3882 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3883 * removed, and cleared from the group.
3884 *
3885 * @example
3886 * // Example: A ButtonGroupWidget with two buttons
3887 * var button1 = new OO.ui.PopupButtonWidget( {
3888 * label: 'Select a category',
3889 * icon: 'menu',
3890 * popup: {
3891 * $content: $( '<p>List of categories...</p>' ),
3892 * padded: true,
3893 * align: 'left'
3894 * }
3895 * } );
3896 * var button2 = new OO.ui.ButtonWidget( {
3897 * label: 'Add item'
3898 * });
3899 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
3900 * items: [button1, button2]
3901 * } );
3902 * $( 'body' ).append( buttonGroup.$element );
3903 *
3904 * @class
3905 * @extends OO.ui.Widget
3906 * @mixins OO.ui.mixin.GroupElement
3907 *
3908 * @constructor
3909 * @param {Object} [config] Configuration options
3910 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
3911 */
3912 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
3913 // Configuration initialization
3914 config = config || {};
3915
3916 // Parent constructor
3917 OO.ui.ButtonGroupWidget.parent.call( this, config );
3918
3919 // Mixin constructors
3920 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
3921
3922 // Initialization
3923 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
3924 if ( Array.isArray( config.items ) ) {
3925 this.addItems( config.items );
3926 }
3927 };
3928
3929 /* Setup */
3930
3931 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
3932 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.GroupElement );
3933
3934 /* Static Properties */
3935
3936 /**
3937 * @static
3938 * @inheritdoc
3939 */
3940 OO.ui.ButtonGroupWidget.static.tagName = 'span';
3941
3942 /* Methods */
3943
3944 /**
3945 * Focus the widget
3946 *
3947 * @chainable
3948 */
3949 OO.ui.ButtonGroupWidget.prototype.focus = function () {
3950 if ( !this.isDisabled() ) {
3951 if ( this.items[ 0 ] ) {
3952 this.items[ 0 ].focus();
3953 }
3954 }
3955 return this;
3956 };
3957
3958 /**
3959 * @inheritdoc
3960 */
3961 OO.ui.ButtonGroupWidget.prototype.simulateLabelClick = function () {
3962 this.focus();
3963 };
3964
3965 /**
3966 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
3967 * which creates a label that identifies the icon’s function. See the [OOUI documentation on MediaWiki] [1]
3968 * for a list of icons included in the library.
3969 *
3970 * @example
3971 * // An icon widget with a label
3972 * var myIcon = new OO.ui.IconWidget( {
3973 * icon: 'help',
3974 * title: 'Help'
3975 * } );
3976 * // Create a label.
3977 * var iconLabel = new OO.ui.LabelWidget( {
3978 * label: 'Help'
3979 * } );
3980 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
3981 *
3982 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
3983 *
3984 * @class
3985 * @extends OO.ui.Widget
3986 * @mixins OO.ui.mixin.IconElement
3987 * @mixins OO.ui.mixin.TitledElement
3988 * @mixins OO.ui.mixin.LabelElement
3989 * @mixins OO.ui.mixin.FlaggedElement
3990 *
3991 * @constructor
3992 * @param {Object} [config] Configuration options
3993 */
3994 OO.ui.IconWidget = function OoUiIconWidget( config ) {
3995 // Configuration initialization
3996 config = config || {};
3997
3998 // Parent constructor
3999 OO.ui.IconWidget.parent.call( this, config );
4000
4001 // Mixin constructors
4002 OO.ui.mixin.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
4003 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
4004 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element, invisibleLabel: true } ) );
4005 OO.ui.mixin.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) );
4006
4007 // Initialization
4008 this.$element.addClass( 'oo-ui-iconWidget' );
4009 // Remove class added by LabelElement initialization. It causes unexpected CSS to apply when
4010 // nested in other widgets, because this widget used to not mix in LabelElement.
4011 this.$element.removeClass( 'oo-ui-labelElement-label' );
4012 };
4013
4014 /* Setup */
4015
4016 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
4017 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.IconElement );
4018 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.TitledElement );
4019 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.LabelElement );
4020 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.FlaggedElement );
4021
4022 /* Static Properties */
4023
4024 /**
4025 * @static
4026 * @inheritdoc
4027 */
4028 OO.ui.IconWidget.static.tagName = 'span';
4029
4030 /**
4031 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
4032 * attention to the status of an item or to clarify the function within a control. For a list of
4033 * indicators included in the library, please see the [OOUI documentation on MediaWiki][1].
4034 *
4035 * @example
4036 * // Example of an indicator widget
4037 * var indicator1 = new OO.ui.IndicatorWidget( {
4038 * indicator: 'required'
4039 * } );
4040 *
4041 * // Create a fieldset layout to add a label
4042 * var fieldset = new OO.ui.FieldsetLayout();
4043 * fieldset.addItems( [
4044 * new OO.ui.FieldLayout( indicator1, { label: 'A required indicator:' } )
4045 * ] );
4046 * $( 'body' ).append( fieldset.$element );
4047 *
4048 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
4049 *
4050 * @class
4051 * @extends OO.ui.Widget
4052 * @mixins OO.ui.mixin.IndicatorElement
4053 * @mixins OO.ui.mixin.TitledElement
4054 * @mixins OO.ui.mixin.LabelElement
4055 *
4056 * @constructor
4057 * @param {Object} [config] Configuration options
4058 */
4059 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
4060 // Configuration initialization
4061 config = config || {};
4062
4063 // Parent constructor
4064 OO.ui.IndicatorWidget.parent.call( this, config );
4065
4066 // Mixin constructors
4067 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
4068 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
4069 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element, invisibleLabel: true } ) );
4070
4071 // Initialization
4072 this.$element.addClass( 'oo-ui-indicatorWidget' );
4073 // Remove class added by LabelElement initialization. It causes unexpected CSS to apply when
4074 // nested in other widgets, because this widget used to not mix in LabelElement.
4075 this.$element.removeClass( 'oo-ui-labelElement-label' );
4076 };
4077
4078 /* Setup */
4079
4080 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
4081 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.IndicatorElement );
4082 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.TitledElement );
4083 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.LabelElement );
4084
4085 /* Static Properties */
4086
4087 /**
4088 * @static
4089 * @inheritdoc
4090 */
4091 OO.ui.IndicatorWidget.static.tagName = 'span';
4092
4093 /**
4094 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
4095 * be configured with a `label` option that is set to a string, a label node, or a function:
4096 *
4097 * - String: a plaintext string
4098 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
4099 * label that includes a link or special styling, such as a gray color or additional graphical elements.
4100 * - Function: a function that will produce a string in the future. Functions are used
4101 * in cases where the value of the label is not currently defined.
4102 *
4103 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
4104 * will come into focus when the label is clicked.
4105 *
4106 * @example
4107 * // Examples of LabelWidgets
4108 * var label1 = new OO.ui.LabelWidget( {
4109 * label: 'plaintext label'
4110 * } );
4111 * var label2 = new OO.ui.LabelWidget( {
4112 * label: $( '<a href="default.html">jQuery label</a>' )
4113 * } );
4114 * // Create a fieldset layout with fields for each example
4115 * var fieldset = new OO.ui.FieldsetLayout();
4116 * fieldset.addItems( [
4117 * new OO.ui.FieldLayout( label1 ),
4118 * new OO.ui.FieldLayout( label2 )
4119 * ] );
4120 * $( 'body' ).append( fieldset.$element );
4121 *
4122 * @class
4123 * @extends OO.ui.Widget
4124 * @mixins OO.ui.mixin.LabelElement
4125 * @mixins OO.ui.mixin.TitledElement
4126 *
4127 * @constructor
4128 * @param {Object} [config] Configuration options
4129 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
4130 * Clicking the label will focus the specified input field.
4131 */
4132 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
4133 // Configuration initialization
4134 config = config || {};
4135
4136 // Parent constructor
4137 OO.ui.LabelWidget.parent.call( this, config );
4138
4139 // Mixin constructors
4140 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
4141 OO.ui.mixin.TitledElement.call( this, config );
4142
4143 // Properties
4144 this.input = config.input;
4145
4146 // Initialization
4147 if ( this.input ) {
4148 if ( this.input.getInputId() ) {
4149 this.$element.attr( 'for', this.input.getInputId() );
4150 } else {
4151 this.$label.on( 'click', function () {
4152 this.input.simulateLabelClick();
4153 }.bind( this ) );
4154 }
4155 }
4156 this.$element.addClass( 'oo-ui-labelWidget' );
4157 };
4158
4159 /* Setup */
4160
4161 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
4162 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.LabelElement );
4163 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.TitledElement );
4164
4165 /* Static Properties */
4166
4167 /**
4168 * @static
4169 * @inheritdoc
4170 */
4171 OO.ui.LabelWidget.static.tagName = 'label';
4172
4173 /**
4174 * PendingElement is a mixin that is used to create elements that notify users that something is happening
4175 * and that they should wait before proceeding. The pending state is visually represented with a pending
4176 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
4177 * field of a {@link OO.ui.TextInputWidget text input widget}.
4178 *
4179 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
4180 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
4181 * in process dialogs.
4182 *
4183 * @example
4184 * function MessageDialog( config ) {
4185 * MessageDialog.parent.call( this, config );
4186 * }
4187 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
4188 *
4189 * MessageDialog.static.name = 'myMessageDialog';
4190 * MessageDialog.static.actions = [
4191 * { action: 'save', label: 'Done', flags: 'primary' },
4192 * { label: 'Cancel', flags: 'safe' }
4193 * ];
4194 *
4195 * MessageDialog.prototype.initialize = function () {
4196 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
4197 * this.content = new OO.ui.PanelLayout( { padded: true } );
4198 * 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>' );
4199 * this.$body.append( this.content.$element );
4200 * };
4201 * MessageDialog.prototype.getBodyHeight = function () {
4202 * return 100;
4203 * }
4204 * MessageDialog.prototype.getActionProcess = function ( action ) {
4205 * var dialog = this;
4206 * if ( action === 'save' ) {
4207 * dialog.getActions().get({actions: 'save'})[0].pushPending();
4208 * return new OO.ui.Process()
4209 * .next( 1000 )
4210 * .next( function () {
4211 * dialog.getActions().get({actions: 'save'})[0].popPending();
4212 * } );
4213 * }
4214 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
4215 * };
4216 *
4217 * var windowManager = new OO.ui.WindowManager();
4218 * $( 'body' ).append( windowManager.$element );
4219 *
4220 * var dialog = new MessageDialog();
4221 * windowManager.addWindows( [ dialog ] );
4222 * windowManager.openWindow( dialog );
4223 *
4224 * @abstract
4225 * @class
4226 *
4227 * @constructor
4228 * @param {Object} [config] Configuration options
4229 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
4230 */
4231 OO.ui.mixin.PendingElement = function OoUiMixinPendingElement( config ) {
4232 // Configuration initialization
4233 config = config || {};
4234
4235 // Properties
4236 this.pending = 0;
4237 this.$pending = null;
4238
4239 // Initialisation
4240 this.setPendingElement( config.$pending || this.$element );
4241 };
4242
4243 /* Setup */
4244
4245 OO.initClass( OO.ui.mixin.PendingElement );
4246
4247 /* Methods */
4248
4249 /**
4250 * Set the pending element (and clean up any existing one).
4251 *
4252 * @param {jQuery} $pending The element to set to pending.
4253 */
4254 OO.ui.mixin.PendingElement.prototype.setPendingElement = function ( $pending ) {
4255 if ( this.$pending ) {
4256 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
4257 }
4258
4259 this.$pending = $pending;
4260 if ( this.pending > 0 ) {
4261 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
4262 }
4263 };
4264
4265 /**
4266 * Check if an element is pending.
4267 *
4268 * @return {boolean} Element is pending
4269 */
4270 OO.ui.mixin.PendingElement.prototype.isPending = function () {
4271 return !!this.pending;
4272 };
4273
4274 /**
4275 * Increase the pending counter. The pending state will remain active until the counter is zero
4276 * (i.e., the number of calls to #pushPending and #popPending is the same).
4277 *
4278 * @chainable
4279 */
4280 OO.ui.mixin.PendingElement.prototype.pushPending = function () {
4281 if ( this.pending === 0 ) {
4282 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
4283 this.updateThemeClasses();
4284 }
4285 this.pending++;
4286
4287 return this;
4288 };
4289
4290 /**
4291 * Decrease the pending counter. The pending state will remain active until the counter is zero
4292 * (i.e., the number of calls to #pushPending and #popPending is the same).
4293 *
4294 * @chainable
4295 */
4296 OO.ui.mixin.PendingElement.prototype.popPending = function () {
4297 if ( this.pending === 1 ) {
4298 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
4299 this.updateThemeClasses();
4300 }
4301 this.pending = Math.max( 0, this.pending - 1 );
4302
4303 return this;
4304 };
4305
4306 /**
4307 * Element that will stick adjacent to a specified container, even when it is inserted elsewhere
4308 * in the document (for example, in an OO.ui.Window's $overlay).
4309 *
4310 * The elements's position is automatically calculated and maintained when window is resized or the
4311 * page is scrolled. If you reposition the container manually, you have to call #position to make
4312 * sure the element is still placed correctly.
4313 *
4314 * As positioning is only possible when both the element and the container are attached to the DOM
4315 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
4316 * the #toggle method to display a floating popup, for example.
4317 *
4318 * @abstract
4319 * @class
4320 *
4321 * @constructor
4322 * @param {Object} [config] Configuration options
4323 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
4324 * @cfg {jQuery} [$floatableContainer] Node to position adjacent to
4325 * @cfg {string} [verticalPosition='below'] Where to position $floatable vertically:
4326 * 'below': Directly below $floatableContainer, aligning f's top edge with fC's bottom edge
4327 * 'above': Directly above $floatableContainer, aligning f's bottom edge with fC's top edge
4328 * 'top': Align the top edge with $floatableContainer's top edge
4329 * 'bottom': Align the bottom edge with $floatableContainer's bottom edge
4330 * 'center': Vertically align the center with $floatableContainer's center
4331 * @cfg {string} [horizontalPosition='start'] Where to position $floatable horizontally:
4332 * 'before': Directly before $floatableContainer, aligning f's end edge with fC's start edge
4333 * 'after': Directly after $floatableContainer, aligning f's start edge with fC's end edge
4334 * 'start': Align the start (left in LTR, right in RTL) edge with $floatableContainer's start edge
4335 * 'end': Align the end (right in LTR, left in RTL) edge with $floatableContainer's end edge
4336 * 'center': Horizontally align the center with $floatableContainer's center
4337 * @cfg {boolean} [hideWhenOutOfView=true] Whether to hide the floatable element if the container
4338 * is out of view
4339 */
4340 OO.ui.mixin.FloatableElement = function OoUiMixinFloatableElement( config ) {
4341 // Configuration initialization
4342 config = config || {};
4343
4344 // Properties
4345 this.$floatable = null;
4346 this.$floatableContainer = null;
4347 this.$floatableWindow = null;
4348 this.$floatableClosestScrollable = null;
4349 this.floatableOutOfView = false;
4350 this.onFloatableScrollHandler = this.position.bind( this );
4351 this.onFloatableWindowResizeHandler = this.position.bind( this );
4352
4353 // Initialization
4354 this.setFloatableContainer( config.$floatableContainer );
4355 this.setFloatableElement( config.$floatable || this.$element );
4356 this.setVerticalPosition( config.verticalPosition || 'below' );
4357 this.setHorizontalPosition( config.horizontalPosition || 'start' );
4358 this.hideWhenOutOfView = config.hideWhenOutOfView === undefined ? true : !!config.hideWhenOutOfView;
4359 };
4360
4361 /* Methods */
4362
4363 /**
4364 * Set floatable element.
4365 *
4366 * If an element is already set, it will be cleaned up before setting up the new element.
4367 *
4368 * @param {jQuery} $floatable Element to make floatable
4369 */
4370 OO.ui.mixin.FloatableElement.prototype.setFloatableElement = function ( $floatable ) {
4371 if ( this.$floatable ) {
4372 this.$floatable.removeClass( 'oo-ui-floatableElement-floatable' );
4373 this.$floatable.css( { left: '', top: '' } );
4374 }
4375
4376 this.$floatable = $floatable.addClass( 'oo-ui-floatableElement-floatable' );
4377 this.position();
4378 };
4379
4380 /**
4381 * Set floatable container.
4382 *
4383 * The element will be positioned relative to the specified container.
4384 *
4385 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
4386 */
4387 OO.ui.mixin.FloatableElement.prototype.setFloatableContainer = function ( $floatableContainer ) {
4388 this.$floatableContainer = $floatableContainer;
4389 if ( this.$floatable ) {
4390 this.position();
4391 }
4392 };
4393
4394 /**
4395 * Change how the element is positioned vertically.
4396 *
4397 * @param {string} position 'below', 'above', 'top', 'bottom' or 'center'
4398 */
4399 OO.ui.mixin.FloatableElement.prototype.setVerticalPosition = function ( position ) {
4400 if ( [ 'below', 'above', 'top', 'bottom', 'center' ].indexOf( position ) === -1 ) {
4401 throw new Error( 'Invalid value for vertical position: ' + position );
4402 }
4403 if ( this.verticalPosition !== position ) {
4404 this.verticalPosition = position;
4405 if ( this.$floatable ) {
4406 this.position();
4407 }
4408 }
4409 };
4410
4411 /**
4412 * Change how the element is positioned horizontally.
4413 *
4414 * @param {string} position 'before', 'after', 'start', 'end' or 'center'
4415 */
4416 OO.ui.mixin.FloatableElement.prototype.setHorizontalPosition = function ( position ) {
4417 if ( [ 'before', 'after', 'start', 'end', 'center' ].indexOf( position ) === -1 ) {
4418 throw new Error( 'Invalid value for horizontal position: ' + position );
4419 }
4420 if ( this.horizontalPosition !== position ) {
4421 this.horizontalPosition = position;
4422 if ( this.$floatable ) {
4423 this.position();
4424 }
4425 }
4426 };
4427
4428 /**
4429 * Toggle positioning.
4430 *
4431 * Do not turn positioning on until after the element is attached to the DOM and visible.
4432 *
4433 * @param {boolean} [positioning] Enable positioning, omit to toggle
4434 * @chainable
4435 */
4436 OO.ui.mixin.FloatableElement.prototype.togglePositioning = function ( positioning ) {
4437 var closestScrollableOfContainer;
4438
4439 if ( !this.$floatable || !this.$floatableContainer ) {
4440 return this;
4441 }
4442
4443 positioning = positioning === undefined ? !this.positioning : !!positioning;
4444
4445 if ( positioning && !this.warnedUnattached && !this.isElementAttached() ) {
4446 OO.ui.warnDeprecation( 'FloatableElement#togglePositioning: Before calling this method, the element must be attached to the DOM.' );
4447 this.warnedUnattached = true;
4448 }
4449
4450 if ( this.positioning !== positioning ) {
4451 this.positioning = positioning;
4452
4453 this.needsCustomPosition =
4454 this.verticalPosition !== 'below' ||
4455 this.horizontalPosition !== 'start' ||
4456 !OO.ui.contains( this.$floatableContainer[ 0 ], this.$floatable[ 0 ] );
4457
4458 closestScrollableOfContainer = OO.ui.Element.static.getClosestScrollableContainer( this.$floatableContainer[ 0 ] );
4459 // If the scrollable is the root, we have to listen to scroll events
4460 // on the window because of browser inconsistencies.
4461 if ( $( closestScrollableOfContainer ).is( 'html, body' ) ) {
4462 closestScrollableOfContainer = OO.ui.Element.static.getWindow( closestScrollableOfContainer );
4463 }
4464
4465 if ( positioning ) {
4466 this.$floatableWindow = $( this.getElementWindow() );
4467 this.$floatableWindow.on( 'resize', this.onFloatableWindowResizeHandler );
4468
4469 this.$floatableClosestScrollable = $( closestScrollableOfContainer );
4470 this.$floatableClosestScrollable.on( 'scroll', this.onFloatableScrollHandler );
4471
4472 // Initial position after visible
4473 this.position();
4474 } else {
4475 if ( this.$floatableWindow ) {
4476 this.$floatableWindow.off( 'resize', this.onFloatableWindowResizeHandler );
4477 this.$floatableWindow = null;
4478 }
4479
4480 if ( this.$floatableClosestScrollable ) {
4481 this.$floatableClosestScrollable.off( 'scroll', this.onFloatableScrollHandler );
4482 this.$floatableClosestScrollable = null;
4483 }
4484
4485 this.$floatable.css( { left: '', right: '', top: '' } );
4486 }
4487 }
4488
4489 return this;
4490 };
4491
4492 /**
4493 * Check whether the bottom edge of the given element is within the viewport of the given container.
4494 *
4495 * @private
4496 * @param {jQuery} $element
4497 * @param {jQuery} $container
4498 * @return {boolean}
4499 */
4500 OO.ui.mixin.FloatableElement.prototype.isElementInViewport = function ( $element, $container ) {
4501 var elemRect, contRect, topEdgeInBounds, bottomEdgeInBounds, leftEdgeInBounds, rightEdgeInBounds,
4502 startEdgeInBounds, endEdgeInBounds, viewportSpacing,
4503 direction = $element.css( 'direction' );
4504
4505 elemRect = $element[ 0 ].getBoundingClientRect();
4506 if ( $container[ 0 ] === window ) {
4507 viewportSpacing = OO.ui.getViewportSpacing();
4508 contRect = {
4509 top: 0,
4510 left: 0,
4511 right: document.documentElement.clientWidth,
4512 bottom: document.documentElement.clientHeight
4513 };
4514 contRect.top += viewportSpacing.top;
4515 contRect.left += viewportSpacing.left;
4516 contRect.right -= viewportSpacing.right;
4517 contRect.bottom -= viewportSpacing.bottom;
4518 } else {
4519 contRect = $container[ 0 ].getBoundingClientRect();
4520 }
4521
4522 topEdgeInBounds = elemRect.top >= contRect.top && elemRect.top <= contRect.bottom;
4523 bottomEdgeInBounds = elemRect.bottom >= contRect.top && elemRect.bottom <= contRect.bottom;
4524 leftEdgeInBounds = elemRect.left >= contRect.left && elemRect.left <= contRect.right;
4525 rightEdgeInBounds = elemRect.right >= contRect.left && elemRect.right <= contRect.right;
4526 if ( direction === 'rtl' ) {
4527 startEdgeInBounds = rightEdgeInBounds;
4528 endEdgeInBounds = leftEdgeInBounds;
4529 } else {
4530 startEdgeInBounds = leftEdgeInBounds;
4531 endEdgeInBounds = rightEdgeInBounds;
4532 }
4533
4534 if ( this.verticalPosition === 'below' && !bottomEdgeInBounds ) {
4535 return false;
4536 }
4537 if ( this.verticalPosition === 'above' && !topEdgeInBounds ) {
4538 return false;
4539 }
4540 if ( this.horizontalPosition === 'before' && !startEdgeInBounds ) {
4541 return false;
4542 }
4543 if ( this.horizontalPosition === 'after' && !endEdgeInBounds ) {
4544 return false;
4545 }
4546
4547 // The other positioning values are all about being inside the container,
4548 // so in those cases all we care about is that any part of the container is visible.
4549 return elemRect.top <= contRect.bottom && elemRect.bottom >= contRect.top &&
4550 elemRect.left <= contRect.right && elemRect.right >= contRect.left;
4551 };
4552
4553 /**
4554 * Check if the floatable is hidden to the user because it was offscreen.
4555 *
4556 * @return {boolean} Floatable is out of view
4557 */
4558 OO.ui.mixin.FloatableElement.prototype.isFloatableOutOfView = function () {
4559 return this.floatableOutOfView;
4560 };
4561
4562 /**
4563 * Position the floatable below its container.
4564 *
4565 * This should only be done when both of them are attached to the DOM and visible.
4566 *
4567 * @chainable
4568 */
4569 OO.ui.mixin.FloatableElement.prototype.position = function () {
4570 if ( !this.positioning ) {
4571 return this;
4572 }
4573
4574 if ( !(
4575 // To continue, some things need to be true:
4576 // The element must actually be in the DOM
4577 this.isElementAttached() && (
4578 // The closest scrollable is the current window
4579 this.$floatableClosestScrollable[ 0 ] === this.getElementWindow() ||
4580 // OR is an element in the element's DOM
4581 $.contains( this.getElementDocument(), this.$floatableClosestScrollable[ 0 ] )
4582 )
4583 ) ) {
4584 // Abort early if important parts of the widget are no longer attached to the DOM
4585 return this;
4586 }
4587
4588 this.floatableOutOfView = this.hideWhenOutOfView && !this.isElementInViewport( this.$floatableContainer, this.$floatableClosestScrollable );
4589 if ( this.floatableOutOfView ) {
4590 this.$floatable.addClass( 'oo-ui-element-hidden' );
4591 return this;
4592 } else {
4593 this.$floatable.removeClass( 'oo-ui-element-hidden' );
4594 }
4595
4596 if ( !this.needsCustomPosition ) {
4597 return this;
4598 }
4599
4600 this.$floatable.css( this.computePosition() );
4601
4602 // We updated the position, so re-evaluate the clipping state.
4603 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
4604 // will not notice the need to update itself.)
4605 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
4606 // it not listen to the right events in the right places?
4607 if ( this.clip ) {
4608 this.clip();
4609 }
4610
4611 return this;
4612 };
4613
4614 /**
4615 * Compute how #$floatable should be positioned based on the position of #$floatableContainer
4616 * and the positioning settings. This is a helper for #position that shouldn't be called directly,
4617 * but may be overridden by subclasses if they want to change or add to the positioning logic.
4618 *
4619 * @return {Object} New position to apply with .css(). Keys are 'top', 'left', 'bottom' and 'right'.
4620 */
4621 OO.ui.mixin.FloatableElement.prototype.computePosition = function () {
4622 var isBody, scrollableX, scrollableY, containerPos,
4623 horizScrollbarHeight, vertScrollbarWidth, scrollTop, scrollLeft,
4624 newPos = { top: '', left: '', bottom: '', right: '' },
4625 direction = this.$floatableContainer.css( 'direction' ),
4626 $offsetParent = this.$floatable.offsetParent();
4627
4628 if ( $offsetParent.is( 'html' ) ) {
4629 // The innerHeight/Width and clientHeight/Width calculations don't work well on the
4630 // <html> element, but they do work on the <body>
4631 $offsetParent = $( $offsetParent[ 0 ].ownerDocument.body );
4632 }
4633 isBody = $offsetParent.is( 'body' );
4634 scrollableX = $offsetParent.css( 'overflow-x' ) === 'scroll' || $offsetParent.css( 'overflow-x' ) === 'auto';
4635 scrollableY = $offsetParent.css( 'overflow-y' ) === 'scroll' || $offsetParent.css( 'overflow-y' ) === 'auto';
4636
4637 vertScrollbarWidth = $offsetParent.innerWidth() - $offsetParent.prop( 'clientWidth' );
4638 horizScrollbarHeight = $offsetParent.innerHeight() - $offsetParent.prop( 'clientHeight' );
4639 // We don't need to compute and add scrollTop and scrollLeft if the scrollable container is the body,
4640 // or if it isn't scrollable
4641 scrollTop = scrollableY && !isBody ? $offsetParent.scrollTop() : 0;
4642 scrollLeft = scrollableX && !isBody ? OO.ui.Element.static.getScrollLeft( $offsetParent[ 0 ] ) : 0;
4643
4644 // Avoid passing the <body> to getRelativePosition(), because it won't return what we expect
4645 // if the <body> has a margin
4646 containerPos = isBody ?
4647 this.$floatableContainer.offset() :
4648 OO.ui.Element.static.getRelativePosition( this.$floatableContainer, $offsetParent );
4649 containerPos.bottom = containerPos.top + this.$floatableContainer.outerHeight();
4650 containerPos.right = containerPos.left + this.$floatableContainer.outerWidth();
4651 containerPos.start = direction === 'rtl' ? containerPos.right : containerPos.left;
4652 containerPos.end = direction === 'rtl' ? containerPos.left : containerPos.right;
4653
4654 if ( this.verticalPosition === 'below' ) {
4655 newPos.top = containerPos.bottom;
4656 } else if ( this.verticalPosition === 'above' ) {
4657 newPos.bottom = $offsetParent.outerHeight() - containerPos.top;
4658 } else if ( this.verticalPosition === 'top' ) {
4659 newPos.top = containerPos.top;
4660 } else if ( this.verticalPosition === 'bottom' ) {
4661 newPos.bottom = $offsetParent.outerHeight() - containerPos.bottom;
4662 } else if ( this.verticalPosition === 'center' ) {
4663 newPos.top = containerPos.top +
4664 ( this.$floatableContainer.height() - this.$floatable.height() ) / 2;
4665 }
4666
4667 if ( this.horizontalPosition === 'before' ) {
4668 newPos.end = containerPos.start;
4669 } else if ( this.horizontalPosition === 'after' ) {
4670 newPos.start = containerPos.end;
4671 } else if ( this.horizontalPosition === 'start' ) {
4672 newPos.start = containerPos.start;
4673 } else if ( this.horizontalPosition === 'end' ) {
4674 newPos.end = containerPos.end;
4675 } else if ( this.horizontalPosition === 'center' ) {
4676 newPos.left = containerPos.left +
4677 ( this.$floatableContainer.width() - this.$floatable.width() ) / 2;
4678 }
4679
4680 if ( newPos.start !== undefined ) {
4681 if ( direction === 'rtl' ) {
4682 newPos.right = ( isBody ? $( $offsetParent[ 0 ].ownerDocument.documentElement ) : $offsetParent ).outerWidth() - newPos.start;
4683 } else {
4684 newPos.left = newPos.start;
4685 }
4686 delete newPos.start;
4687 }
4688 if ( newPos.end !== undefined ) {
4689 if ( direction === 'rtl' ) {
4690 newPos.left = newPos.end;
4691 } else {
4692 newPos.right = ( isBody ? $( $offsetParent[ 0 ].ownerDocument.documentElement ) : $offsetParent ).outerWidth() - newPos.end;
4693 }
4694 delete newPos.end;
4695 }
4696
4697 // Account for scroll position
4698 if ( newPos.top !== '' ) {
4699 newPos.top += scrollTop;
4700 }
4701 if ( newPos.bottom !== '' ) {
4702 newPos.bottom -= scrollTop;
4703 }
4704 if ( newPos.left !== '' ) {
4705 newPos.left += scrollLeft;
4706 }
4707 if ( newPos.right !== '' ) {
4708 newPos.right -= scrollLeft;
4709 }
4710
4711 // Account for scrollbar gutter
4712 if ( newPos.bottom !== '' ) {
4713 newPos.bottom -= horizScrollbarHeight;
4714 }
4715 if ( direction === 'rtl' ) {
4716 if ( newPos.left !== '' ) {
4717 newPos.left -= vertScrollbarWidth;
4718 }
4719 } else {
4720 if ( newPos.right !== '' ) {
4721 newPos.right -= vertScrollbarWidth;
4722 }
4723 }
4724
4725 return newPos;
4726 };
4727
4728 /**
4729 * Element that can be automatically clipped to visible boundaries.
4730 *
4731 * Whenever the element's natural height changes, you have to call
4732 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
4733 * clipping correctly.
4734 *
4735 * The dimensions of #$clippableContainer will be compared to the boundaries of the
4736 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
4737 * then #$clippable will be given a fixed reduced height and/or width and will be made
4738 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
4739 * but you can build a static footer by setting #$clippableContainer to an element that contains
4740 * #$clippable and the footer.
4741 *
4742 * @abstract
4743 * @class
4744 *
4745 * @constructor
4746 * @param {Object} [config] Configuration options
4747 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
4748 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
4749 * omit to use #$clippable
4750 */
4751 OO.ui.mixin.ClippableElement = function OoUiMixinClippableElement( config ) {
4752 // Configuration initialization
4753 config = config || {};
4754
4755 // Properties
4756 this.$clippable = null;
4757 this.$clippableContainer = null;
4758 this.clipping = false;
4759 this.clippedHorizontally = false;
4760 this.clippedVertically = false;
4761 this.$clippableScrollableContainer = null;
4762 this.$clippableScroller = null;
4763 this.$clippableWindow = null;
4764 this.idealWidth = null;
4765 this.idealHeight = null;
4766 this.onClippableScrollHandler = this.clip.bind( this );
4767 this.onClippableWindowResizeHandler = this.clip.bind( this );
4768
4769 // Initialization
4770 if ( config.$clippableContainer ) {
4771 this.setClippableContainer( config.$clippableContainer );
4772 }
4773 this.setClippableElement( config.$clippable || this.$element );
4774 };
4775
4776 /* Methods */
4777
4778 /**
4779 * Set clippable element.
4780 *
4781 * If an element is already set, it will be cleaned up before setting up the new element.
4782 *
4783 * @param {jQuery} $clippable Element to make clippable
4784 */
4785 OO.ui.mixin.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
4786 if ( this.$clippable ) {
4787 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
4788 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
4789 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
4790 }
4791
4792 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
4793 this.clip();
4794 };
4795
4796 /**
4797 * Set clippable container.
4798 *
4799 * This is the container that will be measured when deciding whether to clip. When clipping,
4800 * #$clippable will be resized in order to keep the clippable container fully visible.
4801 *
4802 * If the clippable container is unset, #$clippable will be used.
4803 *
4804 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
4805 */
4806 OO.ui.mixin.ClippableElement.prototype.setClippableContainer = function ( $clippableContainer ) {
4807 this.$clippableContainer = $clippableContainer;
4808 if ( this.$clippable ) {
4809 this.clip();
4810 }
4811 };
4812
4813 /**
4814 * Toggle clipping.
4815 *
4816 * Do not turn clipping on until after the element is attached to the DOM and visible.
4817 *
4818 * @param {boolean} [clipping] Enable clipping, omit to toggle
4819 * @chainable
4820 */
4821 OO.ui.mixin.ClippableElement.prototype.toggleClipping = function ( clipping ) {
4822 clipping = clipping === undefined ? !this.clipping : !!clipping;
4823
4824 if ( clipping && !this.warnedUnattached && !this.isElementAttached() ) {
4825 OO.ui.warnDeprecation( 'ClippableElement#toggleClipping: Before calling this method, the element must be attached to the DOM.' );
4826 this.warnedUnattached = true;
4827 }
4828
4829 if ( this.clipping !== clipping ) {
4830 this.clipping = clipping;
4831 if ( clipping ) {
4832 this.$clippableScrollableContainer = $( this.getClosestScrollableElementContainer() );
4833 // If the clippable container is the root, we have to listen to scroll events and check
4834 // jQuery.scrollTop on the window because of browser inconsistencies
4835 this.$clippableScroller = this.$clippableScrollableContainer.is( 'html, body' ) ?
4836 $( OO.ui.Element.static.getWindow( this.$clippableScrollableContainer ) ) :
4837 this.$clippableScrollableContainer;
4838 this.$clippableScroller.on( 'scroll', this.onClippableScrollHandler );
4839 this.$clippableWindow = $( this.getElementWindow() )
4840 .on( 'resize', this.onClippableWindowResizeHandler );
4841 // Initial clip after visible
4842 this.clip();
4843 } else {
4844 this.$clippable.css( {
4845 width: '',
4846 height: '',
4847 maxWidth: '',
4848 maxHeight: '',
4849 overflowX: '',
4850 overflowY: ''
4851 } );
4852 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
4853
4854 this.$clippableScrollableContainer = null;
4855 this.$clippableScroller.off( 'scroll', this.onClippableScrollHandler );
4856 this.$clippableScroller = null;
4857 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
4858 this.$clippableWindow = null;
4859 }
4860 }
4861
4862 return this;
4863 };
4864
4865 /**
4866 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4867 *
4868 * @return {boolean} Element will be clipped to the visible area
4869 */
4870 OO.ui.mixin.ClippableElement.prototype.isClipping = function () {
4871 return this.clipping;
4872 };
4873
4874 /**
4875 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
4876 *
4877 * @return {boolean} Part of the element is being clipped
4878 */
4879 OO.ui.mixin.ClippableElement.prototype.isClipped = function () {
4880 return this.clippedHorizontally || this.clippedVertically;
4881 };
4882
4883 /**
4884 * Check if the right of the element is being clipped by the nearest scrollable container.
4885 *
4886 * @return {boolean} Part of the element is being clipped
4887 */
4888 OO.ui.mixin.ClippableElement.prototype.isClippedHorizontally = function () {
4889 return this.clippedHorizontally;
4890 };
4891
4892 /**
4893 * Check if the bottom of the element is being clipped by the nearest scrollable container.
4894 *
4895 * @return {boolean} Part of the element is being clipped
4896 */
4897 OO.ui.mixin.ClippableElement.prototype.isClippedVertically = function () {
4898 return this.clippedVertically;
4899 };
4900
4901 /**
4902 * Set the ideal size. These are the dimensions #$clippable will have when it's not being clipped.
4903 *
4904 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
4905 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
4906 */
4907 OO.ui.mixin.ClippableElement.prototype.setIdealSize = function ( width, height ) {
4908 this.idealWidth = width;
4909 this.idealHeight = height;
4910
4911 if ( !this.clipping ) {
4912 // Update dimensions
4913 this.$clippable.css( { width: width, height: height } );
4914 }
4915 // While clipping, idealWidth and idealHeight are not considered
4916 };
4917
4918 /**
4919 * Return the side of the clippable on which it is "anchored" (aligned to something else).
4920 * ClippableElement will clip the opposite side when reducing element's width.
4921 *
4922 * Classes that mix in ClippableElement should override this to return 'right' if their
4923 * clippable is absolutely positioned and using 'right: Npx' (and not using 'left').
4924 * If your class also mixes in FloatableElement, this is handled automatically.
4925 *
4926 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
4927 * always in pixels, even if they were unset or set to 'auto'.)
4928 *
4929 * When in doubt, 'left' (or 'right' in RTL) is a sane fallback.
4930 *
4931 * @return {string} 'left' or 'right'
4932 */
4933 OO.ui.mixin.ClippableElement.prototype.getHorizontalAnchorEdge = function () {
4934 if ( this.computePosition && this.positioning && this.computePosition().right !== '' ) {
4935 return 'right';
4936 }
4937 return 'left';
4938 };
4939
4940 /**
4941 * Return the side of the clippable on which it is "anchored" (aligned to something else).
4942 * ClippableElement will clip the opposite side when reducing element's width.
4943 *
4944 * Classes that mix in ClippableElement should override this to return 'bottom' if their
4945 * clippable is absolutely positioned and using 'bottom: Npx' (and not using 'top').
4946 * If your class also mixes in FloatableElement, this is handled automatically.
4947 *
4948 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
4949 * always in pixels, even if they were unset or set to 'auto'.)
4950 *
4951 * When in doubt, 'top' is a sane fallback.
4952 *
4953 * @return {string} 'top' or 'bottom'
4954 */
4955 OO.ui.mixin.ClippableElement.prototype.getVerticalAnchorEdge = function () {
4956 if ( this.computePosition && this.positioning && this.computePosition().bottom !== '' ) {
4957 return 'bottom';
4958 }
4959 return 'top';
4960 };
4961
4962 /**
4963 * Clip element to visible boundaries and allow scrolling when needed. You should call this method
4964 * when the element's natural height changes.
4965 *
4966 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
4967 * overlapped by, the visible area of the nearest scrollable container.
4968 *
4969 * Because calling clip() when the natural height changes isn't always possible, we also set
4970 * max-height when the element isn't being clipped. This means that if the element tries to grow
4971 * beyond the edge, something reasonable will happen before clip() is called.
4972 *
4973 * @chainable
4974 */
4975 OO.ui.mixin.ClippableElement.prototype.clip = function () {
4976 var extraHeight, extraWidth, viewportSpacing,
4977 desiredWidth, desiredHeight, allotedWidth, allotedHeight,
4978 naturalWidth, naturalHeight, clipWidth, clipHeight,
4979 $item, itemRect, $viewport, viewportRect, availableRect,
4980 direction, vertScrollbarWidth, horizScrollbarHeight,
4981 // Extra tolerance so that the sloppy code below doesn't result in results that are off
4982 // by one or two pixels. (And also so that we have space to display drop shadows.)
4983 // Chosen by fair dice roll.
4984 buffer = 7;
4985
4986 if ( !this.clipping ) {
4987 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
4988 return this;
4989 }
4990
4991 function rectIntersection( a, b ) {
4992 var out = {};
4993 out.top = Math.max( a.top, b.top );
4994 out.left = Math.max( a.left, b.left );
4995 out.bottom = Math.min( a.bottom, b.bottom );
4996 out.right = Math.min( a.right, b.right );
4997 return out;
4998 }
4999
5000 viewportSpacing = OO.ui.getViewportSpacing();
5001
5002 if ( this.$clippableScrollableContainer.is( 'html, body' ) ) {
5003 $viewport = $( this.$clippableScrollableContainer[ 0 ].ownerDocument.body );
5004 // Dimensions of the browser window, rather than the element!
5005 viewportRect = {
5006 top: 0,
5007 left: 0,
5008 right: document.documentElement.clientWidth,
5009 bottom: document.documentElement.clientHeight
5010 };
5011 viewportRect.top += viewportSpacing.top;
5012 viewportRect.left += viewportSpacing.left;
5013 viewportRect.right -= viewportSpacing.right;
5014 viewportRect.bottom -= viewportSpacing.bottom;
5015 } else {
5016 $viewport = this.$clippableScrollableContainer;
5017 viewportRect = $viewport[ 0 ].getBoundingClientRect();
5018 // Convert into a plain object
5019 viewportRect = $.extend( {}, viewportRect );
5020 }
5021
5022 // Account for scrollbar gutter
5023 direction = $viewport.css( 'direction' );
5024 vertScrollbarWidth = $viewport.innerWidth() - $viewport.prop( 'clientWidth' );
5025 horizScrollbarHeight = $viewport.innerHeight() - $viewport.prop( 'clientHeight' );
5026 viewportRect.bottom -= horizScrollbarHeight;
5027 if ( direction === 'rtl' ) {
5028 viewportRect.left += vertScrollbarWidth;
5029 } else {
5030 viewportRect.right -= vertScrollbarWidth;
5031 }
5032
5033 // Add arbitrary tolerance
5034 viewportRect.top += buffer;
5035 viewportRect.left += buffer;
5036 viewportRect.right -= buffer;
5037 viewportRect.bottom -= buffer;
5038
5039 $item = this.$clippableContainer || this.$clippable;
5040
5041 extraHeight = $item.outerHeight() - this.$clippable.outerHeight();
5042 extraWidth = $item.outerWidth() - this.$clippable.outerWidth();
5043
5044 itemRect = $item[ 0 ].getBoundingClientRect();
5045 // Convert into a plain object
5046 itemRect = $.extend( {}, itemRect );
5047
5048 // Item might already be clipped, so we can't just use its dimensions (in case we might need to
5049 // make it larger than before). Extend the rectangle to the maximum size we are allowed to take.
5050 if ( this.getHorizontalAnchorEdge() === 'right' ) {
5051 itemRect.left = viewportRect.left;
5052 } else {
5053 itemRect.right = viewportRect.right;
5054 }
5055 if ( this.getVerticalAnchorEdge() === 'bottom' ) {
5056 itemRect.top = viewportRect.top;
5057 } else {
5058 itemRect.bottom = viewportRect.bottom;
5059 }
5060
5061 availableRect = rectIntersection( viewportRect, itemRect );
5062
5063 desiredWidth = Math.max( 0, availableRect.right - availableRect.left );
5064 desiredHeight = Math.max( 0, availableRect.bottom - availableRect.top );
5065 // It should never be desirable to exceed the dimensions of the browser viewport... right?
5066 desiredWidth = Math.min( desiredWidth,
5067 document.documentElement.clientWidth - viewportSpacing.left - viewportSpacing.right );
5068 desiredHeight = Math.min( desiredHeight,
5069 document.documentElement.clientHeight - viewportSpacing.top - viewportSpacing.right );
5070 allotedWidth = Math.ceil( desiredWidth - extraWidth );
5071 allotedHeight = Math.ceil( desiredHeight - extraHeight );
5072 naturalWidth = this.$clippable.prop( 'scrollWidth' );
5073 naturalHeight = this.$clippable.prop( 'scrollHeight' );
5074 clipWidth = allotedWidth < naturalWidth;
5075 clipHeight = allotedHeight < naturalHeight;
5076
5077 if ( clipWidth ) {
5078 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. See T157672.
5079 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
5080 this.$clippable.css( 'overflowX', 'scroll' );
5081 void this.$clippable[ 0 ].offsetHeight; // Force reflow
5082 this.$clippable.css( {
5083 width: Math.max( 0, allotedWidth ),
5084 maxWidth: ''
5085 } );
5086 } else {
5087 this.$clippable.css( {
5088 overflowX: '',
5089 width: this.idealWidth || '',
5090 maxWidth: Math.max( 0, allotedWidth )
5091 } );
5092 }
5093 if ( clipHeight ) {
5094 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. See T157672.
5095 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
5096 this.$clippable.css( 'overflowY', 'scroll' );
5097 void this.$clippable[ 0 ].offsetHeight; // Force reflow
5098 this.$clippable.css( {
5099 height: Math.max( 0, allotedHeight ),
5100 maxHeight: ''
5101 } );
5102 } else {
5103 this.$clippable.css( {
5104 overflowY: '',
5105 height: this.idealHeight || '',
5106 maxHeight: Math.max( 0, allotedHeight )
5107 } );
5108 }
5109
5110 // If we stopped clipping in at least one of the dimensions
5111 if ( ( this.clippedHorizontally && !clipWidth ) || ( this.clippedVertically && !clipHeight ) ) {
5112 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
5113 }
5114
5115 this.clippedHorizontally = clipWidth;
5116 this.clippedVertically = clipHeight;
5117
5118 return this;
5119 };
5120
5121 /**
5122 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
5123 * By default, each popup has an anchor that points toward its origin.
5124 * Please see the [OOUI documentation on MediaWiki.org] [1] for more information and examples.
5125 *
5126 * Unlike most widgets, PopupWidget is initially hidden and must be shown by calling #toggle.
5127 *
5128 * @example
5129 * // A popup widget.
5130 * var popup = new OO.ui.PopupWidget( {
5131 * $content: $( '<p>Hi there!</p>' ),
5132 * padded: true,
5133 * width: 300
5134 * } );
5135 *
5136 * $( 'body' ).append( popup.$element );
5137 * // To display the popup, toggle the visibility to 'true'.
5138 * popup.toggle( true );
5139 *
5140 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups
5141 *
5142 * @class
5143 * @extends OO.ui.Widget
5144 * @mixins OO.ui.mixin.LabelElement
5145 * @mixins OO.ui.mixin.ClippableElement
5146 * @mixins OO.ui.mixin.FloatableElement
5147 *
5148 * @constructor
5149 * @param {Object} [config] Configuration options
5150 * @cfg {number|null} [width=320] Width of popup in pixels. Pass `null` to use automatic width.
5151 * @cfg {number|null} [height=null] Height of popup in pixels. Pass `null` to use automatic height.
5152 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
5153 * @cfg {string} [position='below'] Where to position the popup relative to $floatableContainer
5154 * 'above': Put popup above $floatableContainer; anchor points down to the horizontal center
5155 * of $floatableContainer
5156 * 'below': Put popup below $floatableContainer; anchor points up to the horizontal center
5157 * of $floatableContainer
5158 * 'before': Put popup to the left (LTR) / right (RTL) of $floatableContainer; anchor points
5159 * endwards (right/left) to the vertical center of $floatableContainer
5160 * 'after': Put popup to the right (LTR) / left (RTL) of $floatableContainer; anchor points
5161 * startwards (left/right) to the vertical center of $floatableContainer
5162 * @cfg {string} [align='center'] How to align the popup to $floatableContainer
5163 * 'forwards': If position is above/below, move the popup as far endwards (right in LTR, left in RTL)
5164 * as possible while still keeping the anchor within the popup;
5165 * if position is before/after, move the popup as far downwards as possible.
5166 * 'backwards': If position is above/below, move the popup as far startwards (left in LTR, right in RTL)
5167 * as possible while still keeping the anchor within the popup;
5168 * if position in before/after, move the popup as far upwards as possible.
5169 * 'center': Horizontally (if position is above/below) or vertically (before/after) align the center
5170 * of the popup with the center of $floatableContainer.
5171 * 'force-left': Alias for 'forwards' in LTR and 'backwards' in RTL
5172 * 'force-right': Alias for 'backwards' in RTL and 'forwards' in LTR
5173 * @cfg {boolean} [autoFlip=true] Whether to automatically switch the popup's position between
5174 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5175 * desired direction to display the popup without clipping
5176 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
5177 * See the [OOUI docs on MediaWiki][3] for an example.
5178 * [3]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#containerExample
5179 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
5180 * @cfg {jQuery} [$content] Content to append to the popup's body
5181 * @cfg {jQuery} [$footer] Content to append to the popup's footer
5182 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
5183 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
5184 * This config option is only relevant if #autoClose is set to `true`. See the [OOUI documentation on MediaWiki][2]
5185 * for an example.
5186 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#autocloseExample
5187 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
5188 * button.
5189 * @cfg {boolean} [padded=false] Add padding to the popup's body
5190 */
5191 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
5192 // Configuration initialization
5193 config = config || {};
5194
5195 // Parent constructor
5196 OO.ui.PopupWidget.parent.call( this, config );
5197
5198 // Properties (must be set before ClippableElement constructor call)
5199 this.$body = $( '<div>' );
5200 this.$popup = $( '<div>' );
5201
5202 // Mixin constructors
5203 OO.ui.mixin.LabelElement.call( this, config );
5204 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, {
5205 $clippable: this.$body,
5206 $clippableContainer: this.$popup
5207 } ) );
5208 OO.ui.mixin.FloatableElement.call( this, config );
5209
5210 // Properties
5211 this.$anchor = $( '<div>' );
5212 // If undefined, will be computed lazily in computePosition()
5213 this.$container = config.$container;
5214 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
5215 this.autoClose = !!config.autoClose;
5216 this.transitionTimeout = null;
5217 this.anchored = false;
5218 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
5219 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
5220
5221 // Initialization
5222 this.setSize( config.width, config.height );
5223 this.toggleAnchor( config.anchor === undefined || config.anchor );
5224 this.setAlignment( config.align || 'center' );
5225 this.setPosition( config.position || 'below' );
5226 this.setAutoFlip( config.autoFlip === undefined || config.autoFlip );
5227 this.setAutoCloseIgnore( config.$autoCloseIgnore );
5228 this.$body.addClass( 'oo-ui-popupWidget-body' );
5229 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
5230 this.$popup
5231 .addClass( 'oo-ui-popupWidget-popup' )
5232 .append( this.$body );
5233 this.$element
5234 .addClass( 'oo-ui-popupWidget' )
5235 .append( this.$popup, this.$anchor );
5236 // Move content, which was added to #$element by OO.ui.Widget, to the body
5237 // FIXME This is gross, we should use '$body' or something for the config
5238 if ( config.$content instanceof jQuery ) {
5239 this.$body.append( config.$content );
5240 }
5241
5242 if ( config.padded ) {
5243 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
5244 }
5245
5246 if ( config.head ) {
5247 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
5248 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
5249 this.$head = $( '<div>' )
5250 .addClass( 'oo-ui-popupWidget-head' )
5251 .append( this.$label, this.closeButton.$element );
5252 this.$popup.prepend( this.$head );
5253 }
5254
5255 if ( config.$footer ) {
5256 this.$footer = $( '<div>' )
5257 .addClass( 'oo-ui-popupWidget-footer' )
5258 .append( config.$footer );
5259 this.$popup.append( this.$footer );
5260 }
5261
5262 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
5263 // that reference properties not initialized at that time of parent class construction
5264 // TODO: Find a better way to handle post-constructor setup
5265 this.visible = false;
5266 this.$element.addClass( 'oo-ui-element-hidden' );
5267 };
5268
5269 /* Setup */
5270
5271 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
5272 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.LabelElement );
5273 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.ClippableElement );
5274 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.FloatableElement );
5275
5276 /* Events */
5277
5278 /**
5279 * @event ready
5280 *
5281 * The popup is ready: it is visible and has been positioned and clipped.
5282 */
5283
5284 /* Methods */
5285
5286 /**
5287 * Handles document mouse down events.
5288 *
5289 * @private
5290 * @param {MouseEvent} e Mouse down event
5291 */
5292 OO.ui.PopupWidget.prototype.onDocumentMouseDown = function ( e ) {
5293 if (
5294 this.isVisible() &&
5295 !OO.ui.contains( this.$element.add( this.$autoCloseIgnore ).get(), e.target, true )
5296 ) {
5297 this.toggle( false );
5298 }
5299 };
5300
5301 // Deprecated alias since 0.28.3
5302 OO.ui.PopupWidget.prototype.onMouseDown = function () {
5303 OO.ui.warnDeprecation( 'onMouseDown is deprecated, use onDocumentMouseDown instead' );
5304 this.onDocumentMouseDown.apply( this, arguments );
5305 };
5306
5307 /**
5308 * Bind document mouse down listener.
5309 *
5310 * @private
5311 */
5312 OO.ui.PopupWidget.prototype.bindDocumentMouseDownListener = function () {
5313 // Capture clicks outside popup
5314 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
5315 // We add 'click' event because iOS safari needs to respond to this event.
5316 // We can't use 'touchstart' (as is usually the equivalent to 'mousedown') because
5317 // then it will trigger when scrolling. While iOS Safari has some reported behavior
5318 // of occasionally not emitting 'click' properly, that event seems to be the standard
5319 // that it should be emitting, so we add it to this and will operate the event handler
5320 // on whichever of these events was triggered first
5321 this.getElementDocument().addEventListener( 'click', this.onDocumentMouseDownHandler, true );
5322 };
5323
5324 // Deprecated alias since 0.28.3
5325 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
5326 OO.ui.warnDeprecation( 'bindMouseDownListener is deprecated, use bindDocumentMouseDownListener instead' );
5327 this.bindDocumentMouseDownListener.apply( this, arguments );
5328 };
5329
5330 /**
5331 * Handles close button click events.
5332 *
5333 * @private
5334 */
5335 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
5336 if ( this.isVisible() ) {
5337 this.toggle( false );
5338 }
5339 };
5340
5341 /**
5342 * Unbind document mouse down listener.
5343 *
5344 * @private
5345 */
5346 OO.ui.PopupWidget.prototype.unbindDocumentMouseDownListener = function () {
5347 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
5348 this.getElementDocument().removeEventListener( 'click', this.onDocumentMouseDownHandler, true );
5349 };
5350
5351 // Deprecated alias since 0.28.3
5352 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
5353 OO.ui.warnDeprecation( 'unbindMouseDownListener is deprecated, use unbindDocumentMouseDownListener instead' );
5354 this.unbindDocumentMouseDownListener.apply( this, arguments );
5355 };
5356
5357 /**
5358 * Handles document key down events.
5359 *
5360 * @private
5361 * @param {KeyboardEvent} e Key down event
5362 */
5363 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
5364 if (
5365 e.which === OO.ui.Keys.ESCAPE &&
5366 this.isVisible()
5367 ) {
5368 this.toggle( false );
5369 e.preventDefault();
5370 e.stopPropagation();
5371 }
5372 };
5373
5374 /**
5375 * Bind document key down listener.
5376 *
5377 * @private
5378 */
5379 OO.ui.PopupWidget.prototype.bindDocumentKeyDownListener = function () {
5380 this.getElementDocument().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
5381 };
5382
5383 // Deprecated alias since 0.28.3
5384 OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
5385 OO.ui.warnDeprecation( 'bindKeyDownListener is deprecated, use bindDocumentKeyDownListener instead' );
5386 this.bindDocumentKeyDownListener.apply( this, arguments );
5387 };
5388
5389 /**
5390 * Unbind document key down listener.
5391 *
5392 * @private
5393 */
5394 OO.ui.PopupWidget.prototype.unbindDocumentKeyDownListener = function () {
5395 this.getElementDocument().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
5396 };
5397
5398 // Deprecated alias since 0.28.3
5399 OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
5400 OO.ui.warnDeprecation( 'unbindKeyDownListener is deprecated, use unbindDocumentKeyDownListener instead' );
5401 this.unbindDocumentKeyDownListener.apply( this, arguments );
5402 };
5403
5404 /**
5405 * Show, hide, or toggle the visibility of the anchor.
5406 *
5407 * @param {boolean} [show] Show anchor, omit to toggle
5408 */
5409 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
5410 show = show === undefined ? !this.anchored : !!show;
5411
5412 if ( this.anchored !== show ) {
5413 if ( show ) {
5414 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
5415 this.$element.addClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge );
5416 } else {
5417 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
5418 this.$element.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge );
5419 }
5420 this.anchored = show;
5421 }
5422 };
5423
5424 /**
5425 * Change which edge the anchor appears on.
5426 *
5427 * @param {string} edge 'top', 'bottom', 'start' or 'end'
5428 */
5429 OO.ui.PopupWidget.prototype.setAnchorEdge = function ( edge ) {
5430 if ( [ 'top', 'bottom', 'start', 'end' ].indexOf( edge ) === -1 ) {
5431 throw new Error( 'Invalid value for edge: ' + edge );
5432 }
5433 if ( this.anchorEdge !== null ) {
5434 this.$element.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge );
5435 }
5436 this.anchorEdge = edge;
5437 if ( this.anchored ) {
5438 this.$element.addClass( 'oo-ui-popupWidget-anchored-' + edge );
5439 }
5440 };
5441
5442 /**
5443 * Check if the anchor is visible.
5444 *
5445 * @return {boolean} Anchor is visible
5446 */
5447 OO.ui.PopupWidget.prototype.hasAnchor = function () {
5448 return this.anchored;
5449 };
5450
5451 /**
5452 * Toggle visibility of the popup. The popup is initially hidden and must be shown by calling
5453 * `.toggle( true )` after its #$element is attached to the DOM.
5454 *
5455 * Do not show the popup while it is not attached to the DOM. The calculations required to display
5456 * it in the right place and with the right dimensions only work correctly while it is attached.
5457 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
5458 * strictly enforced, so currently it only generates a warning in the browser console.
5459 *
5460 * @fires ready
5461 * @inheritdoc
5462 */
5463 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
5464 var change, normalHeight, oppositeHeight, normalWidth, oppositeWidth;
5465 show = show === undefined ? !this.isVisible() : !!show;
5466
5467 change = show !== this.isVisible();
5468
5469 if ( show && !this.warnedUnattached && !this.isElementAttached() ) {
5470 OO.ui.warnDeprecation( 'PopupWidget#toggle: Before calling this method, the popup must be attached to the DOM.' );
5471 this.warnedUnattached = true;
5472 }
5473 if ( show && !this.$floatableContainer && this.isElementAttached() ) {
5474 // Fall back to the parent node if the floatableContainer is not set
5475 this.setFloatableContainer( this.$element.parent() );
5476 }
5477
5478 if ( change && show && this.autoFlip ) {
5479 // Reset auto-flipping before showing the popup again. It's possible we no longer need to flip
5480 // (e.g. if the user scrolled).
5481 this.isAutoFlipped = false;
5482 }
5483
5484 // Parent method
5485 OO.ui.PopupWidget.parent.prototype.toggle.call( this, show );
5486
5487 if ( change ) {
5488 this.togglePositioning( show && !!this.$floatableContainer );
5489
5490 if ( show ) {
5491 if ( this.autoClose ) {
5492 this.bindDocumentMouseDownListener();
5493 this.bindDocumentKeyDownListener();
5494 }
5495 this.updateDimensions();
5496 this.toggleClipping( true );
5497
5498 if ( this.autoFlip ) {
5499 if ( this.popupPosition === 'above' || this.popupPosition === 'below' ) {
5500 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5501 // If opening the popup in the normal direction causes it to be clipped, open
5502 // in the opposite one instead
5503 normalHeight = this.$element.height();
5504 this.isAutoFlipped = !this.isAutoFlipped;
5505 this.position();
5506 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5507 // If that also causes it to be clipped, open in whichever direction
5508 // we have more space
5509 oppositeHeight = this.$element.height();
5510 if ( oppositeHeight < normalHeight ) {
5511 this.isAutoFlipped = !this.isAutoFlipped;
5512 this.position();
5513 }
5514 }
5515 }
5516 }
5517 if ( this.popupPosition === 'before' || this.popupPosition === 'after' ) {
5518 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5519 // If opening the popup in the normal direction causes it to be clipped, open
5520 // in the opposite one instead
5521 normalWidth = this.$element.width();
5522 this.isAutoFlipped = !this.isAutoFlipped;
5523 // Due to T180173 horizontally clipped PopupWidgets have messed up dimensions,
5524 // which causes positioning to be off. Toggle clipping back and fort to work around.
5525 this.toggleClipping( false );
5526 this.position();
5527 this.toggleClipping( true );
5528 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5529 // If that also causes it to be clipped, open in whichever direction
5530 // we have more space
5531 oppositeWidth = this.$element.width();
5532 if ( oppositeWidth < normalWidth ) {
5533 this.isAutoFlipped = !this.isAutoFlipped;
5534 // Due to T180173 horizontally clipped PopupWidgets have messed up dimensions,
5535 // which causes positioning to be off. Toggle clipping back and fort to work around.
5536 this.toggleClipping( false );
5537 this.position();
5538 this.toggleClipping( true );
5539 }
5540 }
5541 }
5542 }
5543 }
5544
5545 this.emit( 'ready' );
5546 } else {
5547 this.toggleClipping( false );
5548 if ( this.autoClose ) {
5549 this.unbindDocumentMouseDownListener();
5550 this.unbindDocumentKeyDownListener();
5551 }
5552 }
5553 }
5554
5555 return this;
5556 };
5557
5558 /**
5559 * Set the size of the popup.
5560 *
5561 * Changing the size may also change the popup's position depending on the alignment.
5562 *
5563 * @param {number|null} [width=320] Width in pixels. Pass `null` to use automatic width.
5564 * @param {number|null} [height=null] Height in pixels. Pass `null` to use automatic height.
5565 * @param {boolean} [transition=false] Use a smooth transition
5566 * @chainable
5567 */
5568 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
5569 this.width = width !== undefined ? width : 320;
5570 this.height = height !== undefined ? height : null;
5571 if ( this.isVisible() ) {
5572 this.updateDimensions( transition );
5573 }
5574 };
5575
5576 /**
5577 * Update the size and position.
5578 *
5579 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
5580 * be called automatically.
5581 *
5582 * @param {boolean} [transition=false] Use a smooth transition
5583 * @chainable
5584 */
5585 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
5586 var widget = this;
5587
5588 // Prevent transition from being interrupted
5589 clearTimeout( this.transitionTimeout );
5590 if ( transition ) {
5591 // Enable transition
5592 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
5593 }
5594
5595 this.position();
5596
5597 if ( transition ) {
5598 // Prevent transitioning after transition is complete
5599 this.transitionTimeout = setTimeout( function () {
5600 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
5601 }, 200 );
5602 } else {
5603 // Prevent transitioning immediately
5604 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
5605 }
5606 };
5607
5608 /**
5609 * @inheritdoc
5610 */
5611 OO.ui.PopupWidget.prototype.computePosition = function () {
5612 var direction, align, vertical, start, end, near, far, sizeProp, popupSize, anchorSize, anchorPos,
5613 anchorOffset, anchorMargin, parentPosition, positionProp, positionAdjustment, floatablePos,
5614 offsetParentPos, containerPos, popupPosition, viewportSpacing,
5615 popupPos = {},
5616 anchorCss = { left: '', right: '', top: '', bottom: '' },
5617 popupPositionOppositeMap = {
5618 above: 'below',
5619 below: 'above',
5620 before: 'after',
5621 after: 'before'
5622 },
5623 alignMap = {
5624 ltr: {
5625 'force-left': 'backwards',
5626 'force-right': 'forwards'
5627 },
5628 rtl: {
5629 'force-left': 'forwards',
5630 'force-right': 'backwards'
5631 }
5632 },
5633 anchorEdgeMap = {
5634 above: 'bottom',
5635 below: 'top',
5636 before: 'end',
5637 after: 'start'
5638 },
5639 hPosMap = {
5640 forwards: 'start',
5641 center: 'center',
5642 backwards: this.anchored ? 'before' : 'end'
5643 },
5644 vPosMap = {
5645 forwards: 'top',
5646 center: 'center',
5647 backwards: 'bottom'
5648 };
5649
5650 if ( !this.$container ) {
5651 // Lazy-initialize $container if not specified in constructor
5652 this.$container = $( this.getClosestScrollableElementContainer() );
5653 }
5654 direction = this.$container.css( 'direction' );
5655
5656 // Set height and width before we do anything else, since it might cause our measurements
5657 // to change (e.g. due to scrollbars appearing or disappearing), and it also affects centering
5658 this.$popup.css( {
5659 width: this.width !== null ? this.width : 'auto',
5660 height: this.height !== null ? this.height : 'auto'
5661 } );
5662
5663 align = alignMap[ direction ][ this.align ] || this.align;
5664 popupPosition = this.popupPosition;
5665 if ( this.isAutoFlipped ) {
5666 popupPosition = popupPositionOppositeMap[ popupPosition ];
5667 }
5668
5669 // If the popup is positioned before or after, then the anchor positioning is vertical, otherwise horizontal
5670 vertical = popupPosition === 'before' || popupPosition === 'after';
5671 start = vertical ? 'top' : ( direction === 'rtl' ? 'right' : 'left' );
5672 end = vertical ? 'bottom' : ( direction === 'rtl' ? 'left' : 'right' );
5673 near = vertical ? 'top' : 'left';
5674 far = vertical ? 'bottom' : 'right';
5675 sizeProp = vertical ? 'Height' : 'Width';
5676 popupSize = vertical ? ( this.height || this.$popup.height() ) : ( this.width || this.$popup.width() );
5677
5678 this.setAnchorEdge( anchorEdgeMap[ popupPosition ] );
5679 this.horizontalPosition = vertical ? popupPosition : hPosMap[ align ];
5680 this.verticalPosition = vertical ? vPosMap[ align ] : popupPosition;
5681
5682 // Parent method
5683 parentPosition = OO.ui.mixin.FloatableElement.prototype.computePosition.call( this );
5684 // Find out which property FloatableElement used for positioning, and adjust that value
5685 positionProp = vertical ?
5686 ( parentPosition.top !== '' ? 'top' : 'bottom' ) :
5687 ( parentPosition.left !== '' ? 'left' : 'right' );
5688
5689 // Figure out where the near and far edges of the popup and $floatableContainer are
5690 floatablePos = this.$floatableContainer.offset();
5691 floatablePos[ far ] = floatablePos[ near ] + this.$floatableContainer[ 'outer' + sizeProp ]();
5692 // Measure where the offsetParent is and compute our position based on that and parentPosition
5693 offsetParentPos = this.$element.offsetParent()[ 0 ] === document.documentElement ?
5694 { top: 0, left: 0 } :
5695 this.$element.offsetParent().offset();
5696
5697 if ( positionProp === near ) {
5698 popupPos[ near ] = offsetParentPos[ near ] + parentPosition[ near ];
5699 popupPos[ far ] = popupPos[ near ] + popupSize;
5700 } else {
5701 popupPos[ far ] = offsetParentPos[ near ] +
5702 this.$element.offsetParent()[ 'inner' + sizeProp ]() - parentPosition[ far ];
5703 popupPos[ near ] = popupPos[ far ] - popupSize;
5704 }
5705
5706 if ( this.anchored ) {
5707 // Position the anchor (which is positioned relative to the popup) to point to $floatableContainer
5708 anchorPos = ( floatablePos[ start ] + floatablePos[ end ] ) / 2;
5709 anchorOffset = ( start === far ? -1 : 1 ) * ( anchorPos - popupPos[ start ] );
5710
5711 // If the anchor is less than 2*anchorSize from either edge, move the popup to make more space
5712 // this.$anchor.width()/height() returns 0 because of the CSS trickery we use, so use scrollWidth/Height
5713 anchorSize = this.$anchor[ 0 ][ 'scroll' + sizeProp ];
5714 anchorMargin = parseFloat( this.$anchor.css( 'margin-' + start ) );
5715 if ( anchorOffset + anchorMargin < 2 * anchorSize ) {
5716 // Not enough space for the anchor on the start side; pull the popup startwards
5717 positionAdjustment = ( positionProp === start ? -1 : 1 ) *
5718 ( 2 * anchorSize - ( anchorOffset + anchorMargin ) );
5719 } else if ( anchorOffset + anchorMargin > popupSize - 2 * anchorSize ) {
5720 // Not enough space for the anchor on the end side; pull the popup endwards
5721 positionAdjustment = ( positionProp === end ? -1 : 1 ) *
5722 ( anchorOffset + anchorMargin - ( popupSize - 2 * anchorSize ) );
5723 } else {
5724 positionAdjustment = 0;
5725 }
5726 } else {
5727 positionAdjustment = 0;
5728 }
5729
5730 // Check if the popup will go beyond the edge of this.$container
5731 containerPos = this.$container[ 0 ] === document.documentElement ?
5732 { top: 0, left: 0 } :
5733 this.$container.offset();
5734 containerPos[ far ] = containerPos[ near ] + this.$container[ 'inner' + sizeProp ]();
5735 if ( this.$container[ 0 ] === document.documentElement ) {
5736 viewportSpacing = OO.ui.getViewportSpacing();
5737 containerPos[ near ] += viewportSpacing[ near ];
5738 containerPos[ far ] -= viewportSpacing[ far ];
5739 }
5740 // Take into account how much the popup will move because of the adjustments we're going to make
5741 popupPos[ near ] += ( positionProp === near ? 1 : -1 ) * positionAdjustment;
5742 popupPos[ far ] += ( positionProp === near ? 1 : -1 ) * positionAdjustment;
5743 if ( containerPos[ near ] + this.containerPadding > popupPos[ near ] ) {
5744 // Popup goes beyond the near (left/top) edge, move it to the right/bottom
5745 positionAdjustment += ( positionProp === near ? 1 : -1 ) *
5746 ( containerPos[ near ] + this.containerPadding - popupPos[ near ] );
5747 } else if ( containerPos[ far ] - this.containerPadding < popupPos[ far ] ) {
5748 // Popup goes beyond the far (right/bottom) edge, move it to the left/top
5749 positionAdjustment += ( positionProp === far ? 1 : -1 ) *
5750 ( popupPos[ far ] - ( containerPos[ far ] - this.containerPadding ) );
5751 }
5752
5753 if ( this.anchored ) {
5754 // Adjust anchorOffset for positionAdjustment
5755 anchorOffset += ( positionProp === start ? -1 : 1 ) * positionAdjustment;
5756
5757 // Position the anchor
5758 anchorCss[ start ] = anchorOffset;
5759 this.$anchor.css( anchorCss );
5760 }
5761
5762 // Move the popup if needed
5763 parentPosition[ positionProp ] += positionAdjustment;
5764
5765 return parentPosition;
5766 };
5767
5768 /**
5769 * Set popup alignment
5770 *
5771 * @param {string} [align=center] Alignment of the popup, `center`, `force-left`, `force-right`,
5772 * `backwards` or `forwards`.
5773 */
5774 OO.ui.PopupWidget.prototype.setAlignment = function ( align ) {
5775 // Validate alignment
5776 if ( [ 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align ) > -1 ) {
5777 this.align = align;
5778 } else {
5779 this.align = 'center';
5780 }
5781 this.position();
5782 };
5783
5784 /**
5785 * Get popup alignment
5786 *
5787 * @return {string} Alignment of the popup, `center`, `force-left`, `force-right`,
5788 * `backwards` or `forwards`.
5789 */
5790 OO.ui.PopupWidget.prototype.getAlignment = function () {
5791 return this.align;
5792 };
5793
5794 /**
5795 * Change the positioning of the popup.
5796 *
5797 * @param {string} position 'above', 'below', 'before' or 'after'
5798 */
5799 OO.ui.PopupWidget.prototype.setPosition = function ( position ) {
5800 if ( [ 'above', 'below', 'before', 'after' ].indexOf( position ) === -1 ) {
5801 position = 'below';
5802 }
5803 this.popupPosition = position;
5804 this.position();
5805 };
5806
5807 /**
5808 * Get popup positioning.
5809 *
5810 * @return {string} 'above', 'below', 'before' or 'after'
5811 */
5812 OO.ui.PopupWidget.prototype.getPosition = function () {
5813 return this.popupPosition;
5814 };
5815
5816 /**
5817 * Set popup auto-flipping.
5818 *
5819 * @param {boolean} autoFlip Whether to automatically switch the popup's position between
5820 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5821 * desired direction to display the popup without clipping
5822 */
5823 OO.ui.PopupWidget.prototype.setAutoFlip = function ( autoFlip ) {
5824 autoFlip = !!autoFlip;
5825
5826 if ( this.autoFlip !== autoFlip ) {
5827 this.autoFlip = autoFlip;
5828 }
5829 };
5830
5831 /**
5832 * Set which elements will not close the popup when clicked.
5833 *
5834 * For auto-closing popups, clicks on these elements will not cause the popup to auto-close.
5835 *
5836 * @param {jQuery} $autoCloseIgnore Elements to ignore for auto-closing
5837 */
5838 OO.ui.PopupWidget.prototype.setAutoCloseIgnore = function ( $autoCloseIgnore ) {
5839 this.$autoCloseIgnore = $autoCloseIgnore;
5840 };
5841
5842 /**
5843 * Get an ID of the body element, this can be used as the
5844 * `aria-describedby` attribute for an input field.
5845 *
5846 * @return {string} The ID of the body element
5847 */
5848 OO.ui.PopupWidget.prototype.getBodyId = function () {
5849 var id = this.$body.attr( 'id' );
5850 if ( id === undefined ) {
5851 id = OO.ui.generateElementId();
5852 this.$body.attr( 'id', id );
5853 }
5854 return id;
5855 };
5856
5857 /**
5858 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5859 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5860 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5861 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5862 *
5863 * @abstract
5864 * @class
5865 *
5866 * @constructor
5867 * @param {Object} [config] Configuration options
5868 * @cfg {Object} [popup] Configuration to pass to popup
5869 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5870 */
5871 OO.ui.mixin.PopupElement = function OoUiMixinPopupElement( config ) {
5872 // Configuration initialization
5873 config = config || {};
5874
5875 // Properties
5876 this.popup = new OO.ui.PopupWidget( $.extend(
5877 {
5878 autoClose: true,
5879 $floatableContainer: this.$element
5880 },
5881 config.popup,
5882 {
5883 $autoCloseIgnore: this.$element.add( config.popup && config.popup.$autoCloseIgnore )
5884 }
5885 ) );
5886 };
5887
5888 /* Methods */
5889
5890 /**
5891 * Get popup.
5892 *
5893 * @return {OO.ui.PopupWidget} Popup widget
5894 */
5895 OO.ui.mixin.PopupElement.prototype.getPopup = function () {
5896 return this.popup;
5897 };
5898
5899 /**
5900 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
5901 * which is used to display additional information or options.
5902 *
5903 * @example
5904 * // Example of a popup button.
5905 * var popupButton = new OO.ui.PopupButtonWidget( {
5906 * label: 'Popup button with options',
5907 * icon: 'menu',
5908 * popup: {
5909 * $content: $( '<p>Additional options here.</p>' ),
5910 * padded: true,
5911 * align: 'force-left'
5912 * }
5913 * } );
5914 * // Append the button to the DOM.
5915 * $( 'body' ).append( popupButton.$element );
5916 *
5917 * @class
5918 * @extends OO.ui.ButtonWidget
5919 * @mixins OO.ui.mixin.PopupElement
5920 *
5921 * @constructor
5922 * @param {Object} [config] Configuration options
5923 * @cfg {jQuery} [$overlay] Render the popup into a separate layer. This configuration is useful in cases where
5924 * the expanded popup is larger than its containing `<div>`. The specified overlay layer is usually on top of the
5925 * containing `<div>` and has a larger area. By default, the popup uses relative positioning.
5926 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
5927 */
5928 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
5929 // Configuration initialization
5930 config = config || {};
5931
5932 // Parent constructor
5933 OO.ui.PopupButtonWidget.parent.call( this, config );
5934
5935 // Mixin constructors
5936 OO.ui.mixin.PopupElement.call( this, config );
5937
5938 // Properties
5939 this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
5940
5941 // Events
5942 this.connect( this, { click: 'onAction' } );
5943
5944 // Initialization
5945 this.$element
5946 .addClass( 'oo-ui-popupButtonWidget' );
5947 this.popup.$element
5948 .addClass( 'oo-ui-popupButtonWidget-popup' )
5949 .toggleClass( 'oo-ui-popupButtonWidget-framed-popup', this.isFramed() )
5950 .toggleClass( 'oo-ui-popupButtonWidget-frameless-popup', !this.isFramed() );
5951 this.$overlay.append( this.popup.$element );
5952 };
5953
5954 /* Setup */
5955
5956 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
5957 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.mixin.PopupElement );
5958
5959 /* Methods */
5960
5961 /**
5962 * Handle the button action being triggered.
5963 *
5964 * @private
5965 */
5966 OO.ui.PopupButtonWidget.prototype.onAction = function () {
5967 this.popup.toggle();
5968 };
5969
5970 /**
5971 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
5972 *
5973 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
5974 *
5975 * @private
5976 * @abstract
5977 * @class
5978 * @mixins OO.ui.mixin.GroupElement
5979 *
5980 * @constructor
5981 * @param {Object} [config] Configuration options
5982 */
5983 OO.ui.mixin.GroupWidget = function OoUiMixinGroupWidget( config ) {
5984 // Mixin constructors
5985 OO.ui.mixin.GroupElement.call( this, config );
5986 };
5987
5988 /* Setup */
5989
5990 OO.mixinClass( OO.ui.mixin.GroupWidget, OO.ui.mixin.GroupElement );
5991
5992 /* Methods */
5993
5994 /**
5995 * Set the disabled state of the widget.
5996 *
5997 * This will also update the disabled state of child widgets.
5998 *
5999 * @param {boolean} disabled Disable widget
6000 * @chainable
6001 */
6002 OO.ui.mixin.GroupWidget.prototype.setDisabled = function ( disabled ) {
6003 var i, len;
6004
6005 // Parent method
6006 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
6007 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
6008
6009 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
6010 if ( this.items ) {
6011 for ( i = 0, len = this.items.length; i < len; i++ ) {
6012 this.items[ i ].updateDisabled();
6013 }
6014 }
6015
6016 return this;
6017 };
6018
6019 /**
6020 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
6021 *
6022 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
6023 * allows bidirectional communication.
6024 *
6025 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
6026 *
6027 * @private
6028 * @abstract
6029 * @class
6030 *
6031 * @constructor
6032 */
6033 OO.ui.mixin.ItemWidget = function OoUiMixinItemWidget() {
6034 //
6035 };
6036
6037 /* Methods */
6038
6039 /**
6040 * Check if widget is disabled.
6041 *
6042 * Checks parent if present, making disabled state inheritable.
6043 *
6044 * @return {boolean} Widget is disabled
6045 */
6046 OO.ui.mixin.ItemWidget.prototype.isDisabled = function () {
6047 return this.disabled ||
6048 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
6049 };
6050
6051 /**
6052 * Set group element is in.
6053 *
6054 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
6055 * @chainable
6056 */
6057 OO.ui.mixin.ItemWidget.prototype.setElementGroup = function ( group ) {
6058 // Parent method
6059 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
6060 OO.ui.Element.prototype.setElementGroup.call( this, group );
6061
6062 // Initialize item disabled states
6063 this.updateDisabled();
6064
6065 return this;
6066 };
6067
6068 /**
6069 * OptionWidgets are special elements that can be selected and configured with data. The
6070 * data is often unique for each option, but it does not have to be. OptionWidgets are used
6071 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
6072 * and examples, please see the [OOUI documentation on MediaWiki][1].
6073 *
6074 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6075 *
6076 * @class
6077 * @extends OO.ui.Widget
6078 * @mixins OO.ui.mixin.ItemWidget
6079 * @mixins OO.ui.mixin.LabelElement
6080 * @mixins OO.ui.mixin.FlaggedElement
6081 * @mixins OO.ui.mixin.AccessKeyedElement
6082 *
6083 * @constructor
6084 * @param {Object} [config] Configuration options
6085 */
6086 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
6087 // Configuration initialization
6088 config = config || {};
6089
6090 // Parent constructor
6091 OO.ui.OptionWidget.parent.call( this, config );
6092
6093 // Mixin constructors
6094 OO.ui.mixin.ItemWidget.call( this );
6095 OO.ui.mixin.LabelElement.call( this, config );
6096 OO.ui.mixin.FlaggedElement.call( this, config );
6097 OO.ui.mixin.AccessKeyedElement.call( this, config );
6098
6099 // Properties
6100 this.selected = false;
6101 this.highlighted = false;
6102 this.pressed = false;
6103
6104 // Initialization
6105 this.$element
6106 .data( 'oo-ui-optionWidget', this )
6107 // Allow programmatic focussing (and by accesskey), but not tabbing
6108 .attr( 'tabindex', '-1' )
6109 .attr( 'role', 'option' )
6110 .attr( 'aria-selected', 'false' )
6111 .addClass( 'oo-ui-optionWidget' )
6112 .append( this.$label );
6113 };
6114
6115 /* Setup */
6116
6117 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
6118 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.ItemWidget );
6119 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.LabelElement );
6120 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.FlaggedElement );
6121 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.AccessKeyedElement );
6122
6123 /* Static Properties */
6124
6125 /**
6126 * Whether this option can be selected. See #setSelected.
6127 *
6128 * @static
6129 * @inheritable
6130 * @property {boolean}
6131 */
6132 OO.ui.OptionWidget.static.selectable = true;
6133
6134 /**
6135 * Whether this option can be highlighted. See #setHighlighted.
6136 *
6137 * @static
6138 * @inheritable
6139 * @property {boolean}
6140 */
6141 OO.ui.OptionWidget.static.highlightable = true;
6142
6143 /**
6144 * Whether this option can be pressed. See #setPressed.
6145 *
6146 * @static
6147 * @inheritable
6148 * @property {boolean}
6149 */
6150 OO.ui.OptionWidget.static.pressable = true;
6151
6152 /**
6153 * Whether this option will be scrolled into view when it is selected.
6154 *
6155 * @static
6156 * @inheritable
6157 * @property {boolean}
6158 */
6159 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
6160
6161 /* Methods */
6162
6163 /**
6164 * Check if the option can be selected.
6165 *
6166 * @return {boolean} Item is selectable
6167 */
6168 OO.ui.OptionWidget.prototype.isSelectable = function () {
6169 return this.constructor.static.selectable && !this.disabled && this.isVisible();
6170 };
6171
6172 /**
6173 * Check if the option can be highlighted. A highlight indicates that the option
6174 * may be selected when a user presses enter or clicks. Disabled items cannot
6175 * be highlighted.
6176 *
6177 * @return {boolean} Item is highlightable
6178 */
6179 OO.ui.OptionWidget.prototype.isHighlightable = function () {
6180 return this.constructor.static.highlightable && !this.disabled && this.isVisible();
6181 };
6182
6183 /**
6184 * Check if the option can be pressed. The pressed state occurs when a user mouses
6185 * down on an item, but has not yet let go of the mouse.
6186 *
6187 * @return {boolean} Item is pressable
6188 */
6189 OO.ui.OptionWidget.prototype.isPressable = function () {
6190 return this.constructor.static.pressable && !this.disabled && this.isVisible();
6191 };
6192
6193 /**
6194 * Check if the option is selected.
6195 *
6196 * @return {boolean} Item is selected
6197 */
6198 OO.ui.OptionWidget.prototype.isSelected = function () {
6199 return this.selected;
6200 };
6201
6202 /**
6203 * Check if the option is highlighted. A highlight indicates that the
6204 * item may be selected when a user presses enter or clicks.
6205 *
6206 * @return {boolean} Item is highlighted
6207 */
6208 OO.ui.OptionWidget.prototype.isHighlighted = function () {
6209 return this.highlighted;
6210 };
6211
6212 /**
6213 * Check if the option is pressed. The pressed state occurs when a user mouses
6214 * down on an item, but has not yet let go of the mouse. The item may appear
6215 * selected, but it will not be selected until the user releases the mouse.
6216 *
6217 * @return {boolean} Item is pressed
6218 */
6219 OO.ui.OptionWidget.prototype.isPressed = function () {
6220 return this.pressed;
6221 };
6222
6223 /**
6224 * Set the option’s selected state. In general, all modifications to the selection
6225 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
6226 * method instead of this method.
6227 *
6228 * @param {boolean} [state=false] Select option
6229 * @chainable
6230 */
6231 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
6232 if ( this.constructor.static.selectable ) {
6233 this.selected = !!state;
6234 this.$element
6235 .toggleClass( 'oo-ui-optionWidget-selected', state )
6236 .attr( 'aria-selected', state.toString() );
6237 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
6238 this.scrollElementIntoView();
6239 }
6240 this.updateThemeClasses();
6241 }
6242 return this;
6243 };
6244
6245 /**
6246 * Set the option’s highlighted state. In general, all programmatic
6247 * modifications to the highlight should be handled by the
6248 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
6249 * method instead of this method.
6250 *
6251 * @param {boolean} [state=false] Highlight option
6252 * @chainable
6253 */
6254 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
6255 if ( this.constructor.static.highlightable ) {
6256 this.highlighted = !!state;
6257 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
6258 this.updateThemeClasses();
6259 }
6260 return this;
6261 };
6262
6263 /**
6264 * Set the option’s pressed state. In general, all
6265 * programmatic modifications to the pressed state should be handled by the
6266 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
6267 * method instead of this method.
6268 *
6269 * @param {boolean} [state=false] Press option
6270 * @chainable
6271 */
6272 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
6273 if ( this.constructor.static.pressable ) {
6274 this.pressed = !!state;
6275 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
6276 this.updateThemeClasses();
6277 }
6278 return this;
6279 };
6280
6281 /**
6282 * Get text to match search strings against.
6283 *
6284 * The default implementation returns the label text, but subclasses
6285 * can override this to provide more complex behavior.
6286 *
6287 * @return {string|boolean} String to match search string against
6288 */
6289 OO.ui.OptionWidget.prototype.getMatchText = function () {
6290 var label = this.getLabel();
6291 return typeof label === 'string' ? label : this.$label.text();
6292 };
6293
6294 /**
6295 * A SelectWidget is of a generic selection of options. The OOUI library contains several types of
6296 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
6297 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
6298 * menu selects}.
6299 *
6300 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
6301 * information, please see the [OOUI documentation on MediaWiki][1].
6302 *
6303 * @example
6304 * // Example of a select widget with three options
6305 * var select = new OO.ui.SelectWidget( {
6306 * items: [
6307 * new OO.ui.OptionWidget( {
6308 * data: 'a',
6309 * label: 'Option One',
6310 * } ),
6311 * new OO.ui.OptionWidget( {
6312 * data: 'b',
6313 * label: 'Option Two',
6314 * } ),
6315 * new OO.ui.OptionWidget( {
6316 * data: 'c',
6317 * label: 'Option Three',
6318 * } )
6319 * ]
6320 * } );
6321 * $( 'body' ).append( select.$element );
6322 *
6323 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6324 *
6325 * @abstract
6326 * @class
6327 * @extends OO.ui.Widget
6328 * @mixins OO.ui.mixin.GroupWidget
6329 *
6330 * @constructor
6331 * @param {Object} [config] Configuration options
6332 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
6333 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
6334 * the [OOUI documentation on MediaWiki] [2] for examples.
6335 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6336 */
6337 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
6338 // Configuration initialization
6339 config = config || {};
6340
6341 // Parent constructor
6342 OO.ui.SelectWidget.parent.call( this, config );
6343
6344 // Mixin constructors
6345 OO.ui.mixin.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
6346
6347 // Properties
6348 this.pressed = false;
6349 this.selecting = null;
6350 this.onDocumentMouseUpHandler = this.onDocumentMouseUp.bind( this );
6351 this.onDocumentMouseMoveHandler = this.onDocumentMouseMove.bind( this );
6352 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
6353 this.onDocumentKeyPressHandler = this.onDocumentKeyPress.bind( this );
6354 this.keyPressBuffer = '';
6355 this.keyPressBufferTimer = null;
6356 this.blockMouseOverEvents = 0;
6357
6358 // Events
6359 this.connect( this, {
6360 toggle: 'onToggle'
6361 } );
6362 this.$element.on( {
6363 focusin: this.onFocus.bind( this ),
6364 mousedown: this.onMouseDown.bind( this ),
6365 mouseover: this.onMouseOver.bind( this ),
6366 mouseleave: this.onMouseLeave.bind( this )
6367 } );
6368
6369 // Initialization
6370 this.$element
6371 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
6372 .attr( 'role', 'listbox' );
6373 this.setFocusOwner( this.$element );
6374 if ( Array.isArray( config.items ) ) {
6375 this.addItems( config.items );
6376 }
6377 };
6378
6379 /* Setup */
6380
6381 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
6382 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupWidget );
6383
6384 /* Events */
6385
6386 /**
6387 * @event highlight
6388 *
6389 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
6390 *
6391 * @param {OO.ui.OptionWidget|null} item Highlighted item
6392 */
6393
6394 /**
6395 * @event press
6396 *
6397 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
6398 * pressed state of an option.
6399 *
6400 * @param {OO.ui.OptionWidget|null} item Pressed item
6401 */
6402
6403 /**
6404 * @event select
6405 *
6406 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
6407 *
6408 * @param {OO.ui.OptionWidget|null} item Selected item
6409 */
6410
6411 /**
6412 * @event choose
6413 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
6414 * @param {OO.ui.OptionWidget} item Chosen item
6415 */
6416
6417 /**
6418 * @event add
6419 *
6420 * An `add` event is emitted when options are added to the select with the #addItems method.
6421 *
6422 * @param {OO.ui.OptionWidget[]} items Added items
6423 * @param {number} index Index of insertion point
6424 */
6425
6426 /**
6427 * @event remove
6428 *
6429 * A `remove` event is emitted when options are removed from the select with the #clearItems
6430 * or #removeItems methods.
6431 *
6432 * @param {OO.ui.OptionWidget[]} items Removed items
6433 */
6434
6435 /* Methods */
6436
6437 /**
6438 * Handle focus events
6439 *
6440 * @private
6441 * @param {jQuery.Event} event
6442 */
6443 OO.ui.SelectWidget.prototype.onFocus = function ( event ) {
6444 var item;
6445 if ( event.target === this.$element[ 0 ] ) {
6446 // This widget was focussed, e.g. by the user tabbing to it.
6447 // The styles for focus state depend on one of the items being selected.
6448 if ( !this.findSelectedItem() ) {
6449 item = this.findFirstSelectableItem();
6450 }
6451 } else {
6452 if ( event.target.tabIndex === -1 ) {
6453 // One of the options got focussed (and the event bubbled up here).
6454 // They can't be tabbed to, but they can be activated using accesskeys.
6455 // OptionWidgets and focusable UI elements inside them have tabindex="-1" set.
6456 item = this.findTargetItem( event );
6457 } else {
6458 // There is something actually user-focusable in one of the labels of the options, and the
6459 // user focussed it (e.g. by tabbing to it). Do nothing (especially, don't change the focus).
6460 return;
6461 }
6462 }
6463
6464 if ( item ) {
6465 if ( item.constructor.static.highlightable ) {
6466 this.highlightItem( item );
6467 } else {
6468 this.selectItem( item );
6469 }
6470 }
6471
6472 if ( event.target !== this.$element[ 0 ] ) {
6473 this.$focusOwner.focus();
6474 }
6475 };
6476
6477 /**
6478 * Handle mouse down events.
6479 *
6480 * @private
6481 * @param {jQuery.Event} e Mouse down event
6482 */
6483 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
6484 var item;
6485
6486 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
6487 this.togglePressed( true );
6488 item = this.findTargetItem( e );
6489 if ( item && item.isSelectable() ) {
6490 this.pressItem( item );
6491 this.selecting = item;
6492 this.getElementDocument().addEventListener( 'mouseup', this.onDocumentMouseUpHandler, true );
6493 this.getElementDocument().addEventListener( 'mousemove', this.onDocumentMouseMoveHandler, true );
6494 }
6495 }
6496 return false;
6497 };
6498
6499 /**
6500 * Handle document mouse up events.
6501 *
6502 * @private
6503 * @param {MouseEvent} e Mouse up event
6504 */
6505 OO.ui.SelectWidget.prototype.onDocumentMouseUp = function ( e ) {
6506 var item;
6507
6508 this.togglePressed( false );
6509 if ( !this.selecting ) {
6510 item = this.findTargetItem( e );
6511 if ( item && item.isSelectable() ) {
6512 this.selecting = item;
6513 }
6514 }
6515 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT && this.selecting ) {
6516 this.pressItem( null );
6517 this.chooseItem( this.selecting );
6518 this.selecting = null;
6519 }
6520
6521 this.getElementDocument().removeEventListener( 'mouseup', this.onDocumentMouseUpHandler, true );
6522 this.getElementDocument().removeEventListener( 'mousemove', this.onDocumentMouseMoveHandler, true );
6523
6524 return false;
6525 };
6526
6527 // Deprecated alias since 0.28.3
6528 OO.ui.SelectWidget.prototype.onMouseUp = function () {
6529 OO.ui.warnDeprecation( 'onMouseUp is deprecated, use onDocumentMouseUp instead' );
6530 this.onDocumentMouseUp.apply( this, arguments );
6531 };
6532
6533 /**
6534 * Handle document mouse move events.
6535 *
6536 * @private
6537 * @param {MouseEvent} e Mouse move event
6538 */
6539 OO.ui.SelectWidget.prototype.onDocumentMouseMove = function ( e ) {
6540 var item;
6541
6542 if ( !this.isDisabled() && this.pressed ) {
6543 item = this.findTargetItem( e );
6544 if ( item && item !== this.selecting && item.isSelectable() ) {
6545 this.pressItem( item );
6546 this.selecting = item;
6547 }
6548 }
6549 };
6550
6551 // Deprecated alias since 0.28.3
6552 OO.ui.SelectWidget.prototype.onMouseMove = function () {
6553 OO.ui.warnDeprecation( 'onMouseMove is deprecated, use onDocumentMouseMove instead' );
6554 this.onDocumentMouseMove.apply( this, arguments );
6555 };
6556
6557 /**
6558 * Handle mouse over events.
6559 *
6560 * @private
6561 * @param {jQuery.Event} e Mouse over event
6562 */
6563 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
6564 var item;
6565 if ( this.blockMouseOverEvents ) {
6566 return;
6567 }
6568 if ( !this.isDisabled() ) {
6569 item = this.findTargetItem( e );
6570 this.highlightItem( item && item.isHighlightable() ? item : null );
6571 }
6572 return false;
6573 };
6574
6575 /**
6576 * Handle mouse leave events.
6577 *
6578 * @private
6579 * @param {jQuery.Event} e Mouse over event
6580 */
6581 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
6582 if ( !this.isDisabled() ) {
6583 this.highlightItem( null );
6584 }
6585 return false;
6586 };
6587
6588 /**
6589 * Handle document key down events.
6590 *
6591 * @protected
6592 * @param {KeyboardEvent} e Key down event
6593 */
6594 OO.ui.SelectWidget.prototype.onDocumentKeyDown = function ( e ) {
6595 var nextItem,
6596 handled = false,
6597 currentItem = this.findHighlightedItem() || this.findSelectedItem();
6598
6599 if ( !this.isDisabled() && this.isVisible() ) {
6600 switch ( e.keyCode ) {
6601 case OO.ui.Keys.ENTER:
6602 if ( currentItem && currentItem.constructor.static.highlightable ) {
6603 // Was only highlighted, now let's select it. No-op if already selected.
6604 this.chooseItem( currentItem );
6605 handled = true;
6606 }
6607 break;
6608 case OO.ui.Keys.UP:
6609 case OO.ui.Keys.LEFT:
6610 this.clearKeyPressBuffer();
6611 nextItem = this.findRelativeSelectableItem( currentItem, -1 );
6612 handled = true;
6613 break;
6614 case OO.ui.Keys.DOWN:
6615 case OO.ui.Keys.RIGHT:
6616 this.clearKeyPressBuffer();
6617 nextItem = this.findRelativeSelectableItem( currentItem, 1 );
6618 handled = true;
6619 break;
6620 case OO.ui.Keys.ESCAPE:
6621 case OO.ui.Keys.TAB:
6622 if ( currentItem && currentItem.constructor.static.highlightable ) {
6623 currentItem.setHighlighted( false );
6624 }
6625 this.unbindDocumentKeyDownListener();
6626 this.unbindDocumentKeyPressListener();
6627 // Don't prevent tabbing away / defocusing
6628 handled = false;
6629 break;
6630 }
6631
6632 if ( nextItem ) {
6633 if ( nextItem.constructor.static.highlightable ) {
6634 this.highlightItem( nextItem );
6635 } else {
6636 this.chooseItem( nextItem );
6637 }
6638 this.scrollItemIntoView( nextItem );
6639 }
6640
6641 if ( handled ) {
6642 e.preventDefault();
6643 e.stopPropagation();
6644 }
6645 }
6646 };
6647
6648 // Deprecated alias since 0.28.3
6649 OO.ui.SelectWidget.prototype.onKeyDown = function () {
6650 OO.ui.warnDeprecation( 'onKeyDown is deprecated, use onDocumentKeyDown instead' );
6651 this.onDocumentKeyDown.apply( this, arguments );
6652 };
6653
6654 /**
6655 * Bind document key down listener.
6656 *
6657 * @protected
6658 */
6659 OO.ui.SelectWidget.prototype.bindDocumentKeyDownListener = function () {
6660 this.getElementDocument().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
6661 };
6662
6663 // Deprecated alias since 0.28.3
6664 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
6665 OO.ui.warnDeprecation( 'bindKeyDownListener is deprecated, use bindDocumentKeyDownListener instead' );
6666 this.bindDocumentKeyDownListener.apply( this, arguments );
6667 };
6668
6669 /**
6670 * Unbind document key down listener.
6671 *
6672 * @protected
6673 */
6674 OO.ui.SelectWidget.prototype.unbindDocumentKeyDownListener = function () {
6675 this.getElementDocument().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
6676 };
6677
6678 // Deprecated alias since 0.28.3
6679 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
6680 OO.ui.warnDeprecation( 'unbindKeyDownListener is deprecated, use unbindDocumentKeyDownListener instead' );
6681 this.unbindDocumentKeyDownListener.apply( this, arguments );
6682 };
6683
6684 /**
6685 * Scroll item into view, preventing spurious mouse highlight actions from happening.
6686 *
6687 * @param {OO.ui.OptionWidget} item Item to scroll into view
6688 */
6689 OO.ui.SelectWidget.prototype.scrollItemIntoView = function ( item ) {
6690 var widget = this;
6691 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling
6692 // and around 100-150 ms after it is finished.
6693 this.blockMouseOverEvents++;
6694 item.scrollElementIntoView().done( function () {
6695 setTimeout( function () {
6696 widget.blockMouseOverEvents--;
6697 }, 200 );
6698 } );
6699 };
6700
6701 /**
6702 * Clear the key-press buffer
6703 *
6704 * @protected
6705 */
6706 OO.ui.SelectWidget.prototype.clearKeyPressBuffer = function () {
6707 if ( this.keyPressBufferTimer ) {
6708 clearTimeout( this.keyPressBufferTimer );
6709 this.keyPressBufferTimer = null;
6710 }
6711 this.keyPressBuffer = '';
6712 };
6713
6714 /**
6715 * Handle key press events.
6716 *
6717 * @protected
6718 * @param {KeyboardEvent} e Key press event
6719 */
6720 OO.ui.SelectWidget.prototype.onDocumentKeyPress = function ( e ) {
6721 var c, filter, item;
6722
6723 if ( !e.charCode ) {
6724 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.keyPressBuffer !== '' ) {
6725 this.keyPressBuffer = this.keyPressBuffer.substr( 0, this.keyPressBuffer.length - 1 );
6726 return false;
6727 }
6728 return;
6729 }
6730 if ( String.fromCodePoint ) {
6731 c = String.fromCodePoint( e.charCode );
6732 } else {
6733 c = String.fromCharCode( e.charCode );
6734 }
6735
6736 if ( this.keyPressBufferTimer ) {
6737 clearTimeout( this.keyPressBufferTimer );
6738 }
6739 this.keyPressBufferTimer = setTimeout( this.clearKeyPressBuffer.bind( this ), 1500 );
6740
6741 item = this.findHighlightedItem() || this.findSelectedItem();
6742
6743 if ( this.keyPressBuffer === c ) {
6744 // Common (if weird) special case: typing "xxxx" will cycle through all
6745 // the items beginning with "x".
6746 if ( item ) {
6747 item = this.findRelativeSelectableItem( item, 1 );
6748 }
6749 } else {
6750 this.keyPressBuffer += c;
6751 }
6752
6753 filter = this.getItemMatcher( this.keyPressBuffer, false );
6754 if ( !item || !filter( item ) ) {
6755 item = this.findRelativeSelectableItem( item, 1, filter );
6756 }
6757 if ( item ) {
6758 if ( this.isVisible() && item.constructor.static.highlightable ) {
6759 this.highlightItem( item );
6760 } else {
6761 this.chooseItem( item );
6762 }
6763 this.scrollItemIntoView( item );
6764 }
6765
6766 e.preventDefault();
6767 e.stopPropagation();
6768 };
6769
6770 // Deprecated alias since 0.28.3
6771 OO.ui.SelectWidget.prototype.onKeyPress = function () {
6772 OO.ui.warnDeprecation( 'onKeyPress is deprecated, use onDocumentKeyPress instead' );
6773 this.onDocumentKeyPress.apply( this, arguments );
6774 };
6775
6776 /**
6777 * Get a matcher for the specific string
6778 *
6779 * @protected
6780 * @param {string} s String to match against items
6781 * @param {boolean} [exact=false] Only accept exact matches
6782 * @return {Function} function ( OO.ui.OptionWidget ) => boolean
6783 */
6784 OO.ui.SelectWidget.prototype.getItemMatcher = function ( s, exact ) {
6785 var re;
6786
6787 if ( s.normalize ) {
6788 s = s.normalize();
6789 }
6790 s = exact ? s.trim() : s.replace( /^\s+/, '' );
6791 re = '^\\s*' + s.replace( /([\\{}()|.?*+\-^$[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
6792 if ( exact ) {
6793 re += '\\s*$';
6794 }
6795 re = new RegExp( re, 'i' );
6796 return function ( item ) {
6797 var matchText = item.getMatchText();
6798 if ( matchText.normalize ) {
6799 matchText = matchText.normalize();
6800 }
6801 return re.test( matchText );
6802 };
6803 };
6804
6805 /**
6806 * Bind document key press listener.
6807 *
6808 * @protected
6809 */
6810 OO.ui.SelectWidget.prototype.bindDocumentKeyPressListener = function () {
6811 this.getElementDocument().addEventListener( 'keypress', this.onDocumentKeyPressHandler, true );
6812 };
6813
6814 // Deprecated alias since 0.28.3
6815 OO.ui.SelectWidget.prototype.bindKeyPressListener = function () {
6816 OO.ui.warnDeprecation( 'bindKeyPressListener is deprecated, use bindDocumentKeyPressListener instead' );
6817 this.bindDocumentKeyPressListener.apply( this, arguments );
6818 };
6819
6820 /**
6821 * Unbind document key down listener.
6822 *
6823 * If you override this, be sure to call this.clearKeyPressBuffer() from your
6824 * implementation.
6825 *
6826 * @protected
6827 */
6828 OO.ui.SelectWidget.prototype.unbindDocumentKeyPressListener = function () {
6829 this.getElementDocument().removeEventListener( 'keypress', this.onDocumentKeyPressHandler, true );
6830 this.clearKeyPressBuffer();
6831 };
6832
6833 // Deprecated alias since 0.28.3
6834 OO.ui.SelectWidget.prototype.unbindKeyPressListener = function () {
6835 OO.ui.warnDeprecation( 'unbindKeyPressListener is deprecated, use unbindDocumentKeyPressListener instead' );
6836 this.unbindDocumentKeyPressListener.apply( this, arguments );
6837 };
6838
6839 /**
6840 * Visibility change handler
6841 *
6842 * @protected
6843 * @param {boolean} visible
6844 */
6845 OO.ui.SelectWidget.prototype.onToggle = function ( visible ) {
6846 if ( !visible ) {
6847 this.clearKeyPressBuffer();
6848 }
6849 };
6850
6851 /**
6852 * Get the closest item to a jQuery.Event.
6853 *
6854 * @private
6855 * @param {jQuery.Event} e
6856 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
6857 */
6858 OO.ui.SelectWidget.prototype.findTargetItem = function ( e ) {
6859 var $option = $( e.target ).closest( '.oo-ui-optionWidget' );
6860 if ( !$option.closest( '.oo-ui-selectWidget' ).is( this.$element ) ) {
6861 return null;
6862 }
6863 return $option.data( 'oo-ui-optionWidget' ) || null;
6864 };
6865
6866 /**
6867 * Find selected item.
6868 *
6869 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
6870 */
6871 OO.ui.SelectWidget.prototype.findSelectedItem = function () {
6872 var i, len;
6873
6874 for ( i = 0, len = this.items.length; i < len; i++ ) {
6875 if ( this.items[ i ].isSelected() ) {
6876 return this.items[ i ];
6877 }
6878 }
6879 return null;
6880 };
6881
6882 /**
6883 * Find highlighted item.
6884 *
6885 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
6886 */
6887 OO.ui.SelectWidget.prototype.findHighlightedItem = function () {
6888 var i, len;
6889
6890 for ( i = 0, len = this.items.length; i < len; i++ ) {
6891 if ( this.items[ i ].isHighlighted() ) {
6892 return this.items[ i ];
6893 }
6894 }
6895 return null;
6896 };
6897
6898 /**
6899 * Toggle pressed state.
6900 *
6901 * Press is a state that occurs when a user mouses down on an item, but
6902 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
6903 * until the user releases the mouse.
6904 *
6905 * @param {boolean} pressed An option is being pressed
6906 */
6907 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
6908 if ( pressed === undefined ) {
6909 pressed = !this.pressed;
6910 }
6911 if ( pressed !== this.pressed ) {
6912 this.$element
6913 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
6914 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
6915 this.pressed = pressed;
6916 }
6917 };
6918
6919 /**
6920 * Highlight an option. If the `item` param is omitted, no options will be highlighted
6921 * and any existing highlight will be removed. The highlight is mutually exclusive.
6922 *
6923 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
6924 * @fires highlight
6925 * @chainable
6926 */
6927 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
6928 var i, len, highlighted,
6929 changed = false;
6930
6931 for ( i = 0, len = this.items.length; i < len; i++ ) {
6932 highlighted = this.items[ i ] === item;
6933 if ( this.items[ i ].isHighlighted() !== highlighted ) {
6934 this.items[ i ].setHighlighted( highlighted );
6935 changed = true;
6936 }
6937 }
6938 if ( changed ) {
6939 if ( item ) {
6940 this.$focusOwner.attr( 'aria-activedescendant', item.getElementId() );
6941 } else {
6942 this.$focusOwner.removeAttr( 'aria-activedescendant' );
6943 }
6944 this.emit( 'highlight', item );
6945 }
6946
6947 return this;
6948 };
6949
6950 /**
6951 * Fetch an item by its label.
6952 *
6953 * @param {string} label Label of the item to select.
6954 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
6955 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
6956 */
6957 OO.ui.SelectWidget.prototype.getItemFromLabel = function ( label, prefix ) {
6958 var i, item, found,
6959 len = this.items.length,
6960 filter = this.getItemMatcher( label, true );
6961
6962 for ( i = 0; i < len; i++ ) {
6963 item = this.items[ i ];
6964 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
6965 return item;
6966 }
6967 }
6968
6969 if ( prefix ) {
6970 found = null;
6971 filter = this.getItemMatcher( label, false );
6972 for ( i = 0; i < len; i++ ) {
6973 item = this.items[ i ];
6974 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
6975 if ( found ) {
6976 return null;
6977 }
6978 found = item;
6979 }
6980 }
6981 if ( found ) {
6982 return found;
6983 }
6984 }
6985
6986 return null;
6987 };
6988
6989 /**
6990 * Programmatically select an option by its label. If the item does not exist,
6991 * all options will be deselected.
6992 *
6993 * @param {string} [label] Label of the item to select.
6994 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
6995 * @fires select
6996 * @chainable
6997 */
6998 OO.ui.SelectWidget.prototype.selectItemByLabel = function ( label, prefix ) {
6999 var itemFromLabel = this.getItemFromLabel( label, !!prefix );
7000 if ( label === undefined || !itemFromLabel ) {
7001 return this.selectItem();
7002 }
7003 return this.selectItem( itemFromLabel );
7004 };
7005
7006 /**
7007 * Programmatically select an option by its data. If the `data` parameter is omitted,
7008 * or if the item does not exist, all options will be deselected.
7009 *
7010 * @param {Object|string} [data] Value of the item to select, omit to deselect all
7011 * @fires select
7012 * @chainable
7013 */
7014 OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) {
7015 var itemFromData = this.findItemFromData( data );
7016 if ( data === undefined || !itemFromData ) {
7017 return this.selectItem();
7018 }
7019 return this.selectItem( itemFromData );
7020 };
7021
7022 /**
7023 * Programmatically select an option by its reference. If the `item` parameter is omitted,
7024 * all options will be deselected.
7025 *
7026 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
7027 * @fires select
7028 * @chainable
7029 */
7030 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
7031 var i, len, selected,
7032 changed = false;
7033
7034 for ( i = 0, len = this.items.length; i < len; i++ ) {
7035 selected = this.items[ i ] === item;
7036 if ( this.items[ i ].isSelected() !== selected ) {
7037 this.items[ i ].setSelected( selected );
7038 changed = true;
7039 }
7040 }
7041 if ( changed ) {
7042 if ( item && !item.constructor.static.highlightable ) {
7043 if ( item ) {
7044 this.$focusOwner.attr( 'aria-activedescendant', item.getElementId() );
7045 } else {
7046 this.$focusOwner.removeAttr( 'aria-activedescendant' );
7047 }
7048 }
7049 this.emit( 'select', item );
7050 }
7051
7052 return this;
7053 };
7054
7055 /**
7056 * Press an item.
7057 *
7058 * Press is a state that occurs when a user mouses down on an item, but has not
7059 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
7060 * releases the mouse.
7061 *
7062 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
7063 * @fires press
7064 * @chainable
7065 */
7066 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
7067 var i, len, pressed,
7068 changed = false;
7069
7070 for ( i = 0, len = this.items.length; i < len; i++ ) {
7071 pressed = this.items[ i ] === item;
7072 if ( this.items[ i ].isPressed() !== pressed ) {
7073 this.items[ i ].setPressed( pressed );
7074 changed = true;
7075 }
7076 }
7077 if ( changed ) {
7078 this.emit( 'press', item );
7079 }
7080
7081 return this;
7082 };
7083
7084 /**
7085 * Choose an item.
7086 *
7087 * Note that ‘choose’ should never be modified programmatically. A user can choose
7088 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
7089 * use the #selectItem method.
7090 *
7091 * This method is identical to #selectItem, but may vary in subclasses that take additional action
7092 * when users choose an item with the keyboard or mouse.
7093 *
7094 * @param {OO.ui.OptionWidget} item Item to choose
7095 * @fires choose
7096 * @chainable
7097 */
7098 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
7099 if ( item ) {
7100 this.selectItem( item );
7101 this.emit( 'choose', item );
7102 }
7103
7104 return this;
7105 };
7106
7107 /**
7108 * Find an option by its position relative to the specified item (or to the start of the option array,
7109 * if item is `null`). The direction in which to search through the option array is specified with a
7110 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
7111 * `null` if there are no options in the array.
7112 *
7113 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
7114 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
7115 * @param {Function} [filter] Only consider items for which this function returns
7116 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
7117 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
7118 */
7119 OO.ui.SelectWidget.prototype.findRelativeSelectableItem = function ( item, direction, filter ) {
7120 var currentIndex, nextIndex, i,
7121 increase = direction > 0 ? 1 : -1,
7122 len = this.items.length;
7123
7124 if ( item instanceof OO.ui.OptionWidget ) {
7125 currentIndex = this.items.indexOf( item );
7126 nextIndex = ( currentIndex + increase + len ) % len;
7127 } else {
7128 // If no item is selected and moving forward, start at the beginning.
7129 // If moving backward, start at the end.
7130 nextIndex = direction > 0 ? 0 : len - 1;
7131 }
7132
7133 for ( i = 0; i < len; i++ ) {
7134 item = this.items[ nextIndex ];
7135 if (
7136 item instanceof OO.ui.OptionWidget && item.isSelectable() &&
7137 ( !filter || filter( item ) )
7138 ) {
7139 return item;
7140 }
7141 nextIndex = ( nextIndex + increase + len ) % len;
7142 }
7143 return null;
7144 };
7145
7146 /**
7147 * Find the next selectable item or `null` if there are no selectable items.
7148 * Disabled options and menu-section markers and breaks are not selectable.
7149 *
7150 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
7151 */
7152 OO.ui.SelectWidget.prototype.findFirstSelectableItem = function () {
7153 return this.findRelativeSelectableItem( null, 1 );
7154 };
7155
7156 /**
7157 * Add an array of options to the select. Optionally, an index number can be used to
7158 * specify an insertion point.
7159 *
7160 * @param {OO.ui.OptionWidget[]} items Items to add
7161 * @param {number} [index] Index to insert items after
7162 * @fires add
7163 * @chainable
7164 */
7165 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
7166 // Mixin method
7167 OO.ui.mixin.GroupWidget.prototype.addItems.call( this, items, index );
7168
7169 // Always provide an index, even if it was omitted
7170 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
7171
7172 return this;
7173 };
7174
7175 /**
7176 * Remove the specified array of options from the select. Options will be detached
7177 * from the DOM, not removed, so they can be reused later. To remove all options from
7178 * the select, you may wish to use the #clearItems method instead.
7179 *
7180 * @param {OO.ui.OptionWidget[]} items Items to remove
7181 * @fires remove
7182 * @chainable
7183 */
7184 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
7185 var i, len, item;
7186
7187 // Deselect items being removed
7188 for ( i = 0, len = items.length; i < len; i++ ) {
7189 item = items[ i ];
7190 if ( item.isSelected() ) {
7191 this.selectItem( null );
7192 }
7193 }
7194
7195 // Mixin method
7196 OO.ui.mixin.GroupWidget.prototype.removeItems.call( this, items );
7197
7198 this.emit( 'remove', items );
7199
7200 return this;
7201 };
7202
7203 /**
7204 * Clear all options from the select. Options will be detached from the DOM, not removed,
7205 * so that they can be reused later. To remove a subset of options from the select, use
7206 * the #removeItems method.
7207 *
7208 * @fires remove
7209 * @chainable
7210 */
7211 OO.ui.SelectWidget.prototype.clearItems = function () {
7212 var items = this.items.slice();
7213
7214 // Mixin method
7215 OO.ui.mixin.GroupWidget.prototype.clearItems.call( this );
7216
7217 // Clear selection
7218 this.selectItem( null );
7219
7220 this.emit( 'remove', items );
7221
7222 return this;
7223 };
7224
7225 /**
7226 * Set the DOM element which has focus while the user is interacting with this SelectWidget.
7227 *
7228 * Currently this is just used to set `aria-activedescendant` on it.
7229 *
7230 * @protected
7231 * @param {jQuery} $focusOwner
7232 */
7233 OO.ui.SelectWidget.prototype.setFocusOwner = function ( $focusOwner ) {
7234 this.$focusOwner = $focusOwner;
7235 };
7236
7237 /**
7238 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
7239 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
7240 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
7241 * options. For more information about options and selects, please see the
7242 * [OOUI documentation on MediaWiki][1].
7243 *
7244 * @example
7245 * // Decorated options in a select widget
7246 * var select = new OO.ui.SelectWidget( {
7247 * items: [
7248 * new OO.ui.DecoratedOptionWidget( {
7249 * data: 'a',
7250 * label: 'Option with icon',
7251 * icon: 'help'
7252 * } ),
7253 * new OO.ui.DecoratedOptionWidget( {
7254 * data: 'b',
7255 * label: 'Option with indicator',
7256 * indicator: 'next'
7257 * } )
7258 * ]
7259 * } );
7260 * $( 'body' ).append( select.$element );
7261 *
7262 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7263 *
7264 * @class
7265 * @extends OO.ui.OptionWidget
7266 * @mixins OO.ui.mixin.IconElement
7267 * @mixins OO.ui.mixin.IndicatorElement
7268 *
7269 * @constructor
7270 * @param {Object} [config] Configuration options
7271 */
7272 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
7273 // Parent constructor
7274 OO.ui.DecoratedOptionWidget.parent.call( this, config );
7275
7276 // Mixin constructors
7277 OO.ui.mixin.IconElement.call( this, config );
7278 OO.ui.mixin.IndicatorElement.call( this, config );
7279
7280 // Initialization
7281 this.$element
7282 .addClass( 'oo-ui-decoratedOptionWidget' )
7283 .prepend( this.$icon )
7284 .append( this.$indicator );
7285 };
7286
7287 /* Setup */
7288
7289 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
7290 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IconElement );
7291 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IndicatorElement );
7292
7293 /**
7294 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
7295 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
7296 * the [OOUI documentation on MediaWiki] [1] for more information.
7297 *
7298 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
7299 *
7300 * @class
7301 * @extends OO.ui.DecoratedOptionWidget
7302 *
7303 * @constructor
7304 * @param {Object} [config] Configuration options
7305 */
7306 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
7307 // Parent constructor
7308 OO.ui.MenuOptionWidget.parent.call( this, config );
7309
7310 // Properties
7311 this.checkIcon = new OO.ui.IconWidget( {
7312 icon: 'check',
7313 classes: [ 'oo-ui-menuOptionWidget-checkIcon' ]
7314 } );
7315
7316 // Initialization
7317 this.$element
7318 .prepend( this.checkIcon.$element )
7319 .addClass( 'oo-ui-menuOptionWidget' );
7320 };
7321
7322 /* Setup */
7323
7324 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
7325
7326 /* Static Properties */
7327
7328 /**
7329 * @static
7330 * @inheritdoc
7331 */
7332 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
7333
7334 /**
7335 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
7336 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
7337 *
7338 * @example
7339 * var myDropdown = new OO.ui.DropdownWidget( {
7340 * menu: {
7341 * items: [
7342 * new OO.ui.MenuSectionOptionWidget( {
7343 * label: 'Dogs'
7344 * } ),
7345 * new OO.ui.MenuOptionWidget( {
7346 * data: 'corgi',
7347 * label: 'Welsh Corgi'
7348 * } ),
7349 * new OO.ui.MenuOptionWidget( {
7350 * data: 'poodle',
7351 * label: 'Standard Poodle'
7352 * } ),
7353 * new OO.ui.MenuSectionOptionWidget( {
7354 * label: 'Cats'
7355 * } ),
7356 * new OO.ui.MenuOptionWidget( {
7357 * data: 'lion',
7358 * label: 'Lion'
7359 * } )
7360 * ]
7361 * }
7362 * } );
7363 * $( 'body' ).append( myDropdown.$element );
7364 *
7365 * @class
7366 * @extends OO.ui.DecoratedOptionWidget
7367 *
7368 * @constructor
7369 * @param {Object} [config] Configuration options
7370 */
7371 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
7372 // Parent constructor
7373 OO.ui.MenuSectionOptionWidget.parent.call( this, config );
7374
7375 // Initialization
7376 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' )
7377 .removeAttr( 'role aria-selected' );
7378 };
7379
7380 /* Setup */
7381
7382 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
7383
7384 /* Static Properties */
7385
7386 /**
7387 * @static
7388 * @inheritdoc
7389 */
7390 OO.ui.MenuSectionOptionWidget.static.selectable = false;
7391
7392 /**
7393 * @static
7394 * @inheritdoc
7395 */
7396 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
7397
7398 /**
7399 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
7400 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
7401 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
7402 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
7403 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
7404 * and customized to be opened, closed, and displayed as needed.
7405 *
7406 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
7407 * mouse outside the menu.
7408 *
7409 * Menus also have support for keyboard interaction:
7410 *
7411 * - Enter/Return key: choose and select a menu option
7412 * - Up-arrow key: highlight the previous menu option
7413 * - Down-arrow key: highlight the next menu option
7414 * - Esc key: hide the menu
7415 *
7416 * Unlike most widgets, MenuSelectWidget is initially hidden and must be shown by calling #toggle.
7417 *
7418 * Please see the [OOUI documentation on MediaWiki][1] for more information.
7419 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7420 *
7421 * @class
7422 * @extends OO.ui.SelectWidget
7423 * @mixins OO.ui.mixin.ClippableElement
7424 * @mixins OO.ui.mixin.FloatableElement
7425 *
7426 * @constructor
7427 * @param {Object} [config] Configuration options
7428 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
7429 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
7430 * and {@link OO.ui.mixin.LookupElement LookupElement}
7431 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
7432 * the text the user types. This config is used by {@link OO.ui.TagMultiselectWidget TagMultiselectWidget}
7433 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
7434 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
7435 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
7436 * that button, unless the button (or its parent widget) is passed in here.
7437 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
7438 * @cfg {jQuery} [$autoCloseIgnore] If these elements are clicked, don't auto-hide the menu.
7439 * @cfg {boolean} [hideOnChoose=true] Hide the menu when the user chooses an option.
7440 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
7441 * @cfg {boolean} [highlightOnFilter] Highlight the first result when filtering
7442 * @cfg {number} [width] Width of the menu
7443 */
7444 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
7445 // Configuration initialization
7446 config = config || {};
7447
7448 // Parent constructor
7449 OO.ui.MenuSelectWidget.parent.call( this, config );
7450
7451 // Mixin constructors
7452 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
7453 OO.ui.mixin.FloatableElement.call( this, config );
7454
7455 // Initial vertical positions other than 'center' will result in
7456 // the menu being flipped if there is not enough space in the container.
7457 // Store the original position so we know what to reset to.
7458 this.originalVerticalPosition = this.verticalPosition;
7459
7460 // Properties
7461 this.autoHide = config.autoHide === undefined || !!config.autoHide;
7462 this.hideOnChoose = config.hideOnChoose === undefined || !!config.hideOnChoose;
7463 this.filterFromInput = !!config.filterFromInput;
7464 this.$input = config.$input ? config.$input : config.input ? config.input.$input : null;
7465 this.$widget = config.widget ? config.widget.$element : null;
7466 this.$autoCloseIgnore = config.$autoCloseIgnore || $( [] );
7467 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
7468 this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 );
7469 this.highlightOnFilter = !!config.highlightOnFilter;
7470 this.width = config.width;
7471
7472 // Initialization
7473 this.$element.addClass( 'oo-ui-menuSelectWidget' );
7474 if ( config.widget ) {
7475 this.setFocusOwner( config.widget.$tabIndexed );
7476 }
7477
7478 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
7479 // that reference properties not initialized at that time of parent class construction
7480 // TODO: Find a better way to handle post-constructor setup
7481 this.visible = false;
7482 this.$element.addClass( 'oo-ui-element-hidden' );
7483 };
7484
7485 /* Setup */
7486
7487 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
7488 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement );
7489 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.FloatableElement );
7490
7491 /* Events */
7492
7493 /**
7494 * @event ready
7495 *
7496 * The menu is ready: it is visible and has been positioned and clipped.
7497 */
7498
7499 /* Static properties */
7500
7501 /**
7502 * Positions to flip to if there isn't room in the container for the
7503 * menu in a specific direction.
7504 *
7505 * @property {Object.<string,string>}
7506 */
7507 OO.ui.MenuSelectWidget.static.flippedPositions = {
7508 below: 'above',
7509 above: 'below',
7510 top: 'bottom',
7511 bottom: 'top'
7512 };
7513
7514 /* Methods */
7515
7516 /**
7517 * Handles document mouse down events.
7518 *
7519 * @protected
7520 * @param {MouseEvent} e Mouse down event
7521 */
7522 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
7523 if (
7524 this.isVisible() &&
7525 !OO.ui.contains(
7526 this.$element.add( this.$widget ).add( this.$autoCloseIgnore ).get(),
7527 e.target,
7528 true
7529 )
7530 ) {
7531 this.toggle( false );
7532 }
7533 };
7534
7535 /**
7536 * @inheritdoc
7537 */
7538 OO.ui.MenuSelectWidget.prototype.onDocumentKeyDown = function ( e ) {
7539 var currentItem = this.findHighlightedItem() || this.findSelectedItem();
7540
7541 if ( !this.isDisabled() && this.isVisible() ) {
7542 switch ( e.keyCode ) {
7543 case OO.ui.Keys.LEFT:
7544 case OO.ui.Keys.RIGHT:
7545 // Do nothing if a text field is associated, arrow keys will be handled natively
7546 if ( !this.$input ) {
7547 OO.ui.MenuSelectWidget.parent.prototype.onDocumentKeyDown.call( this, e );
7548 }
7549 break;
7550 case OO.ui.Keys.ESCAPE:
7551 case OO.ui.Keys.TAB:
7552 if ( currentItem ) {
7553 currentItem.setHighlighted( false );
7554 }
7555 this.toggle( false );
7556 // Don't prevent tabbing away, prevent defocusing
7557 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
7558 e.preventDefault();
7559 e.stopPropagation();
7560 }
7561 break;
7562 default:
7563 OO.ui.MenuSelectWidget.parent.prototype.onDocumentKeyDown.call( this, e );
7564 return;
7565 }
7566 }
7567 };
7568
7569 /**
7570 * Update menu item visibility and clipping after input changes (if filterFromInput is enabled)
7571 * or after items were added/removed (always).
7572 *
7573 * @protected
7574 */
7575 OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () {
7576 var i, item, items, visible, section, sectionEmpty, filter, exactFilter,
7577 anyVisible = false,
7578 len = this.items.length,
7579 showAll = !this.isVisible(),
7580 exactMatch = false;
7581
7582 if ( this.$input && this.filterFromInput ) {
7583 filter = showAll ? null : this.getItemMatcher( this.$input.val() );
7584 exactFilter = this.getItemMatcher( this.$input.val(), true );
7585 // Hide non-matching options, and also hide section headers if all options
7586 // in their section are hidden.
7587 for ( i = 0; i < len; i++ ) {
7588 item = this.items[ i ];
7589 if ( item instanceof OO.ui.MenuSectionOptionWidget ) {
7590 if ( section ) {
7591 // If the previous section was empty, hide its header
7592 section.toggle( showAll || !sectionEmpty );
7593 }
7594 section = item;
7595 sectionEmpty = true;
7596 } else if ( item instanceof OO.ui.OptionWidget ) {
7597 visible = showAll || filter( item );
7598 exactMatch = exactMatch || exactFilter( item );
7599 anyVisible = anyVisible || visible;
7600 sectionEmpty = sectionEmpty && !visible;
7601 item.toggle( visible );
7602 }
7603 }
7604 // Process the final section
7605 if ( section ) {
7606 section.toggle( showAll || !sectionEmpty );
7607 }
7608
7609 if ( anyVisible && this.items.length && !exactMatch ) {
7610 this.scrollItemIntoView( this.items[ 0 ] );
7611 }
7612
7613 this.$element.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible );
7614
7615 if ( this.highlightOnFilter ) {
7616 // Highlight the first item on the list
7617 item = null;
7618 items = this.getItems();
7619 for ( i = 0; i < items.length; i++ ) {
7620 if ( items[ i ].isVisible() ) {
7621 item = items[ i ];
7622 break;
7623 }
7624 }
7625 this.highlightItem( item );
7626 }
7627
7628 }
7629
7630 // Reevaluate clipping
7631 this.clip();
7632 };
7633
7634 /**
7635 * @inheritdoc
7636 */
7637 OO.ui.MenuSelectWidget.prototype.bindDocumentKeyDownListener = function () {
7638 if ( this.$input ) {
7639 this.$input.on( 'keydown', this.onDocumentKeyDownHandler );
7640 } else {
7641 OO.ui.MenuSelectWidget.parent.prototype.bindDocumentKeyDownListener.call( this );
7642 }
7643 };
7644
7645 /**
7646 * @inheritdoc
7647 */
7648 OO.ui.MenuSelectWidget.prototype.unbindDocumentKeyDownListener = function () {
7649 if ( this.$input ) {
7650 this.$input.off( 'keydown', this.onDocumentKeyDownHandler );
7651 } else {
7652 OO.ui.MenuSelectWidget.parent.prototype.unbindDocumentKeyDownListener.call( this );
7653 }
7654 };
7655
7656 /**
7657 * @inheritdoc
7658 */
7659 OO.ui.MenuSelectWidget.prototype.bindDocumentKeyPressListener = function () {
7660 if ( this.$input ) {
7661 if ( this.filterFromInput ) {
7662 this.$input.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
7663 this.updateItemVisibility();
7664 }
7665 } else {
7666 OO.ui.MenuSelectWidget.parent.prototype.bindDocumentKeyPressListener.call( this );
7667 }
7668 };
7669
7670 /**
7671 * @inheritdoc
7672 */
7673 OO.ui.MenuSelectWidget.prototype.unbindDocumentKeyPressListener = function () {
7674 if ( this.$input ) {
7675 if ( this.filterFromInput ) {
7676 this.$input.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
7677 this.updateItemVisibility();
7678 }
7679 } else {
7680 OO.ui.MenuSelectWidget.parent.prototype.unbindDocumentKeyPressListener.call( this );
7681 }
7682 };
7683
7684 /**
7685 * Choose an item.
7686 *
7687 * When a user chooses an item, the menu is closed, unless the hideOnChoose config option is set to false.
7688 *
7689 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
7690 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
7691 *
7692 * @param {OO.ui.OptionWidget} item Item to choose
7693 * @chainable
7694 */
7695 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
7696 OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item );
7697 if ( this.hideOnChoose ) {
7698 this.toggle( false );
7699 }
7700 return this;
7701 };
7702
7703 /**
7704 * @inheritdoc
7705 */
7706 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
7707 // Parent method
7708 OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index );
7709
7710 this.updateItemVisibility();
7711
7712 return this;
7713 };
7714
7715 /**
7716 * @inheritdoc
7717 */
7718 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
7719 // Parent method
7720 OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items );
7721
7722 this.updateItemVisibility();
7723
7724 return this;
7725 };
7726
7727 /**
7728 * @inheritdoc
7729 */
7730 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
7731 // Parent method
7732 OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this );
7733
7734 this.updateItemVisibility();
7735
7736 return this;
7737 };
7738
7739 /**
7740 * Toggle visibility of the menu. The menu is initially hidden and must be shown by calling
7741 * `.toggle( true )` after its #$element is attached to the DOM.
7742 *
7743 * Do not show the menu while it is not attached to the DOM. The calculations required to display
7744 * it in the right place and with the right dimensions only work correctly while it is attached.
7745 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
7746 * strictly enforced, so currently it only generates a warning in the browser console.
7747 *
7748 * @fires ready
7749 * @inheritdoc
7750 */
7751 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
7752 var change, originalHeight, flippedHeight;
7753
7754 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
7755 change = visible !== this.isVisible();
7756
7757 if ( visible && !this.warnedUnattached && !this.isElementAttached() ) {
7758 OO.ui.warnDeprecation( 'MenuSelectWidget#toggle: Before calling this method, the menu must be attached to the DOM.' );
7759 this.warnedUnattached = true;
7760 }
7761
7762 if ( change && visible ) {
7763 // Reset position before showing the popup again. It's possible we no longer need to flip
7764 // (e.g. if the user scrolled).
7765 this.setVerticalPosition( this.originalVerticalPosition );
7766 }
7767
7768 // Parent method
7769 OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible );
7770
7771 if ( change ) {
7772 if ( visible ) {
7773
7774 if ( this.width ) {
7775 this.setIdealSize( this.width );
7776 } else if ( this.$floatableContainer ) {
7777 this.$clippable.css( 'width', 'auto' );
7778 this.setIdealSize(
7779 this.$floatableContainer[ 0 ].offsetWidth > this.$clippable[ 0 ].offsetWidth ?
7780 // Dropdown is smaller than handle so expand to width
7781 this.$floatableContainer[ 0 ].offsetWidth :
7782 // Dropdown is larger than handle so auto size
7783 'auto'
7784 );
7785 this.$clippable.css( 'width', '' );
7786 }
7787
7788 this.togglePositioning( !!this.$floatableContainer );
7789 this.toggleClipping( true );
7790
7791 this.bindDocumentKeyDownListener();
7792 this.bindDocumentKeyPressListener();
7793
7794 if (
7795 ( this.isClippedVertically() || this.isFloatableOutOfView() ) &&
7796 this.originalVerticalPosition !== 'center'
7797 ) {
7798 // If opening the menu in one direction causes it to be clipped, flip it
7799 originalHeight = this.$element.height();
7800 this.setVerticalPosition(
7801 this.constructor.static.flippedPositions[ this.originalVerticalPosition ]
7802 );
7803 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
7804 // If flipping also causes it to be clipped, open in whichever direction
7805 // we have more space
7806 flippedHeight = this.$element.height();
7807 if ( originalHeight > flippedHeight ) {
7808 this.setVerticalPosition( this.originalVerticalPosition );
7809 }
7810 }
7811 }
7812 // Note that we do not flip the menu's opening direction if the clipping changes
7813 // later (e.g. after the user scrolls), that seems like it would be annoying
7814
7815 this.$focusOwner.attr( 'aria-expanded', 'true' );
7816
7817 if ( this.findSelectedItem() ) {
7818 this.$focusOwner.attr( 'aria-activedescendant', this.findSelectedItem().getElementId() );
7819 this.findSelectedItem().scrollElementIntoView( { duration: 0 } );
7820 }
7821
7822 // Auto-hide
7823 if ( this.autoHide ) {
7824 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
7825 }
7826
7827 this.emit( 'ready' );
7828 } else {
7829 this.$focusOwner.removeAttr( 'aria-activedescendant' );
7830 this.unbindDocumentKeyDownListener();
7831 this.unbindDocumentKeyPressListener();
7832 this.$focusOwner.attr( 'aria-expanded', 'false' );
7833 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
7834 this.togglePositioning( false );
7835 this.toggleClipping( false );
7836 }
7837 }
7838
7839 return this;
7840 };
7841
7842 /**
7843 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
7844 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
7845 * users can interact with it.
7846 *
7847 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7848 * OO.ui.DropdownInputWidget instead.
7849 *
7850 * @example
7851 * // Example: A DropdownWidget with a menu that contains three options
7852 * var dropDown = new OO.ui.DropdownWidget( {
7853 * label: 'Dropdown menu: Select a menu option',
7854 * menu: {
7855 * items: [
7856 * new OO.ui.MenuOptionWidget( {
7857 * data: 'a',
7858 * label: 'First'
7859 * } ),
7860 * new OO.ui.MenuOptionWidget( {
7861 * data: 'b',
7862 * label: 'Second'
7863 * } ),
7864 * new OO.ui.MenuOptionWidget( {
7865 * data: 'c',
7866 * label: 'Third'
7867 * } )
7868 * ]
7869 * }
7870 * } );
7871 *
7872 * $( 'body' ).append( dropDown.$element );
7873 *
7874 * dropDown.getMenu().selectItemByData( 'b' );
7875 *
7876 * dropDown.getMenu().findSelectedItem().getData(); // returns 'b'
7877 *
7878 * For more information, please see the [OOUI documentation on MediaWiki] [1].
7879 *
7880 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
7881 *
7882 * @class
7883 * @extends OO.ui.Widget
7884 * @mixins OO.ui.mixin.IconElement
7885 * @mixins OO.ui.mixin.IndicatorElement
7886 * @mixins OO.ui.mixin.LabelElement
7887 * @mixins OO.ui.mixin.TitledElement
7888 * @mixins OO.ui.mixin.TabIndexedElement
7889 *
7890 * @constructor
7891 * @param {Object} [config] Configuration options
7892 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.MenuSelectWidget menu select widget}
7893 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
7894 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
7895 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
7896 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
7897 */
7898 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
7899 // Configuration initialization
7900 config = $.extend( { indicator: 'down' }, config );
7901
7902 // Parent constructor
7903 OO.ui.DropdownWidget.parent.call( this, config );
7904
7905 // Properties (must be set before TabIndexedElement constructor call)
7906 this.$handle = $( '<span>' );
7907 this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
7908
7909 // Mixin constructors
7910 OO.ui.mixin.IconElement.call( this, config );
7911 OO.ui.mixin.IndicatorElement.call( this, config );
7912 OO.ui.mixin.LabelElement.call( this, config );
7913 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
7914 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
7915
7916 // Properties
7917 this.menu = new OO.ui.MenuSelectWidget( $.extend( {
7918 widget: this,
7919 $floatableContainer: this.$element
7920 }, config.menu ) );
7921
7922 // Events
7923 this.$handle.on( {
7924 click: this.onClick.bind( this ),
7925 keydown: this.onKeyDown.bind( this ),
7926 // Hack? Handle type-to-search when menu is not expanded and not handling its own events
7927 keypress: this.menu.onDocumentKeyPressHandler,
7928 blur: this.menu.clearKeyPressBuffer.bind( this.menu )
7929 } );
7930 this.menu.connect( this, {
7931 select: 'onMenuSelect',
7932 toggle: 'onMenuToggle'
7933 } );
7934
7935 // Initialization
7936 this.$handle
7937 .addClass( 'oo-ui-dropdownWidget-handle' )
7938 .attr( {
7939 role: 'combobox',
7940 'aria-owns': this.menu.getElementId(),
7941 'aria-autocomplete': 'list'
7942 } )
7943 .append( this.$icon, this.$label, this.$indicator );
7944 this.$element
7945 .addClass( 'oo-ui-dropdownWidget' )
7946 .append( this.$handle );
7947 this.$overlay.append( this.menu.$element );
7948 };
7949
7950 /* Setup */
7951
7952 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
7953 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IconElement );
7954 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IndicatorElement );
7955 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.LabelElement );
7956 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TitledElement );
7957 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TabIndexedElement );
7958
7959 /* Methods */
7960
7961 /**
7962 * Get the menu.
7963 *
7964 * @return {OO.ui.MenuSelectWidget} Menu of widget
7965 */
7966 OO.ui.DropdownWidget.prototype.getMenu = function () {
7967 return this.menu;
7968 };
7969
7970 /**
7971 * Handles menu select events.
7972 *
7973 * @private
7974 * @param {OO.ui.MenuOptionWidget} item Selected menu item
7975 */
7976 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
7977 var selectedLabel;
7978
7979 if ( !item ) {
7980 this.setLabel( null );
7981 return;
7982 }
7983
7984 selectedLabel = item.getLabel();
7985
7986 // If the label is a DOM element, clone it, because setLabel will append() it
7987 if ( selectedLabel instanceof jQuery ) {
7988 selectedLabel = selectedLabel.clone();
7989 }
7990
7991 this.setLabel( selectedLabel );
7992 };
7993
7994 /**
7995 * Handle menu toggle events.
7996 *
7997 * @private
7998 * @param {boolean} isVisible Open state of the menu
7999 */
8000 OO.ui.DropdownWidget.prototype.onMenuToggle = function ( isVisible ) {
8001 this.$element.toggleClass( 'oo-ui-dropdownWidget-open', isVisible );
8002 this.$handle.attr(
8003 'aria-expanded',
8004 this.$element.hasClass( 'oo-ui-dropdownWidget-open' ).toString()
8005 );
8006 };
8007
8008 /**
8009 * Handle mouse click events.
8010 *
8011 * @private
8012 * @param {jQuery.Event} e Mouse click event
8013 */
8014 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
8015 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
8016 this.menu.toggle();
8017 }
8018 return false;
8019 };
8020
8021 /**
8022 * Handle key down events.
8023 *
8024 * @private
8025 * @param {jQuery.Event} e Key down event
8026 */
8027 OO.ui.DropdownWidget.prototype.onKeyDown = function ( e ) {
8028 if (
8029 !this.isDisabled() &&
8030 (
8031 e.which === OO.ui.Keys.ENTER ||
8032 (
8033 e.which === OO.ui.Keys.SPACE &&
8034 // Avoid conflicts with type-to-search, see SelectWidget#onKeyPress.
8035 // Space only closes the menu is the user is not typing to search.
8036 this.menu.keyPressBuffer === ''
8037 ) ||
8038 (
8039 !this.menu.isVisible() &&
8040 (
8041 e.which === OO.ui.Keys.UP ||
8042 e.which === OO.ui.Keys.DOWN
8043 )
8044 )
8045 )
8046 ) {
8047 this.menu.toggle();
8048 return false;
8049 }
8050 };
8051
8052 /**
8053 * RadioOptionWidget is an option widget that looks like a radio button.
8054 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
8055 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8056 *
8057 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8058 *
8059 * @class
8060 * @extends OO.ui.OptionWidget
8061 *
8062 * @constructor
8063 * @param {Object} [config] Configuration options
8064 */
8065 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
8066 // Configuration initialization
8067 config = config || {};
8068
8069 // Properties (must be done before parent constructor which calls #setDisabled)
8070 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
8071
8072 // Parent constructor
8073 OO.ui.RadioOptionWidget.parent.call( this, config );
8074
8075 // Initialization
8076 // Remove implicit role, we're handling it ourselves
8077 this.radio.$input.attr( 'role', 'presentation' );
8078 this.$element
8079 .addClass( 'oo-ui-radioOptionWidget' )
8080 .attr( 'role', 'radio' )
8081 .attr( 'aria-checked', 'false' )
8082 .removeAttr( 'aria-selected' )
8083 .prepend( this.radio.$element );
8084 };
8085
8086 /* Setup */
8087
8088 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
8089
8090 /* Static Properties */
8091
8092 /**
8093 * @static
8094 * @inheritdoc
8095 */
8096 OO.ui.RadioOptionWidget.static.highlightable = false;
8097
8098 /**
8099 * @static
8100 * @inheritdoc
8101 */
8102 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
8103
8104 /**
8105 * @static
8106 * @inheritdoc
8107 */
8108 OO.ui.RadioOptionWidget.static.pressable = false;
8109
8110 /**
8111 * @static
8112 * @inheritdoc
8113 */
8114 OO.ui.RadioOptionWidget.static.tagName = 'label';
8115
8116 /* Methods */
8117
8118 /**
8119 * @inheritdoc
8120 */
8121 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
8122 OO.ui.RadioOptionWidget.parent.prototype.setSelected.call( this, state );
8123
8124 this.radio.setSelected( state );
8125 this.$element
8126 .attr( 'aria-checked', state.toString() )
8127 .removeAttr( 'aria-selected' );
8128
8129 return this;
8130 };
8131
8132 /**
8133 * @inheritdoc
8134 */
8135 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
8136 OO.ui.RadioOptionWidget.parent.prototype.setDisabled.call( this, disabled );
8137
8138 this.radio.setDisabled( this.isDisabled() );
8139
8140 return this;
8141 };
8142
8143 /**
8144 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
8145 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
8146 * an interface for adding, removing and selecting options.
8147 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8148 *
8149 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8150 * OO.ui.RadioSelectInputWidget instead.
8151 *
8152 * @example
8153 * // A RadioSelectWidget with RadioOptions.
8154 * var option1 = new OO.ui.RadioOptionWidget( {
8155 * data: 'a',
8156 * label: 'Selected radio option'
8157 * } );
8158 *
8159 * var option2 = new OO.ui.RadioOptionWidget( {
8160 * data: 'b',
8161 * label: 'Unselected radio option'
8162 * } );
8163 *
8164 * var radioSelect=new OO.ui.RadioSelectWidget( {
8165 * items: [ option1, option2 ]
8166 * } );
8167 *
8168 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
8169 * radioSelect.selectItem( option1 );
8170 *
8171 * $( 'body' ).append( radioSelect.$element );
8172 *
8173 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8174
8175 *
8176 * @class
8177 * @extends OO.ui.SelectWidget
8178 * @mixins OO.ui.mixin.TabIndexedElement
8179 *
8180 * @constructor
8181 * @param {Object} [config] Configuration options
8182 */
8183 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
8184 // Parent constructor
8185 OO.ui.RadioSelectWidget.parent.call( this, config );
8186
8187 // Mixin constructors
8188 OO.ui.mixin.TabIndexedElement.call( this, config );
8189
8190 // Events
8191 this.$element.on( {
8192 focus: this.bindDocumentKeyDownListener.bind( this ),
8193 blur: this.unbindDocumentKeyDownListener.bind( this )
8194 } );
8195
8196 // Initialization
8197 this.$element
8198 .addClass( 'oo-ui-radioSelectWidget' )
8199 .attr( 'role', 'radiogroup' );
8200 };
8201
8202 /* Setup */
8203
8204 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
8205 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.mixin.TabIndexedElement );
8206
8207 /**
8208 * MultioptionWidgets are special elements that can be selected and configured with data. The
8209 * data is often unique for each option, but it does not have to be. MultioptionWidgets are used
8210 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
8211 * and examples, please see the [OOUI documentation on MediaWiki][1].
8212 *
8213 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Multioptions
8214 *
8215 * @class
8216 * @extends OO.ui.Widget
8217 * @mixins OO.ui.mixin.ItemWidget
8218 * @mixins OO.ui.mixin.LabelElement
8219 *
8220 * @constructor
8221 * @param {Object} [config] Configuration options
8222 * @cfg {boolean} [selected=false] Whether the option is initially selected
8223 */
8224 OO.ui.MultioptionWidget = function OoUiMultioptionWidget( config ) {
8225 // Configuration initialization
8226 config = config || {};
8227
8228 // Parent constructor
8229 OO.ui.MultioptionWidget.parent.call( this, config );
8230
8231 // Mixin constructors
8232 OO.ui.mixin.ItemWidget.call( this );
8233 OO.ui.mixin.LabelElement.call( this, config );
8234
8235 // Properties
8236 this.selected = null;
8237
8238 // Initialization
8239 this.$element
8240 .addClass( 'oo-ui-multioptionWidget' )
8241 .append( this.$label );
8242 this.setSelected( config.selected );
8243 };
8244
8245 /* Setup */
8246
8247 OO.inheritClass( OO.ui.MultioptionWidget, OO.ui.Widget );
8248 OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.ItemWidget );
8249 OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.LabelElement );
8250
8251 /* Events */
8252
8253 /**
8254 * @event change
8255 *
8256 * A change event is emitted when the selected state of the option changes.
8257 *
8258 * @param {boolean} selected Whether the option is now selected
8259 */
8260
8261 /* Methods */
8262
8263 /**
8264 * Check if the option is selected.
8265 *
8266 * @return {boolean} Item is selected
8267 */
8268 OO.ui.MultioptionWidget.prototype.isSelected = function () {
8269 return this.selected;
8270 };
8271
8272 /**
8273 * Set the option’s selected state. In general, all modifications to the selection
8274 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
8275 * method instead of this method.
8276 *
8277 * @param {boolean} [state=false] Select option
8278 * @chainable
8279 */
8280 OO.ui.MultioptionWidget.prototype.setSelected = function ( state ) {
8281 state = !!state;
8282 if ( this.selected !== state ) {
8283 this.selected = state;
8284 this.emit( 'change', state );
8285 this.$element.toggleClass( 'oo-ui-multioptionWidget-selected', state );
8286 }
8287 return this;
8288 };
8289
8290 /**
8291 * MultiselectWidget allows selecting multiple options from a list.
8292 *
8293 * For more information about menus and options, please see the [OOUI documentation on MediaWiki][1].
8294 *
8295 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
8296 *
8297 * @class
8298 * @abstract
8299 * @extends OO.ui.Widget
8300 * @mixins OO.ui.mixin.GroupWidget
8301 *
8302 * @constructor
8303 * @param {Object} [config] Configuration options
8304 * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
8305 */
8306 OO.ui.MultiselectWidget = function OoUiMultiselectWidget( config ) {
8307 // Parent constructor
8308 OO.ui.MultiselectWidget.parent.call( this, config );
8309
8310 // Configuration initialization
8311 config = config || {};
8312
8313 // Mixin constructors
8314 OO.ui.mixin.GroupWidget.call( this, config );
8315
8316 // Events
8317 this.aggregate( { change: 'select' } );
8318 // This is mostly for compatibility with TagMultiselectWidget... normally, 'change' is emitted
8319 // by GroupElement only when items are added/removed
8320 this.connect( this, { select: [ 'emit', 'change' ] } );
8321
8322 // Initialization
8323 if ( config.items ) {
8324 this.addItems( config.items );
8325 }
8326 this.$group.addClass( 'oo-ui-multiselectWidget-group' );
8327 this.$element.addClass( 'oo-ui-multiselectWidget' )
8328 .append( this.$group );
8329 };
8330
8331 /* Setup */
8332
8333 OO.inheritClass( OO.ui.MultiselectWidget, OO.ui.Widget );
8334 OO.mixinClass( OO.ui.MultiselectWidget, OO.ui.mixin.GroupWidget );
8335
8336 /* Events */
8337
8338 /**
8339 * @event change
8340 *
8341 * A change event is emitted when the set of items changes, or an item is selected or deselected.
8342 */
8343
8344 /**
8345 * @event select
8346 *
8347 * A select event is emitted when an item is selected or deselected.
8348 */
8349
8350 /* Methods */
8351
8352 /**
8353 * Find options that are selected.
8354 *
8355 * @return {OO.ui.MultioptionWidget[]} Selected options
8356 */
8357 OO.ui.MultiselectWidget.prototype.findSelectedItems = function () {
8358 return this.items.filter( function ( item ) {
8359 return item.isSelected();
8360 } );
8361 };
8362
8363 /**
8364 * Find the data of options that are selected.
8365 *
8366 * @return {Object[]|string[]} Values of selected options
8367 */
8368 OO.ui.MultiselectWidget.prototype.findSelectedItemsData = function () {
8369 return this.findSelectedItems().map( function ( item ) {
8370 return item.data;
8371 } );
8372 };
8373
8374 /**
8375 * Select options by reference. Options not mentioned in the `items` array will be deselected.
8376 *
8377 * @param {OO.ui.MultioptionWidget[]} items Items to select
8378 * @chainable
8379 */
8380 OO.ui.MultiselectWidget.prototype.selectItems = function ( items ) {
8381 this.items.forEach( function ( item ) {
8382 var selected = items.indexOf( item ) !== -1;
8383 item.setSelected( selected );
8384 } );
8385 return this;
8386 };
8387
8388 /**
8389 * Select items by their data. Options not mentioned in the `datas` array will be deselected.
8390 *
8391 * @param {Object[]|string[]} datas Values of items to select
8392 * @chainable
8393 */
8394 OO.ui.MultiselectWidget.prototype.selectItemsByData = function ( datas ) {
8395 var items,
8396 widget = this;
8397 items = datas.map( function ( data ) {
8398 return widget.findItemFromData( data );
8399 } );
8400 this.selectItems( items );
8401 return this;
8402 };
8403
8404 /**
8405 * CheckboxMultioptionWidget is an option widget that looks like a checkbox.
8406 * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
8407 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8408 *
8409 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8410 *
8411 * @class
8412 * @extends OO.ui.MultioptionWidget
8413 *
8414 * @constructor
8415 * @param {Object} [config] Configuration options
8416 */
8417 OO.ui.CheckboxMultioptionWidget = function OoUiCheckboxMultioptionWidget( config ) {
8418 // Configuration initialization
8419 config = config || {};
8420
8421 // Properties (must be done before parent constructor which calls #setDisabled)
8422 this.checkbox = new OO.ui.CheckboxInputWidget();
8423
8424 // Parent constructor
8425 OO.ui.CheckboxMultioptionWidget.parent.call( this, config );
8426
8427 // Events
8428 this.checkbox.on( 'change', this.onCheckboxChange.bind( this ) );
8429 this.$element.on( 'keydown', this.onKeyDown.bind( this ) );
8430
8431 // Initialization
8432 this.$element
8433 .addClass( 'oo-ui-checkboxMultioptionWidget' )
8434 .prepend( this.checkbox.$element );
8435 };
8436
8437 /* Setup */
8438
8439 OO.inheritClass( OO.ui.CheckboxMultioptionWidget, OO.ui.MultioptionWidget );
8440
8441 /* Static Properties */
8442
8443 /**
8444 * @static
8445 * @inheritdoc
8446 */
8447 OO.ui.CheckboxMultioptionWidget.static.tagName = 'label';
8448
8449 /* Methods */
8450
8451 /**
8452 * Handle checkbox selected state change.
8453 *
8454 * @private
8455 */
8456 OO.ui.CheckboxMultioptionWidget.prototype.onCheckboxChange = function () {
8457 this.setSelected( this.checkbox.isSelected() );
8458 };
8459
8460 /**
8461 * @inheritdoc
8462 */
8463 OO.ui.CheckboxMultioptionWidget.prototype.setSelected = function ( state ) {
8464 OO.ui.CheckboxMultioptionWidget.parent.prototype.setSelected.call( this, state );
8465 this.checkbox.setSelected( state );
8466 return this;
8467 };
8468
8469 /**
8470 * @inheritdoc
8471 */
8472 OO.ui.CheckboxMultioptionWidget.prototype.setDisabled = function ( disabled ) {
8473 OO.ui.CheckboxMultioptionWidget.parent.prototype.setDisabled.call( this, disabled );
8474 this.checkbox.setDisabled( this.isDisabled() );
8475 return this;
8476 };
8477
8478 /**
8479 * Focus the widget.
8480 */
8481 OO.ui.CheckboxMultioptionWidget.prototype.focus = function () {
8482 this.checkbox.focus();
8483 };
8484
8485 /**
8486 * Handle key down events.
8487 *
8488 * @protected
8489 * @param {jQuery.Event} e
8490 */
8491 OO.ui.CheckboxMultioptionWidget.prototype.onKeyDown = function ( e ) {
8492 var
8493 element = this.getElementGroup(),
8494 nextItem;
8495
8496 if ( e.keyCode === OO.ui.Keys.LEFT || e.keyCode === OO.ui.Keys.UP ) {
8497 nextItem = element.getRelativeFocusableItem( this, -1 );
8498 } else if ( e.keyCode === OO.ui.Keys.RIGHT || e.keyCode === OO.ui.Keys.DOWN ) {
8499 nextItem = element.getRelativeFocusableItem( this, 1 );
8500 }
8501
8502 if ( nextItem ) {
8503 e.preventDefault();
8504 nextItem.focus();
8505 }
8506 };
8507
8508 /**
8509 * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
8510 * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
8511 * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
8512 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8513 *
8514 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8515 * OO.ui.CheckboxMultiselectInputWidget instead.
8516 *
8517 * @example
8518 * // A CheckboxMultiselectWidget with CheckboxMultioptions.
8519 * var option1 = new OO.ui.CheckboxMultioptionWidget( {
8520 * data: 'a',
8521 * selected: true,
8522 * label: 'Selected checkbox'
8523 * } );
8524 *
8525 * var option2 = new OO.ui.CheckboxMultioptionWidget( {
8526 * data: 'b',
8527 * label: 'Unselected checkbox'
8528 * } );
8529 *
8530 * var multiselect=new OO.ui.CheckboxMultiselectWidget( {
8531 * items: [ option1, option2 ]
8532 * } );
8533 *
8534 * $( 'body' ).append( multiselect.$element );
8535 *
8536 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8537 *
8538 * @class
8539 * @extends OO.ui.MultiselectWidget
8540 *
8541 * @constructor
8542 * @param {Object} [config] Configuration options
8543 */
8544 OO.ui.CheckboxMultiselectWidget = function OoUiCheckboxMultiselectWidget( config ) {
8545 // Parent constructor
8546 OO.ui.CheckboxMultiselectWidget.parent.call( this, config );
8547
8548 // Properties
8549 this.$lastClicked = null;
8550
8551 // Events
8552 this.$group.on( 'click', this.onClick.bind( this ) );
8553
8554 // Initialization
8555 this.$element
8556 .addClass( 'oo-ui-checkboxMultiselectWidget' );
8557 };
8558
8559 /* Setup */
8560
8561 OO.inheritClass( OO.ui.CheckboxMultiselectWidget, OO.ui.MultiselectWidget );
8562
8563 /* Methods */
8564
8565 /**
8566 * Get an option by its position relative to the specified item (or to the start of the option array,
8567 * if item is `null`). The direction in which to search through the option array is specified with a
8568 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
8569 * `null` if there are no options in the array.
8570 *
8571 * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
8572 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
8573 * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items in the select
8574 */
8575 OO.ui.CheckboxMultiselectWidget.prototype.getRelativeFocusableItem = function ( item, direction ) {
8576 var currentIndex, nextIndex, i,
8577 increase = direction > 0 ? 1 : -1,
8578 len = this.items.length;
8579
8580 if ( item ) {
8581 currentIndex = this.items.indexOf( item );
8582 nextIndex = ( currentIndex + increase + len ) % len;
8583 } else {
8584 // If no item is selected and moving forward, start at the beginning.
8585 // If moving backward, start at the end.
8586 nextIndex = direction > 0 ? 0 : len - 1;
8587 }
8588
8589 for ( i = 0; i < len; i++ ) {
8590 item = this.items[ nextIndex ];
8591 if ( item && !item.isDisabled() ) {
8592 return item;
8593 }
8594 nextIndex = ( nextIndex + increase + len ) % len;
8595 }
8596 return null;
8597 };
8598
8599 /**
8600 * Handle click events on checkboxes.
8601 *
8602 * @param {jQuery.Event} e
8603 */
8604 OO.ui.CheckboxMultiselectWidget.prototype.onClick = function ( e ) {
8605 var $options, lastClickedIndex, nowClickedIndex, i, direction, wasSelected, items,
8606 $lastClicked = this.$lastClicked,
8607 $nowClicked = $( e.target ).closest( '.oo-ui-checkboxMultioptionWidget' )
8608 .not( '.oo-ui-widget-disabled' );
8609
8610 // Allow selecting multiple options at once by Shift-clicking them
8611 if ( $lastClicked && $nowClicked.length && e.shiftKey ) {
8612 $options = this.$group.find( '.oo-ui-checkboxMultioptionWidget' );
8613 lastClickedIndex = $options.index( $lastClicked );
8614 nowClickedIndex = $options.index( $nowClicked );
8615 // If it's the same item, either the user is being silly, or it's a fake event generated by the
8616 // browser. In either case we don't need custom handling.
8617 if ( nowClickedIndex !== lastClickedIndex ) {
8618 items = this.items;
8619 wasSelected = items[ nowClickedIndex ].isSelected();
8620 direction = nowClickedIndex > lastClickedIndex ? 1 : -1;
8621
8622 // This depends on the DOM order of the items and the order of the .items array being the same.
8623 for ( i = lastClickedIndex; i !== nowClickedIndex; i += direction ) {
8624 if ( !items[ i ].isDisabled() ) {
8625 items[ i ].setSelected( !wasSelected );
8626 }
8627 }
8628 // For the now-clicked element, use immediate timeout to allow the browser to do its own
8629 // handling first, then set our value. The order in which events happen is different for
8630 // clicks on the <input> and on the <label> and there are additional fake clicks fired for
8631 // non-click actions that change the checkboxes.
8632 e.preventDefault();
8633 setTimeout( function () {
8634 if ( !items[ nowClickedIndex ].isDisabled() ) {
8635 items[ nowClickedIndex ].setSelected( !wasSelected );
8636 }
8637 } );
8638 }
8639 }
8640
8641 if ( $nowClicked.length ) {
8642 this.$lastClicked = $nowClicked;
8643 }
8644 };
8645
8646 /**
8647 * Focus the widget
8648 *
8649 * @chainable
8650 */
8651 OO.ui.CheckboxMultiselectWidget.prototype.focus = function () {
8652 var item;
8653 if ( !this.isDisabled() ) {
8654 item = this.getRelativeFocusableItem( null, 1 );
8655 if ( item ) {
8656 item.focus();
8657 }
8658 }
8659 return this;
8660 };
8661
8662 /**
8663 * @inheritdoc
8664 */
8665 OO.ui.CheckboxMultiselectWidget.prototype.simulateLabelClick = function () {
8666 this.focus();
8667 };
8668
8669 /**
8670 * Progress bars visually display the status of an operation, such as a download,
8671 * and can be either determinate or indeterminate:
8672 *
8673 * - **determinate** process bars show the percent of an operation that is complete.
8674 *
8675 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
8676 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
8677 * not use percentages.
8678 *
8679 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
8680 *
8681 * @example
8682 * // Examples of determinate and indeterminate progress bars.
8683 * var progressBar1 = new OO.ui.ProgressBarWidget( {
8684 * progress: 33
8685 * } );
8686 * var progressBar2 = new OO.ui.ProgressBarWidget();
8687 *
8688 * // Create a FieldsetLayout to layout progress bars
8689 * var fieldset = new OO.ui.FieldsetLayout;
8690 * fieldset.addItems( [
8691 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
8692 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
8693 * ] );
8694 * $( 'body' ).append( fieldset.$element );
8695 *
8696 * @class
8697 * @extends OO.ui.Widget
8698 *
8699 * @constructor
8700 * @param {Object} [config] Configuration options
8701 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
8702 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
8703 * By default, the progress bar is indeterminate.
8704 */
8705 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
8706 // Configuration initialization
8707 config = config || {};
8708
8709 // Parent constructor
8710 OO.ui.ProgressBarWidget.parent.call( this, config );
8711
8712 // Properties
8713 this.$bar = $( '<div>' );
8714 this.progress = null;
8715
8716 // Initialization
8717 this.setProgress( config.progress !== undefined ? config.progress : false );
8718 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
8719 this.$element
8720 .attr( {
8721 role: 'progressbar',
8722 'aria-valuemin': 0,
8723 'aria-valuemax': 100
8724 } )
8725 .addClass( 'oo-ui-progressBarWidget' )
8726 .append( this.$bar );
8727 };
8728
8729 /* Setup */
8730
8731 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
8732
8733 /* Static Properties */
8734
8735 /**
8736 * @static
8737 * @inheritdoc
8738 */
8739 OO.ui.ProgressBarWidget.static.tagName = 'div';
8740
8741 /* Methods */
8742
8743 /**
8744 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
8745 *
8746 * @return {number|boolean} Progress percent
8747 */
8748 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
8749 return this.progress;
8750 };
8751
8752 /**
8753 * Set the percent of the process completed or `false` for an indeterminate process.
8754 *
8755 * @param {number|boolean} progress Progress percent or `false` for indeterminate
8756 */
8757 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
8758 this.progress = progress;
8759
8760 if ( progress !== false ) {
8761 this.$bar.css( 'width', this.progress + '%' );
8762 this.$element.attr( 'aria-valuenow', this.progress );
8763 } else {
8764 this.$bar.css( 'width', '' );
8765 this.$element.removeAttr( 'aria-valuenow' );
8766 }
8767 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress === false );
8768 };
8769
8770 /**
8771 * InputWidget is the base class for all input widgets, which
8772 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
8773 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
8774 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
8775 *
8776 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
8777 *
8778 * @abstract
8779 * @class
8780 * @extends OO.ui.Widget
8781 * @mixins OO.ui.mixin.FlaggedElement
8782 * @mixins OO.ui.mixin.TabIndexedElement
8783 * @mixins OO.ui.mixin.TitledElement
8784 * @mixins OO.ui.mixin.AccessKeyedElement
8785 *
8786 * @constructor
8787 * @param {Object} [config] Configuration options
8788 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
8789 * @cfg {string} [value=''] The value of the input.
8790 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
8791 * @cfg {string} [inputId] The value of the input’s HTML `id` attribute.
8792 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
8793 * before it is accepted.
8794 */
8795 OO.ui.InputWidget = function OoUiInputWidget( config ) {
8796 // Configuration initialization
8797 config = config || {};
8798
8799 // Parent constructor
8800 OO.ui.InputWidget.parent.call( this, config );
8801
8802 // Properties
8803 // See #reusePreInfuseDOM about config.$input
8804 this.$input = config.$input || this.getInputElement( config );
8805 this.value = '';
8806 this.inputFilter = config.inputFilter;
8807
8808 // Mixin constructors
8809 OO.ui.mixin.FlaggedElement.call( this, config );
8810 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
8811 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
8812 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$input } ) );
8813
8814 // Events
8815 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
8816
8817 // Initialization
8818 this.$input
8819 .addClass( 'oo-ui-inputWidget-input' )
8820 .attr( 'name', config.name )
8821 .prop( 'disabled', this.isDisabled() );
8822 this.$element
8823 .addClass( 'oo-ui-inputWidget' )
8824 .append( this.$input );
8825 this.setValue( config.value );
8826 if ( config.dir ) {
8827 this.setDir( config.dir );
8828 }
8829 if ( config.inputId !== undefined ) {
8830 this.setInputId( config.inputId );
8831 }
8832 };
8833
8834 /* Setup */
8835
8836 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
8837 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.FlaggedElement );
8838 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TabIndexedElement );
8839 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TitledElement );
8840 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.AccessKeyedElement );
8841
8842 /* Static Methods */
8843
8844 /**
8845 * @inheritdoc
8846 */
8847 OO.ui.InputWidget.static.reusePreInfuseDOM = function ( node, config ) {
8848 config = OO.ui.InputWidget.parent.static.reusePreInfuseDOM( node, config );
8849 // Reusing `$input` lets browsers preserve inputted values across page reloads, see T114134.
8850 config.$input = $( node ).find( '.oo-ui-inputWidget-input' );
8851 return config;
8852 };
8853
8854 /**
8855 * @inheritdoc
8856 */
8857 OO.ui.InputWidget.static.gatherPreInfuseState = function ( node, config ) {
8858 var state = OO.ui.InputWidget.parent.static.gatherPreInfuseState( node, config );
8859 if ( config.$input && config.$input.length ) {
8860 state.value = config.$input.val();
8861 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
8862 state.focus = config.$input.is( ':focus' );
8863 }
8864 return state;
8865 };
8866
8867 /* Events */
8868
8869 /**
8870 * @event change
8871 *
8872 * A change event is emitted when the value of the input changes.
8873 *
8874 * @param {string} value
8875 */
8876
8877 /* Methods */
8878
8879 /**
8880 * Get input element.
8881 *
8882 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
8883 * different circumstances. The element must have a `value` property (like form elements).
8884 *
8885 * @protected
8886 * @param {Object} config Configuration options
8887 * @return {jQuery} Input element
8888 */
8889 OO.ui.InputWidget.prototype.getInputElement = function () {
8890 return $( '<input>' );
8891 };
8892
8893 /**
8894 * Handle potentially value-changing events.
8895 *
8896 * @private
8897 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
8898 */
8899 OO.ui.InputWidget.prototype.onEdit = function () {
8900 var widget = this;
8901 if ( !this.isDisabled() ) {
8902 // Allow the stack to clear so the value will be updated
8903 setTimeout( function () {
8904 widget.setValue( widget.$input.val() );
8905 } );
8906 }
8907 };
8908
8909 /**
8910 * Get the value of the input.
8911 *
8912 * @return {string} Input value
8913 */
8914 OO.ui.InputWidget.prototype.getValue = function () {
8915 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
8916 // it, and we won't know unless they're kind enough to trigger a 'change' event.
8917 var value = this.$input.val();
8918 if ( this.value !== value ) {
8919 this.setValue( value );
8920 }
8921 return this.value;
8922 };
8923
8924 /**
8925 * Set the directionality of the input.
8926 *
8927 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
8928 * @chainable
8929 */
8930 OO.ui.InputWidget.prototype.setDir = function ( dir ) {
8931 this.$input.prop( 'dir', dir );
8932 return this;
8933 };
8934
8935 /**
8936 * Set the value of the input.
8937 *
8938 * @param {string} value New value
8939 * @fires change
8940 * @chainable
8941 */
8942 OO.ui.InputWidget.prototype.setValue = function ( value ) {
8943 value = this.cleanUpValue( value );
8944 // Update the DOM if it has changed. Note that with cleanUpValue, it
8945 // is possible for the DOM value to change without this.value changing.
8946 if ( this.$input.val() !== value ) {
8947 this.$input.val( value );
8948 }
8949 if ( this.value !== value ) {
8950 this.value = value;
8951 this.emit( 'change', this.value );
8952 }
8953 // The first time that the value is set (probably while constructing the widget),
8954 // remember it in defaultValue. This property can be later used to check whether
8955 // the value of the input has been changed since it was created.
8956 if ( this.defaultValue === undefined ) {
8957 this.defaultValue = this.value;
8958 this.$input[ 0 ].defaultValue = this.defaultValue;
8959 }
8960 return this;
8961 };
8962
8963 /**
8964 * Clean up incoming value.
8965 *
8966 * Ensures value is a string, and converts undefined and null to empty string.
8967 *
8968 * @private
8969 * @param {string} value Original value
8970 * @return {string} Cleaned up value
8971 */
8972 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
8973 if ( value === undefined || value === null ) {
8974 return '';
8975 } else if ( this.inputFilter ) {
8976 return this.inputFilter( String( value ) );
8977 } else {
8978 return String( value );
8979 }
8980 };
8981
8982 /**
8983 * @inheritdoc
8984 */
8985 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
8986 OO.ui.InputWidget.parent.prototype.setDisabled.call( this, state );
8987 if ( this.$input ) {
8988 this.$input.prop( 'disabled', this.isDisabled() );
8989 }
8990 return this;
8991 };
8992
8993 /**
8994 * Set the 'id' attribute of the `<input>` element.
8995 *
8996 * @param {string} id
8997 * @chainable
8998 */
8999 OO.ui.InputWidget.prototype.setInputId = function ( id ) {
9000 this.$input.attr( 'id', id );
9001 return this;
9002 };
9003
9004 /**
9005 * @inheritdoc
9006 */
9007 OO.ui.InputWidget.prototype.restorePreInfuseState = function ( state ) {
9008 OO.ui.InputWidget.parent.prototype.restorePreInfuseState.call( this, state );
9009 if ( state.value !== undefined && state.value !== this.getValue() ) {
9010 this.setValue( state.value );
9011 }
9012 if ( state.focus ) {
9013 this.focus();
9014 }
9015 };
9016
9017 /**
9018 * Data widget intended for creating 'hidden'-type inputs.
9019 *
9020 * @class
9021 * @extends OO.ui.Widget
9022 *
9023 * @constructor
9024 * @param {Object} [config] Configuration options
9025 * @cfg {string} [value=''] The value of the input.
9026 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
9027 */
9028 OO.ui.HiddenInputWidget = function OoUiHiddenInputWidget( config ) {
9029 // Configuration initialization
9030 config = $.extend( { value: '', name: '' }, config );
9031
9032 // Parent constructor
9033 OO.ui.HiddenInputWidget.parent.call( this, config );
9034
9035 // Initialization
9036 this.$element.attr( {
9037 type: 'hidden',
9038 value: config.value,
9039 name: config.name
9040 } );
9041 this.$element.removeAttr( 'aria-disabled' );
9042 };
9043
9044 /* Setup */
9045
9046 OO.inheritClass( OO.ui.HiddenInputWidget, OO.ui.Widget );
9047
9048 /* Static Properties */
9049
9050 /**
9051 * @static
9052 * @inheritdoc
9053 */
9054 OO.ui.HiddenInputWidget.static.tagName = 'input';
9055
9056 /**
9057 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
9058 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
9059 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
9060 * HTML `<button>` (the default) or an HTML `<input>` tags. See the
9061 * [OOUI documentation on MediaWiki] [1] for more information.
9062 *
9063 * @example
9064 * // A ButtonInputWidget rendered as an HTML button, the default.
9065 * var button = new OO.ui.ButtonInputWidget( {
9066 * label: 'Input button',
9067 * icon: 'check',
9068 * value: 'check'
9069 * } );
9070 * $( 'body' ).append( button.$element );
9071 *
9072 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#Button_inputs
9073 *
9074 * @class
9075 * @extends OO.ui.InputWidget
9076 * @mixins OO.ui.mixin.ButtonElement
9077 * @mixins OO.ui.mixin.IconElement
9078 * @mixins OO.ui.mixin.IndicatorElement
9079 * @mixins OO.ui.mixin.LabelElement
9080 * @mixins OO.ui.mixin.TitledElement
9081 *
9082 * @constructor
9083 * @param {Object} [config] Configuration options
9084 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
9085 * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
9086 * Widgets configured to be an `<input>` do not support {@link #icon icons} and {@link #indicator indicators},
9087 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
9088 * be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
9089 */
9090 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
9091 // Configuration initialization
9092 config = $.extend( { type: 'button', useInputTag: false }, config );
9093
9094 // See InputWidget#reusePreInfuseDOM about config.$input
9095 if ( config.$input ) {
9096 config.$input.empty();
9097 }
9098
9099 // Properties (must be set before parent constructor, which calls #setValue)
9100 this.useInputTag = config.useInputTag;
9101
9102 // Parent constructor
9103 OO.ui.ButtonInputWidget.parent.call( this, config );
9104
9105 // Mixin constructors
9106 OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
9107 OO.ui.mixin.IconElement.call( this, config );
9108 OO.ui.mixin.IndicatorElement.call( this, config );
9109 OO.ui.mixin.LabelElement.call( this, config );
9110 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
9111
9112 // Initialization
9113 if ( !config.useInputTag ) {
9114 this.$input.append( this.$icon, this.$label, this.$indicator );
9115 }
9116 this.$element.addClass( 'oo-ui-buttonInputWidget' );
9117 };
9118
9119 /* Setup */
9120
9121 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
9122 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.ButtonElement );
9123 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IconElement );
9124 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IndicatorElement );
9125 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.LabelElement );
9126 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.TitledElement );
9127
9128 /* Static Properties */
9129
9130 /**
9131 * @static
9132 * @inheritdoc
9133 */
9134 OO.ui.ButtonInputWidget.static.tagName = 'span';
9135
9136 /* Methods */
9137
9138 /**
9139 * @inheritdoc
9140 * @protected
9141 */
9142 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
9143 var type;
9144 type = [ 'button', 'submit', 'reset' ].indexOf( config.type ) !== -1 ? config.type : 'button';
9145 return $( '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + type + '">' );
9146 };
9147
9148 /**
9149 * Set label value.
9150 *
9151 * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
9152 *
9153 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
9154 * text, or `null` for no label
9155 * @chainable
9156 */
9157 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
9158 if ( typeof label === 'function' ) {
9159 label = OO.ui.resolveMsg( label );
9160 }
9161
9162 if ( this.useInputTag ) {
9163 // Discard non-plaintext labels
9164 if ( typeof label !== 'string' ) {
9165 label = '';
9166 }
9167
9168 this.$input.val( label );
9169 }
9170
9171 return OO.ui.mixin.LabelElement.prototype.setLabel.call( this, label );
9172 };
9173
9174 /**
9175 * Set the value of the input.
9176 *
9177 * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
9178 * they do not support {@link #value values}.
9179 *
9180 * @param {string} value New value
9181 * @chainable
9182 */
9183 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
9184 if ( !this.useInputTag ) {
9185 OO.ui.ButtonInputWidget.parent.prototype.setValue.call( this, value );
9186 }
9187 return this;
9188 };
9189
9190 /**
9191 * @inheritdoc
9192 */
9193 OO.ui.ButtonInputWidget.prototype.getInputId = function () {
9194 // Disable generating `<label>` elements for buttons. One would very rarely need additional label
9195 // for a button, and it's already a big clickable target, and it causes unexpected rendering.
9196 return null;
9197 };
9198
9199 /**
9200 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
9201 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
9202 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
9203 * alignment. For more information, please see the [OOUI documentation on MediaWiki][1].
9204 *
9205 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9206 *
9207 * @example
9208 * // An example of selected, unselected, and disabled checkbox inputs
9209 * var checkbox1=new OO.ui.CheckboxInputWidget( {
9210 * value: 'a',
9211 * selected: true
9212 * } );
9213 * var checkbox2=new OO.ui.CheckboxInputWidget( {
9214 * value: 'b'
9215 * } );
9216 * var checkbox3=new OO.ui.CheckboxInputWidget( {
9217 * value:'c',
9218 * disabled: true
9219 * } );
9220 * // Create a fieldset layout with fields for each checkbox.
9221 * var fieldset = new OO.ui.FieldsetLayout( {
9222 * label: 'Checkboxes'
9223 * } );
9224 * fieldset.addItems( [
9225 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
9226 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
9227 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
9228 * ] );
9229 * $( 'body' ).append( fieldset.$element );
9230 *
9231 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9232 *
9233 * @class
9234 * @extends OO.ui.InputWidget
9235 *
9236 * @constructor
9237 * @param {Object} [config] Configuration options
9238 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
9239 */
9240 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
9241 // Configuration initialization
9242 config = config || {};
9243
9244 // Parent constructor
9245 OO.ui.CheckboxInputWidget.parent.call( this, config );
9246
9247 // Properties
9248 this.checkIcon = new OO.ui.IconWidget( {
9249 icon: 'check',
9250 classes: [ 'oo-ui-checkboxInputWidget-checkIcon' ]
9251 } );
9252
9253 // Initialization
9254 this.$element
9255 .addClass( 'oo-ui-checkboxInputWidget' )
9256 // Required for pretty styling in WikimediaUI theme
9257 .append( this.checkIcon.$element );
9258 this.setSelected( config.selected !== undefined ? config.selected : false );
9259 };
9260
9261 /* Setup */
9262
9263 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
9264
9265 /* Static Properties */
9266
9267 /**
9268 * @static
9269 * @inheritdoc
9270 */
9271 OO.ui.CheckboxInputWidget.static.tagName = 'span';
9272
9273 /* Static Methods */
9274
9275 /**
9276 * @inheritdoc
9277 */
9278 OO.ui.CheckboxInputWidget.static.gatherPreInfuseState = function ( node, config ) {
9279 var state = OO.ui.CheckboxInputWidget.parent.static.gatherPreInfuseState( node, config );
9280 state.checked = config.$input.prop( 'checked' );
9281 return state;
9282 };
9283
9284 /* Methods */
9285
9286 /**
9287 * @inheritdoc
9288 * @protected
9289 */
9290 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
9291 return $( '<input>' ).attr( 'type', 'checkbox' );
9292 };
9293
9294 /**
9295 * @inheritdoc
9296 */
9297 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
9298 var widget = this;
9299 if ( !this.isDisabled() ) {
9300 // Allow the stack to clear so the value will be updated
9301 setTimeout( function () {
9302 widget.setSelected( widget.$input.prop( 'checked' ) );
9303 } );
9304 }
9305 };
9306
9307 /**
9308 * Set selection state of this checkbox.
9309 *
9310 * @param {boolean} state `true` for selected
9311 * @chainable
9312 */
9313 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
9314 state = !!state;
9315 if ( this.selected !== state ) {
9316 this.selected = state;
9317 this.$input.prop( 'checked', this.selected );
9318 this.emit( 'change', this.selected );
9319 }
9320 // The first time that the selection state is set (probably while constructing the widget),
9321 // remember it in defaultSelected. This property can be later used to check whether
9322 // the selection state of the input has been changed since it was created.
9323 if ( this.defaultSelected === undefined ) {
9324 this.defaultSelected = this.selected;
9325 this.$input[ 0 ].defaultChecked = this.defaultSelected;
9326 }
9327 return this;
9328 };
9329
9330 /**
9331 * Check if this checkbox is selected.
9332 *
9333 * @return {boolean} Checkbox is selected
9334 */
9335 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
9336 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
9337 // it, and we won't know unless they're kind enough to trigger a 'change' event.
9338 var selected = this.$input.prop( 'checked' );
9339 if ( this.selected !== selected ) {
9340 this.setSelected( selected );
9341 }
9342 return this.selected;
9343 };
9344
9345 /**
9346 * @inheritdoc
9347 */
9348 OO.ui.CheckboxInputWidget.prototype.simulateLabelClick = function () {
9349 if ( !this.isDisabled() ) {
9350 this.$input.click();
9351 }
9352 this.focus();
9353 };
9354
9355 /**
9356 * @inheritdoc
9357 */
9358 OO.ui.CheckboxInputWidget.prototype.restorePreInfuseState = function ( state ) {
9359 OO.ui.CheckboxInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
9360 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
9361 this.setSelected( state.checked );
9362 }
9363 };
9364
9365 /**
9366 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
9367 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
9368 * of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9369 * more information about input widgets.
9370 *
9371 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
9372 * are no options. If no `value` configuration option is provided, the first option is selected.
9373 * If you need a state representing no value (no option being selected), use a DropdownWidget.
9374 *
9375 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
9376 *
9377 * @example
9378 * // Example: A DropdownInputWidget with three options
9379 * var dropdownInput = new OO.ui.DropdownInputWidget( {
9380 * options: [
9381 * { data: 'a', label: 'First' },
9382 * { data: 'b', label: 'Second'},
9383 * { data: 'c', label: 'Third' }
9384 * ]
9385 * } );
9386 * $( 'body' ).append( dropdownInput.$element );
9387 *
9388 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9389 *
9390 * @class
9391 * @extends OO.ui.InputWidget
9392 *
9393 * @constructor
9394 * @param {Object} [config] Configuration options
9395 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9396 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
9397 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
9398 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
9399 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
9400 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
9401 */
9402 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
9403 // Configuration initialization
9404 config = config || {};
9405
9406 // Properties (must be done before parent constructor which calls #setDisabled)
9407 this.dropdownWidget = new OO.ui.DropdownWidget( $.extend(
9408 {
9409 $overlay: config.$overlay
9410 },
9411 config.dropdown
9412 ) );
9413 // Set up the options before parent constructor, which uses them to validate config.value.
9414 // Use this instead of setOptions() because this.$input is not set up yet.
9415 this.setOptionsData( config.options || [] );
9416
9417 // Parent constructor
9418 OO.ui.DropdownInputWidget.parent.call( this, config );
9419
9420 // Events
9421 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
9422
9423 // Initialization
9424 this.$element
9425 .addClass( 'oo-ui-dropdownInputWidget' )
9426 .append( this.dropdownWidget.$element );
9427 this.setTabIndexedElement( this.dropdownWidget.$tabIndexed );
9428 };
9429
9430 /* Setup */
9431
9432 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
9433
9434 /* Methods */
9435
9436 /**
9437 * @inheritdoc
9438 * @protected
9439 */
9440 OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
9441 return $( '<select>' );
9442 };
9443
9444 /**
9445 * Handles menu select events.
9446 *
9447 * @private
9448 * @param {OO.ui.MenuOptionWidget|null} item Selected menu item
9449 */
9450 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
9451 this.setValue( item ? item.getData() : '' );
9452 };
9453
9454 /**
9455 * @inheritdoc
9456 */
9457 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
9458 var selected;
9459 value = this.cleanUpValue( value );
9460 // Only allow setting values that are actually present in the dropdown
9461 selected = this.dropdownWidget.getMenu().findItemFromData( value ) ||
9462 this.dropdownWidget.getMenu().findFirstSelectableItem();
9463 this.dropdownWidget.getMenu().selectItem( selected );
9464 value = selected ? selected.getData() : '';
9465 OO.ui.DropdownInputWidget.parent.prototype.setValue.call( this, value );
9466 if ( this.optionsDirty ) {
9467 // We reached this from the constructor or from #setOptions.
9468 // We have to update the <select> element.
9469 this.updateOptionsInterface();
9470 }
9471 return this;
9472 };
9473
9474 /**
9475 * @inheritdoc
9476 */
9477 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
9478 this.dropdownWidget.setDisabled( state );
9479 OO.ui.DropdownInputWidget.parent.prototype.setDisabled.call( this, state );
9480 return this;
9481 };
9482
9483 /**
9484 * Set the options available for this input.
9485 *
9486 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9487 * @chainable
9488 */
9489 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
9490 var value = this.getValue();
9491
9492 this.setOptionsData( options );
9493
9494 // Re-set the value to update the visible interface (DropdownWidget and <select>).
9495 // In case the previous value is no longer an available option, select the first valid one.
9496 this.setValue( value );
9497
9498 return this;
9499 };
9500
9501 /**
9502 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
9503 *
9504 * This method may be called before the parent constructor, so various properties may not be
9505 * intialized yet.
9506 *
9507 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9508 * @private
9509 */
9510 OO.ui.DropdownInputWidget.prototype.setOptionsData = function ( options ) {
9511 var
9512 optionWidgets,
9513 widget = this;
9514
9515 this.optionsDirty = true;
9516
9517 optionWidgets = options.map( function ( opt ) {
9518 var optValue;
9519
9520 if ( opt.optgroup !== undefined ) {
9521 return widget.createMenuSectionOptionWidget( opt.optgroup );
9522 }
9523
9524 optValue = widget.cleanUpValue( opt.data );
9525 return widget.createMenuOptionWidget(
9526 optValue,
9527 opt.label !== undefined ? opt.label : optValue
9528 );
9529
9530 } );
9531
9532 this.dropdownWidget.getMenu().clearItems().addItems( optionWidgets );
9533 };
9534
9535 /**
9536 * Create a menu option widget.
9537 *
9538 * @protected
9539 * @param {string} data Item data
9540 * @param {string} label Item label
9541 * @return {OO.ui.MenuOptionWidget} Option widget
9542 */
9543 OO.ui.DropdownInputWidget.prototype.createMenuOptionWidget = function ( data, label ) {
9544 return new OO.ui.MenuOptionWidget( {
9545 data: data,
9546 label: label
9547 } );
9548 };
9549
9550 /**
9551 * Create a menu section option widget.
9552 *
9553 * @protected
9554 * @param {string} label Section item label
9555 * @return {OO.ui.MenuSectionOptionWidget} Menu section option widget
9556 */
9557 OO.ui.DropdownInputWidget.prototype.createMenuSectionOptionWidget = function ( label ) {
9558 return new OO.ui.MenuSectionOptionWidget( {
9559 label: label
9560 } );
9561 };
9562
9563 /**
9564 * Update the user-visible interface to match the internal list of options and value.
9565 *
9566 * This method must only be called after the parent constructor.
9567 *
9568 * @private
9569 */
9570 OO.ui.DropdownInputWidget.prototype.updateOptionsInterface = function () {
9571 var
9572 $optionsContainer = this.$input,
9573 defaultValue = this.defaultValue,
9574 widget = this;
9575
9576 this.$input.empty();
9577
9578 this.dropdownWidget.getMenu().getItems().forEach( function ( optionWidget ) {
9579 var $optionNode;
9580
9581 if ( !( optionWidget instanceof OO.ui.MenuSectionOptionWidget ) ) {
9582 $optionNode = $( '<option>' )
9583 .attr( 'value', optionWidget.getData() )
9584 .text( optionWidget.getLabel() );
9585
9586 // Remember original selection state. This property can be later used to check whether
9587 // the selection state of the input has been changed since it was created.
9588 $optionNode[ 0 ].defaultSelected = ( optionWidget.getData() === defaultValue );
9589
9590 $optionsContainer.append( $optionNode );
9591 } else {
9592 $optionNode = $( '<optgroup>' )
9593 .attr( 'label', optionWidget.getLabel() );
9594 widget.$input.append( $optionNode );
9595 $optionsContainer = $optionNode;
9596 }
9597 } );
9598
9599 this.optionsDirty = false;
9600 };
9601
9602 /**
9603 * @inheritdoc
9604 */
9605 OO.ui.DropdownInputWidget.prototype.focus = function () {
9606 this.dropdownWidget.focus();
9607 return this;
9608 };
9609
9610 /**
9611 * @inheritdoc
9612 */
9613 OO.ui.DropdownInputWidget.prototype.blur = function () {
9614 this.dropdownWidget.blur();
9615 return this;
9616 };
9617
9618 /**
9619 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
9620 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
9621 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
9622 * please see the [OOUI documentation on MediaWiki][1].
9623 *
9624 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9625 *
9626 * @example
9627 * // An example of selected, unselected, and disabled radio inputs
9628 * var radio1 = new OO.ui.RadioInputWidget( {
9629 * value: 'a',
9630 * selected: true
9631 * } );
9632 * var radio2 = new OO.ui.RadioInputWidget( {
9633 * value: 'b'
9634 * } );
9635 * var radio3 = new OO.ui.RadioInputWidget( {
9636 * value: 'c',
9637 * disabled: true
9638 * } );
9639 * // Create a fieldset layout with fields for each radio button.
9640 * var fieldset = new OO.ui.FieldsetLayout( {
9641 * label: 'Radio inputs'
9642 * } );
9643 * fieldset.addItems( [
9644 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
9645 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
9646 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
9647 * ] );
9648 * $( 'body' ).append( fieldset.$element );
9649 *
9650 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9651 *
9652 * @class
9653 * @extends OO.ui.InputWidget
9654 *
9655 * @constructor
9656 * @param {Object} [config] Configuration options
9657 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
9658 */
9659 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
9660 // Configuration initialization
9661 config = config || {};
9662
9663 // Parent constructor
9664 OO.ui.RadioInputWidget.parent.call( this, config );
9665
9666 // Initialization
9667 this.$element
9668 .addClass( 'oo-ui-radioInputWidget' )
9669 // Required for pretty styling in WikimediaUI theme
9670 .append( $( '<span>' ) );
9671 this.setSelected( config.selected !== undefined ? config.selected : false );
9672 };
9673
9674 /* Setup */
9675
9676 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
9677
9678 /* Static Properties */
9679
9680 /**
9681 * @static
9682 * @inheritdoc
9683 */
9684 OO.ui.RadioInputWidget.static.tagName = 'span';
9685
9686 /* Static Methods */
9687
9688 /**
9689 * @inheritdoc
9690 */
9691 OO.ui.RadioInputWidget.static.gatherPreInfuseState = function ( node, config ) {
9692 var state = OO.ui.RadioInputWidget.parent.static.gatherPreInfuseState( node, config );
9693 state.checked = config.$input.prop( 'checked' );
9694 return state;
9695 };
9696
9697 /* Methods */
9698
9699 /**
9700 * @inheritdoc
9701 * @protected
9702 */
9703 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
9704 return $( '<input>' ).attr( 'type', 'radio' );
9705 };
9706
9707 /**
9708 * @inheritdoc
9709 */
9710 OO.ui.RadioInputWidget.prototype.onEdit = function () {
9711 // RadioInputWidget doesn't track its state.
9712 };
9713
9714 /**
9715 * Set selection state of this radio button.
9716 *
9717 * @param {boolean} state `true` for selected
9718 * @chainable
9719 */
9720 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
9721 // RadioInputWidget doesn't track its state.
9722 this.$input.prop( 'checked', state );
9723 // The first time that the selection state is set (probably while constructing the widget),
9724 // remember it in defaultSelected. This property can be later used to check whether
9725 // the selection state of the input has been changed since it was created.
9726 if ( this.defaultSelected === undefined ) {
9727 this.defaultSelected = state;
9728 this.$input[ 0 ].defaultChecked = this.defaultSelected;
9729 }
9730 return this;
9731 };
9732
9733 /**
9734 * Check if this radio button is selected.
9735 *
9736 * @return {boolean} Radio is selected
9737 */
9738 OO.ui.RadioInputWidget.prototype.isSelected = function () {
9739 return this.$input.prop( 'checked' );
9740 };
9741
9742 /**
9743 * @inheritdoc
9744 */
9745 OO.ui.RadioInputWidget.prototype.simulateLabelClick = function () {
9746 if ( !this.isDisabled() ) {
9747 this.$input.click();
9748 }
9749 this.focus();
9750 };
9751
9752 /**
9753 * @inheritdoc
9754 */
9755 OO.ui.RadioInputWidget.prototype.restorePreInfuseState = function ( state ) {
9756 OO.ui.RadioInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
9757 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
9758 this.setSelected( state.checked );
9759 }
9760 };
9761
9762 /**
9763 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
9764 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
9765 * of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9766 * more information about input widgets.
9767 *
9768 * This and OO.ui.DropdownInputWidget support the same configuration options.
9769 *
9770 * @example
9771 * // Example: A RadioSelectInputWidget with three options
9772 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
9773 * options: [
9774 * { data: 'a', label: 'First' },
9775 * { data: 'b', label: 'Second'},
9776 * { data: 'c', label: 'Third' }
9777 * ]
9778 * } );
9779 * $( 'body' ).append( radioSelectInput.$element );
9780 *
9781 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9782 *
9783 * @class
9784 * @extends OO.ui.InputWidget
9785 *
9786 * @constructor
9787 * @param {Object} [config] Configuration options
9788 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9789 */
9790 OO.ui.RadioSelectInputWidget = function OoUiRadioSelectInputWidget( config ) {
9791 // Configuration initialization
9792 config = config || {};
9793
9794 // Properties (must be done before parent constructor which calls #setDisabled)
9795 this.radioSelectWidget = new OO.ui.RadioSelectWidget();
9796 // Set up the options before parent constructor, which uses them to validate config.value.
9797 // Use this instead of setOptions() because this.$input is not set up yet
9798 this.setOptionsData( config.options || [] );
9799
9800 // Parent constructor
9801 OO.ui.RadioSelectInputWidget.parent.call( this, config );
9802
9803 // Events
9804 this.radioSelectWidget.connect( this, { select: 'onMenuSelect' } );
9805
9806 // Initialization
9807 this.$element
9808 .addClass( 'oo-ui-radioSelectInputWidget' )
9809 .append( this.radioSelectWidget.$element );
9810 this.setTabIndexedElement( this.radioSelectWidget.$tabIndexed );
9811 };
9812
9813 /* Setup */
9814
9815 OO.inheritClass( OO.ui.RadioSelectInputWidget, OO.ui.InputWidget );
9816
9817 /* Static Methods */
9818
9819 /**
9820 * @inheritdoc
9821 */
9822 OO.ui.RadioSelectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
9823 var state = OO.ui.RadioSelectInputWidget.parent.static.gatherPreInfuseState( node, config );
9824 state.value = $( node ).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
9825 return state;
9826 };
9827
9828 /**
9829 * @inheritdoc
9830 */
9831 OO.ui.RadioSelectInputWidget.static.reusePreInfuseDOM = function ( node, config ) {
9832 config = OO.ui.RadioSelectInputWidget.parent.static.reusePreInfuseDOM( node, config );
9833 // Cannot reuse the `<input type=radio>` set
9834 delete config.$input;
9835 return config;
9836 };
9837
9838 /* Methods */
9839
9840 /**
9841 * @inheritdoc
9842 * @protected
9843 */
9844 OO.ui.RadioSelectInputWidget.prototype.getInputElement = function () {
9845 // Use this instead of <input type="hidden">, because hidden inputs do not have separate
9846 // 'value' and 'defaultValue' properties, and InputWidget wants to handle 'defaultValue'.
9847 return $( '<input>' ).addClass( 'oo-ui-element-hidden' );
9848 };
9849
9850 /**
9851 * Handles menu select events.
9852 *
9853 * @private
9854 * @param {OO.ui.RadioOptionWidget} item Selected menu item
9855 */
9856 OO.ui.RadioSelectInputWidget.prototype.onMenuSelect = function ( item ) {
9857 this.setValue( item.getData() );
9858 };
9859
9860 /**
9861 * @inheritdoc
9862 */
9863 OO.ui.RadioSelectInputWidget.prototype.setValue = function ( value ) {
9864 var selected;
9865 value = this.cleanUpValue( value );
9866 // Only allow setting values that are actually present in the dropdown
9867 selected = this.radioSelectWidget.findItemFromData( value ) ||
9868 this.radioSelectWidget.findFirstSelectableItem();
9869 this.radioSelectWidget.selectItem( selected );
9870 value = selected ? selected.getData() : '';
9871 OO.ui.RadioSelectInputWidget.parent.prototype.setValue.call( this, value );
9872 return this;
9873 };
9874
9875 /**
9876 * @inheritdoc
9877 */
9878 OO.ui.RadioSelectInputWidget.prototype.setDisabled = function ( state ) {
9879 this.radioSelectWidget.setDisabled( state );
9880 OO.ui.RadioSelectInputWidget.parent.prototype.setDisabled.call( this, state );
9881 return this;
9882 };
9883
9884 /**
9885 * Set the options available for this input.
9886 *
9887 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9888 * @chainable
9889 */
9890 OO.ui.RadioSelectInputWidget.prototype.setOptions = function ( options ) {
9891 var value = this.getValue();
9892
9893 this.setOptionsData( options );
9894
9895 // Re-set the value to update the visible interface (RadioSelectWidget).
9896 // In case the previous value is no longer an available option, select the first valid one.
9897 this.setValue( value );
9898
9899 return this;
9900 };
9901
9902 /**
9903 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
9904 *
9905 * This method may be called before the parent constructor, so various properties may not be
9906 * intialized yet.
9907 *
9908 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9909 * @private
9910 */
9911 OO.ui.RadioSelectInputWidget.prototype.setOptionsData = function ( options ) {
9912 var widget = this;
9913
9914 this.radioSelectWidget
9915 .clearItems()
9916 .addItems( options.map( function ( opt ) {
9917 var optValue = widget.cleanUpValue( opt.data );
9918 return new OO.ui.RadioOptionWidget( {
9919 data: optValue,
9920 label: opt.label !== undefined ? opt.label : optValue
9921 } );
9922 } ) );
9923 };
9924
9925 /**
9926 * @inheritdoc
9927 */
9928 OO.ui.RadioSelectInputWidget.prototype.focus = function () {
9929 this.radioSelectWidget.focus();
9930 return this;
9931 };
9932
9933 /**
9934 * @inheritdoc
9935 */
9936 OO.ui.RadioSelectInputWidget.prototype.blur = function () {
9937 this.radioSelectWidget.blur();
9938 return this;
9939 };
9940
9941 /**
9942 * CheckboxMultiselectInputWidget is a
9943 * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
9944 * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
9945 * HTML `<input type=checkbox>` tags. Please see the [OOUI documentation on MediaWiki][1] for
9946 * more information about input widgets.
9947 *
9948 * @example
9949 * // Example: A CheckboxMultiselectInputWidget with three options
9950 * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
9951 * options: [
9952 * { data: 'a', label: 'First' },
9953 * { data: 'b', label: 'Second'},
9954 * { data: 'c', label: 'Third' }
9955 * ]
9956 * } );
9957 * $( 'body' ).append( multiselectInput.$element );
9958 *
9959 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9960 *
9961 * @class
9962 * @extends OO.ui.InputWidget
9963 *
9964 * @constructor
9965 * @param {Object} [config] Configuration options
9966 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: …, disabled: … }`
9967 */
9968 OO.ui.CheckboxMultiselectInputWidget = function OoUiCheckboxMultiselectInputWidget( config ) {
9969 // Configuration initialization
9970 config = config || {};
9971
9972 // Properties (must be done before parent constructor which calls #setDisabled)
9973 this.checkboxMultiselectWidget = new OO.ui.CheckboxMultiselectWidget();
9974 // Must be set before the #setOptionsData call below
9975 this.inputName = config.name;
9976 // Set up the options before parent constructor, which uses them to validate config.value.
9977 // Use this instead of setOptions() because this.$input is not set up yet
9978 this.setOptionsData( config.options || [] );
9979
9980 // Parent constructor
9981 OO.ui.CheckboxMultiselectInputWidget.parent.call( this, config );
9982
9983 // Events
9984 this.checkboxMultiselectWidget.connect( this, { select: 'onCheckboxesSelect' } );
9985
9986 // Initialization
9987 this.$element
9988 .addClass( 'oo-ui-checkboxMultiselectInputWidget' )
9989 .append( this.checkboxMultiselectWidget.$element );
9990 // We don't use this.$input, but rather the CheckboxInputWidgets inside each option
9991 this.$input.detach();
9992 };
9993
9994 /* Setup */
9995
9996 OO.inheritClass( OO.ui.CheckboxMultiselectInputWidget, OO.ui.InputWidget );
9997
9998 /* Static Methods */
9999
10000 /**
10001 * @inheritdoc
10002 */
10003 OO.ui.CheckboxMultiselectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
10004 var state = OO.ui.CheckboxMultiselectInputWidget.parent.static.gatherPreInfuseState( node, config );
10005 state.value = $( node ).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
10006 .toArray().map( function ( el ) { return el.value; } );
10007 return state;
10008 };
10009
10010 /**
10011 * @inheritdoc
10012 */
10013 OO.ui.CheckboxMultiselectInputWidget.static.reusePreInfuseDOM = function ( node, config ) {
10014 config = OO.ui.CheckboxMultiselectInputWidget.parent.static.reusePreInfuseDOM( node, config );
10015 // Cannot reuse the `<input type=checkbox>` set
10016 delete config.$input;
10017 return config;
10018 };
10019
10020 /* Methods */
10021
10022 /**
10023 * @inheritdoc
10024 * @protected
10025 */
10026 OO.ui.CheckboxMultiselectInputWidget.prototype.getInputElement = function () {
10027 // Actually unused
10028 return $( '<unused>' );
10029 };
10030
10031 /**
10032 * Handles CheckboxMultiselectWidget select events.
10033 *
10034 * @private
10035 */
10036 OO.ui.CheckboxMultiselectInputWidget.prototype.onCheckboxesSelect = function () {
10037 this.setValue( this.checkboxMultiselectWidget.findSelectedItemsData() );
10038 };
10039
10040 /**
10041 * @inheritdoc
10042 */
10043 OO.ui.CheckboxMultiselectInputWidget.prototype.getValue = function () {
10044 var value = this.$element.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
10045 .toArray().map( function ( el ) { return el.value; } );
10046 if ( this.value !== value ) {
10047 this.setValue( value );
10048 }
10049 return this.value;
10050 };
10051
10052 /**
10053 * @inheritdoc
10054 */
10055 OO.ui.CheckboxMultiselectInputWidget.prototype.setValue = function ( value ) {
10056 value = this.cleanUpValue( value );
10057 this.checkboxMultiselectWidget.selectItemsByData( value );
10058 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.setValue.call( this, value );
10059 if ( this.optionsDirty ) {
10060 // We reached this from the constructor or from #setOptions.
10061 // We have to update the <select> element.
10062 this.updateOptionsInterface();
10063 }
10064 return this;
10065 };
10066
10067 /**
10068 * Clean up incoming value.
10069 *
10070 * @param {string[]} value Original value
10071 * @return {string[]} Cleaned up value
10072 */
10073 OO.ui.CheckboxMultiselectInputWidget.prototype.cleanUpValue = function ( value ) {
10074 var i, singleValue,
10075 cleanValue = [];
10076 if ( !Array.isArray( value ) ) {
10077 return cleanValue;
10078 }
10079 for ( i = 0; i < value.length; i++ ) {
10080 singleValue =
10081 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.cleanUpValue.call( this, value[ i ] );
10082 // Remove options that we don't have here
10083 if ( !this.checkboxMultiselectWidget.findItemFromData( singleValue ) ) {
10084 continue;
10085 }
10086 cleanValue.push( singleValue );
10087 }
10088 return cleanValue;
10089 };
10090
10091 /**
10092 * @inheritdoc
10093 */
10094 OO.ui.CheckboxMultiselectInputWidget.prototype.setDisabled = function ( state ) {
10095 this.checkboxMultiselectWidget.setDisabled( state );
10096 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.setDisabled.call( this, state );
10097 return this;
10098 };
10099
10100 /**
10101 * Set the options available for this input.
10102 *
10103 * @param {Object[]} options Array of menu options in the format `{ data: …, label: …, disabled: … }`
10104 * @chainable
10105 */
10106 OO.ui.CheckboxMultiselectInputWidget.prototype.setOptions = function ( options ) {
10107 var value = this.getValue();
10108
10109 this.setOptionsData( options );
10110
10111 // Re-set the value to update the visible interface (CheckboxMultiselectWidget).
10112 // This will also get rid of any stale options that we just removed.
10113 this.setValue( value );
10114
10115 return this;
10116 };
10117
10118 /**
10119 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
10120 *
10121 * This method may be called before the parent constructor, so various properties may not be
10122 * intialized yet.
10123 *
10124 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10125 * @private
10126 */
10127 OO.ui.CheckboxMultiselectInputWidget.prototype.setOptionsData = function ( options ) {
10128 var widget = this;
10129
10130 this.optionsDirty = true;
10131
10132 this.checkboxMultiselectWidget
10133 .clearItems()
10134 .addItems( options.map( function ( opt ) {
10135 var optValue, item, optDisabled;
10136 optValue =
10137 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.cleanUpValue.call( widget, opt.data );
10138 optDisabled = opt.disabled !== undefined ? opt.disabled : false;
10139 item = new OO.ui.CheckboxMultioptionWidget( {
10140 data: optValue,
10141 label: opt.label !== undefined ? opt.label : optValue,
10142 disabled: optDisabled
10143 } );
10144 // Set the 'name' and 'value' for form submission
10145 item.checkbox.$input.attr( 'name', widget.inputName );
10146 item.checkbox.setValue( optValue );
10147 return item;
10148 } ) );
10149 };
10150
10151 /**
10152 * Update the user-visible interface to match the internal list of options and value.
10153 *
10154 * This method must only be called after the parent constructor.
10155 *
10156 * @private
10157 */
10158 OO.ui.CheckboxMultiselectInputWidget.prototype.updateOptionsInterface = function () {
10159 var defaultValue = this.defaultValue;
10160
10161 this.checkboxMultiselectWidget.getItems().forEach( function ( item ) {
10162 // Remember original selection state. This property can be later used to check whether
10163 // the selection state of the input has been changed since it was created.
10164 var isDefault = defaultValue.indexOf( item.getData() ) !== -1;
10165 item.checkbox.defaultSelected = isDefault;
10166 item.checkbox.$input[ 0 ].defaultChecked = isDefault;
10167 } );
10168
10169 this.optionsDirty = false;
10170 };
10171
10172 /**
10173 * @inheritdoc
10174 */
10175 OO.ui.CheckboxMultiselectInputWidget.prototype.focus = function () {
10176 this.checkboxMultiselectWidget.focus();
10177 return this;
10178 };
10179
10180 /**
10181 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
10182 * size of the field as well as its presentation. In addition, these widgets can be configured
10183 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
10184 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
10185 * which modifies incoming values rather than validating them.
10186 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
10187 *
10188 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
10189 *
10190 * @example
10191 * // Example of a text input widget
10192 * var textInput = new OO.ui.TextInputWidget( {
10193 * value: 'Text input'
10194 * } )
10195 * $( 'body' ).append( textInput.$element );
10196 *
10197 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
10198 *
10199 * @class
10200 * @extends OO.ui.InputWidget
10201 * @mixins OO.ui.mixin.IconElement
10202 * @mixins OO.ui.mixin.IndicatorElement
10203 * @mixins OO.ui.mixin.PendingElement
10204 * @mixins OO.ui.mixin.LabelElement
10205 *
10206 * @constructor
10207 * @param {Object} [config] Configuration options
10208 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password'
10209 * 'email', 'url' or 'number'.
10210 * @cfg {string} [placeholder] Placeholder text
10211 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
10212 * instruct the browser to focus this widget.
10213 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
10214 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
10215 *
10216 * For unfortunate historical reasons, this counts the number of UTF-16 code units rather than
10217 * Unicode codepoints, which means that codepoints outside the Basic Multilingual Plane (e.g.
10218 * many emojis) count as 2 characters each.
10219 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
10220 * the value or placeholder text: `'before'` or `'after'`
10221 * @cfg {boolean} [required=false] Mark the field as required with `true`. Implies `indicator: 'required'`.
10222 * Note that `false` & setting `indicator: 'required' will result in no indicator shown.
10223 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
10224 * @cfg {boolean} [spellcheck] Should the browser support spellcheck for this field (`undefined` means
10225 * leaving it up to the browser).
10226 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
10227 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
10228 * (the value must contain only numbers); when RegExp, a regular expression that must match the
10229 * value for it to be considered valid; when Function, a function receiving the value as parameter
10230 * that must return true, or promise resolving to true, for it to be considered valid.
10231 */
10232 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
10233 // Configuration initialization
10234 config = $.extend( {
10235 type: 'text',
10236 labelPosition: 'after'
10237 }, config );
10238
10239 // Parent constructor
10240 OO.ui.TextInputWidget.parent.call( this, config );
10241
10242 // Mixin constructors
10243 OO.ui.mixin.IconElement.call( this, config );
10244 OO.ui.mixin.IndicatorElement.call( this, config );
10245 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$input } ) );
10246 OO.ui.mixin.LabelElement.call( this, config );
10247
10248 // Properties
10249 this.type = this.getSaneType( config );
10250 this.readOnly = false;
10251 this.required = false;
10252 this.validate = null;
10253 this.styleHeight = null;
10254 this.scrollWidth = null;
10255
10256 this.setValidation( config.validate );
10257 this.setLabelPosition( config.labelPosition );
10258
10259 // Events
10260 this.$input.on( {
10261 keypress: this.onKeyPress.bind( this ),
10262 blur: this.onBlur.bind( this ),
10263 focus: this.onFocus.bind( this )
10264 } );
10265 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
10266 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
10267 this.on( 'labelChange', this.updatePosition.bind( this ) );
10268 this.on( 'change', OO.ui.debounce( this.onDebouncedChange.bind( this ), 250 ) );
10269
10270 // Initialization
10271 this.$element
10272 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type )
10273 .append( this.$icon, this.$indicator );
10274 this.setReadOnly( !!config.readOnly );
10275 this.setRequired( !!config.required );
10276 if ( config.placeholder !== undefined ) {
10277 this.$input.attr( 'placeholder', config.placeholder );
10278 }
10279 if ( config.maxLength !== undefined ) {
10280 this.$input.attr( 'maxlength', config.maxLength );
10281 }
10282 if ( config.autofocus ) {
10283 this.$input.attr( 'autofocus', 'autofocus' );
10284 }
10285 if ( config.autocomplete === false ) {
10286 this.$input.attr( 'autocomplete', 'off' );
10287 // Turning off autocompletion also disables "form caching" when the user navigates to a
10288 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
10289 $( window ).on( {
10290 beforeunload: function () {
10291 this.$input.removeAttr( 'autocomplete' );
10292 }.bind( this ),
10293 pageshow: function () {
10294 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
10295 // whole page... it shouldn't hurt, though.
10296 this.$input.attr( 'autocomplete', 'off' );
10297 }.bind( this )
10298 } );
10299 }
10300 if ( config.spellcheck !== undefined ) {
10301 this.$input.attr( 'spellcheck', config.spellcheck ? 'true' : 'false' );
10302 }
10303 if ( this.label ) {
10304 this.isWaitingToBeAttached = true;
10305 this.installParentChangeDetector();
10306 }
10307 };
10308
10309 /* Setup */
10310
10311 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
10312 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IconElement );
10313 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IndicatorElement );
10314 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.PendingElement );
10315 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.LabelElement );
10316
10317 /* Static Properties */
10318
10319 OO.ui.TextInputWidget.static.validationPatterns = {
10320 'non-empty': /.+/,
10321 integer: /^\d+$/
10322 };
10323
10324 /* Events */
10325
10326 /**
10327 * An `enter` event is emitted when the user presses 'enter' inside the text box.
10328 *
10329 * @event enter
10330 */
10331
10332 /* Methods */
10333
10334 /**
10335 * Handle icon mouse down events.
10336 *
10337 * @private
10338 * @param {jQuery.Event} e Mouse down event
10339 */
10340 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
10341 if ( e.which === OO.ui.MouseButtons.LEFT ) {
10342 this.focus();
10343 return false;
10344 }
10345 };
10346
10347 /**
10348 * Handle indicator mouse down events.
10349 *
10350 * @private
10351 * @param {jQuery.Event} e Mouse down event
10352 */
10353 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
10354 if ( e.which === OO.ui.MouseButtons.LEFT ) {
10355 this.focus();
10356 return false;
10357 }
10358 };
10359
10360 /**
10361 * Handle key press events.
10362 *
10363 * @private
10364 * @param {jQuery.Event} e Key press event
10365 * @fires enter If enter key is pressed
10366 */
10367 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
10368 if ( e.which === OO.ui.Keys.ENTER ) {
10369 this.emit( 'enter', e );
10370 }
10371 };
10372
10373 /**
10374 * Handle blur events.
10375 *
10376 * @private
10377 * @param {jQuery.Event} e Blur event
10378 */
10379 OO.ui.TextInputWidget.prototype.onBlur = function () {
10380 this.setValidityFlag();
10381 };
10382
10383 /**
10384 * Handle focus events.
10385 *
10386 * @private
10387 * @param {jQuery.Event} e Focus event
10388 */
10389 OO.ui.TextInputWidget.prototype.onFocus = function () {
10390 if ( this.isWaitingToBeAttached ) {
10391 // If we've received focus, then we must be attached to the document, and if
10392 // isWaitingToBeAttached is still true, that means the handler never fired. Fire it now.
10393 this.onElementAttach();
10394 }
10395 this.setValidityFlag( true );
10396 };
10397
10398 /**
10399 * Handle element attach events.
10400 *
10401 * @private
10402 * @param {jQuery.Event} e Element attach event
10403 */
10404 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
10405 this.isWaitingToBeAttached = false;
10406 // Any previously calculated size is now probably invalid if we reattached elsewhere
10407 this.valCache = null;
10408 this.positionLabel();
10409 };
10410
10411 /**
10412 * Handle debounced change events.
10413 *
10414 * @param {string} value
10415 * @private
10416 */
10417 OO.ui.TextInputWidget.prototype.onDebouncedChange = function () {
10418 this.setValidityFlag();
10419 };
10420
10421 /**
10422 * Check if the input is {@link #readOnly read-only}.
10423 *
10424 * @return {boolean}
10425 */
10426 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
10427 return this.readOnly;
10428 };
10429
10430 /**
10431 * Set the {@link #readOnly read-only} state of the input.
10432 *
10433 * @param {boolean} state Make input read-only
10434 * @chainable
10435 */
10436 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
10437 this.readOnly = !!state;
10438 this.$input.prop( 'readOnly', this.readOnly );
10439 return this;
10440 };
10441
10442 /**
10443 * Check if the input is {@link #required required}.
10444 *
10445 * @return {boolean}
10446 */
10447 OO.ui.TextInputWidget.prototype.isRequired = function () {
10448 return this.required;
10449 };
10450
10451 /**
10452 * Set the {@link #required required} state of the input.
10453 *
10454 * @param {boolean} state Make input required
10455 * @chainable
10456 */
10457 OO.ui.TextInputWidget.prototype.setRequired = function ( state ) {
10458 this.required = !!state;
10459 if ( this.required ) {
10460 this.$input
10461 .prop( 'required', true )
10462 .attr( 'aria-required', 'true' );
10463 if ( this.getIndicator() === null ) {
10464 this.setIndicator( 'required' );
10465 }
10466 } else {
10467 this.$input
10468 .prop( 'required', false )
10469 .removeAttr( 'aria-required' );
10470 if ( this.getIndicator() === 'required' ) {
10471 this.setIndicator( null );
10472 }
10473 }
10474 return this;
10475 };
10476
10477 /**
10478 * Support function for making #onElementAttach work across browsers.
10479 *
10480 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
10481 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
10482 *
10483 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
10484 * first time that the element gets attached to the documented.
10485 */
10486 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
10487 var mutationObserver, onRemove, topmostNode, fakeParentNode,
10488 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
10489 widget = this;
10490
10491 if ( MutationObserver ) {
10492 // The new way. If only it wasn't so ugly.
10493
10494 if ( this.isElementAttached() ) {
10495 // Widget is attached already, do nothing. This breaks the functionality of this function when
10496 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
10497 // would require observation of the whole document, which would hurt performance of other,
10498 // more important code.
10499 return;
10500 }
10501
10502 // Find topmost node in the tree
10503 topmostNode = this.$element[ 0 ];
10504 while ( topmostNode.parentNode ) {
10505 topmostNode = topmostNode.parentNode;
10506 }
10507
10508 // We have no way to detect the $element being attached somewhere without observing the entire
10509 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
10510 // parent node of $element, and instead detect when $element is removed from it (and thus
10511 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
10512 // doesn't get attached, we end up back here and create the parent.
10513
10514 mutationObserver = new MutationObserver( function ( mutations ) {
10515 var i, j, removedNodes;
10516 for ( i = 0; i < mutations.length; i++ ) {
10517 removedNodes = mutations[ i ].removedNodes;
10518 for ( j = 0; j < removedNodes.length; j++ ) {
10519 if ( removedNodes[ j ] === topmostNode ) {
10520 setTimeout( onRemove, 0 );
10521 return;
10522 }
10523 }
10524 }
10525 } );
10526
10527 onRemove = function () {
10528 // If the node was attached somewhere else, report it
10529 if ( widget.isElementAttached() ) {
10530 widget.onElementAttach();
10531 }
10532 mutationObserver.disconnect();
10533 widget.installParentChangeDetector();
10534 };
10535
10536 // Create a fake parent and observe it
10537 fakeParentNode = $( '<div>' ).append( topmostNode )[ 0 ];
10538 mutationObserver.observe( fakeParentNode, { childList: true } );
10539 } else {
10540 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
10541 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
10542 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
10543 }
10544 };
10545
10546 /**
10547 * @inheritdoc
10548 * @protected
10549 */
10550 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
10551 if ( this.getSaneType( config ) === 'number' ) {
10552 return $( '<input>' )
10553 .attr( 'step', 'any' )
10554 .attr( 'type', 'number' );
10555 } else {
10556 return $( '<input>' ).attr( 'type', this.getSaneType( config ) );
10557 }
10558 };
10559
10560 /**
10561 * Get sanitized value for 'type' for given config.
10562 *
10563 * @param {Object} config Configuration options
10564 * @return {string|null}
10565 * @protected
10566 */
10567 OO.ui.TextInputWidget.prototype.getSaneType = function ( config ) {
10568 var allowedTypes = [
10569 'text',
10570 'password',
10571 'email',
10572 'url',
10573 'number'
10574 ];
10575 return allowedTypes.indexOf( config.type ) !== -1 ? config.type : 'text';
10576 };
10577
10578 /**
10579 * Focus the input and select a specified range within the text.
10580 *
10581 * @param {number} from Select from offset
10582 * @param {number} [to] Select to offset, defaults to from
10583 * @chainable
10584 */
10585 OO.ui.TextInputWidget.prototype.selectRange = function ( from, to ) {
10586 var isBackwards, start, end,
10587 input = this.$input[ 0 ];
10588
10589 to = to || from;
10590
10591 isBackwards = to < from;
10592 start = isBackwards ? to : from;
10593 end = isBackwards ? from : to;
10594
10595 this.focus();
10596
10597 try {
10598 input.setSelectionRange( start, end, isBackwards ? 'backward' : 'forward' );
10599 } catch ( e ) {
10600 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
10601 // Rather than expensively check if the input is attached every time, just check
10602 // if it was the cause of an error being thrown. If not, rethrow the error.
10603 if ( this.getElementDocument().body.contains( input ) ) {
10604 throw e;
10605 }
10606 }
10607 return this;
10608 };
10609
10610 /**
10611 * Get an object describing the current selection range in a directional manner
10612 *
10613 * @return {Object} Object containing 'from' and 'to' offsets
10614 */
10615 OO.ui.TextInputWidget.prototype.getRange = function () {
10616 var input = this.$input[ 0 ],
10617 start = input.selectionStart,
10618 end = input.selectionEnd,
10619 isBackwards = input.selectionDirection === 'backward';
10620
10621 return {
10622 from: isBackwards ? end : start,
10623 to: isBackwards ? start : end
10624 };
10625 };
10626
10627 /**
10628 * Get the length of the text input value.
10629 *
10630 * This could differ from the length of #getValue if the
10631 * value gets filtered
10632 *
10633 * @return {number} Input length
10634 */
10635 OO.ui.TextInputWidget.prototype.getInputLength = function () {
10636 return this.$input[ 0 ].value.length;
10637 };
10638
10639 /**
10640 * Focus the input and select the entire text.
10641 *
10642 * @chainable
10643 */
10644 OO.ui.TextInputWidget.prototype.select = function () {
10645 return this.selectRange( 0, this.getInputLength() );
10646 };
10647
10648 /**
10649 * Focus the input and move the cursor to the start.
10650 *
10651 * @chainable
10652 */
10653 OO.ui.TextInputWidget.prototype.moveCursorToStart = function () {
10654 return this.selectRange( 0 );
10655 };
10656
10657 /**
10658 * Focus the input and move the cursor to the end.
10659 *
10660 * @chainable
10661 */
10662 OO.ui.TextInputWidget.prototype.moveCursorToEnd = function () {
10663 return this.selectRange( this.getInputLength() );
10664 };
10665
10666 /**
10667 * Insert new content into the input.
10668 *
10669 * @param {string} content Content to be inserted
10670 * @chainable
10671 */
10672 OO.ui.TextInputWidget.prototype.insertContent = function ( content ) {
10673 var start, end,
10674 range = this.getRange(),
10675 value = this.getValue();
10676
10677 start = Math.min( range.from, range.to );
10678 end = Math.max( range.from, range.to );
10679
10680 this.setValue( value.slice( 0, start ) + content + value.slice( end ) );
10681 this.selectRange( start + content.length );
10682 return this;
10683 };
10684
10685 /**
10686 * Insert new content either side of a selection.
10687 *
10688 * @param {string} pre Content to be inserted before the selection
10689 * @param {string} post Content to be inserted after the selection
10690 * @chainable
10691 */
10692 OO.ui.TextInputWidget.prototype.encapsulateContent = function ( pre, post ) {
10693 var start, end,
10694 range = this.getRange(),
10695 offset = pre.length;
10696
10697 start = Math.min( range.from, range.to );
10698 end = Math.max( range.from, range.to );
10699
10700 this.selectRange( start ).insertContent( pre );
10701 this.selectRange( offset + end ).insertContent( post );
10702
10703 this.selectRange( offset + start, offset + end );
10704 return this;
10705 };
10706
10707 /**
10708 * Set the validation pattern.
10709 *
10710 * The validation pattern is either a regular expression, a function, or the symbolic name of a
10711 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
10712 * value must contain only numbers).
10713 *
10714 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
10715 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
10716 */
10717 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
10718 if ( validate instanceof RegExp || validate instanceof Function ) {
10719 this.validate = validate;
10720 } else {
10721 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
10722 }
10723 };
10724
10725 /**
10726 * Sets the 'invalid' flag appropriately.
10727 *
10728 * @param {boolean} [isValid] Optionally override validation result
10729 */
10730 OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) {
10731 var widget = this,
10732 setFlag = function ( valid ) {
10733 if ( !valid ) {
10734 widget.$input.attr( 'aria-invalid', 'true' );
10735 } else {
10736 widget.$input.removeAttr( 'aria-invalid' );
10737 }
10738 widget.setFlags( { invalid: !valid } );
10739 };
10740
10741 if ( isValid !== undefined ) {
10742 setFlag( isValid );
10743 } else {
10744 this.getValidity().then( function () {
10745 setFlag( true );
10746 }, function () {
10747 setFlag( false );
10748 } );
10749 }
10750 };
10751
10752 /**
10753 * Get the validity of current value.
10754 *
10755 * This method returns a promise that resolves if the value is valid and rejects if
10756 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
10757 *
10758 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
10759 */
10760 OO.ui.TextInputWidget.prototype.getValidity = function () {
10761 var result;
10762
10763 function rejectOrResolve( valid ) {
10764 if ( valid ) {
10765 return $.Deferred().resolve().promise();
10766 } else {
10767 return $.Deferred().reject().promise();
10768 }
10769 }
10770
10771 // Check browser validity and reject if it is invalid
10772 if (
10773 this.$input[ 0 ].checkValidity !== undefined &&
10774 this.$input[ 0 ].checkValidity() === false
10775 ) {
10776 return rejectOrResolve( false );
10777 }
10778
10779 // Run our checks if the browser thinks the field is valid
10780 if ( this.validate instanceof Function ) {
10781 result = this.validate( this.getValue() );
10782 if ( result && $.isFunction( result.promise ) ) {
10783 return result.promise().then( function ( valid ) {
10784 return rejectOrResolve( valid );
10785 } );
10786 } else {
10787 return rejectOrResolve( result );
10788 }
10789 } else {
10790 return rejectOrResolve( this.getValue().match( this.validate ) );
10791 }
10792 };
10793
10794 /**
10795 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
10796 *
10797 * @param {string} labelPosition Label position, 'before' or 'after'
10798 * @chainable
10799 */
10800 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
10801 this.labelPosition = labelPosition;
10802 if ( this.label ) {
10803 // If there is no label and we only change the position, #updatePosition is a no-op,
10804 // but it takes really a lot of work to do nothing.
10805 this.updatePosition();
10806 }
10807 return this;
10808 };
10809
10810 /**
10811 * Update the position of the inline label.
10812 *
10813 * This method is called by #setLabelPosition, and can also be called on its own if
10814 * something causes the label to be mispositioned.
10815 *
10816 * @chainable
10817 */
10818 OO.ui.TextInputWidget.prototype.updatePosition = function () {
10819 var after = this.labelPosition === 'after';
10820
10821 this.$element
10822 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
10823 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
10824
10825 this.valCache = null;
10826 this.scrollWidth = null;
10827 this.positionLabel();
10828
10829 return this;
10830 };
10831
10832 /**
10833 * Position the label by setting the correct padding on the input.
10834 *
10835 * @private
10836 * @chainable
10837 */
10838 OO.ui.TextInputWidget.prototype.positionLabel = function () {
10839 var after, rtl, property, newCss;
10840
10841 if ( this.isWaitingToBeAttached ) {
10842 // #onElementAttach will be called soon, which calls this method
10843 return this;
10844 }
10845
10846 newCss = {
10847 'padding-right': '',
10848 'padding-left': ''
10849 };
10850
10851 if ( this.label ) {
10852 this.$element.append( this.$label );
10853 } else {
10854 this.$label.detach();
10855 // Clear old values if present
10856 this.$input.css( newCss );
10857 return;
10858 }
10859
10860 after = this.labelPosition === 'after';
10861 rtl = this.$element.css( 'direction' ) === 'rtl';
10862 property = after === rtl ? 'padding-left' : 'padding-right';
10863
10864 newCss[ property ] = this.$label.outerWidth( true ) + ( after ? this.scrollWidth : 0 );
10865 // We have to clear the padding on the other side, in case the element direction changed
10866 this.$input.css( newCss );
10867
10868 return this;
10869 };
10870
10871 /**
10872 * @class
10873 * @extends OO.ui.TextInputWidget
10874 *
10875 * @constructor
10876 * @param {Object} [config] Configuration options
10877 */
10878 OO.ui.SearchInputWidget = function OoUiSearchInputWidget( config ) {
10879 config = $.extend( {
10880 icon: 'search'
10881 }, config );
10882
10883 // Parent constructor
10884 OO.ui.SearchInputWidget.parent.call( this, config );
10885
10886 // Events
10887 this.connect( this, {
10888 change: 'onChange'
10889 } );
10890
10891 // Initialization
10892 this.updateSearchIndicator();
10893 this.connect( this, {
10894 disable: 'onDisable'
10895 } );
10896 };
10897
10898 /* Setup */
10899
10900 OO.inheritClass( OO.ui.SearchInputWidget, OO.ui.TextInputWidget );
10901
10902 /* Methods */
10903
10904 /**
10905 * @inheritdoc
10906 * @protected
10907 */
10908 OO.ui.SearchInputWidget.prototype.getSaneType = function () {
10909 return 'search';
10910 };
10911
10912 /**
10913 * @inheritdoc
10914 */
10915 OO.ui.SearchInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
10916 if ( e.which === OO.ui.MouseButtons.LEFT ) {
10917 // Clear the text field
10918 this.setValue( '' );
10919 this.focus();
10920 return false;
10921 }
10922 };
10923
10924 /**
10925 * Update the 'clear' indicator displayed on type: 'search' text
10926 * fields, hiding it when the field is already empty or when it's not
10927 * editable.
10928 */
10929 OO.ui.SearchInputWidget.prototype.updateSearchIndicator = function () {
10930 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
10931 this.setIndicator( null );
10932 } else {
10933 this.setIndicator( 'clear' );
10934 }
10935 };
10936
10937 /**
10938 * Handle change events.
10939 *
10940 * @private
10941 */
10942 OO.ui.SearchInputWidget.prototype.onChange = function () {
10943 this.updateSearchIndicator();
10944 };
10945
10946 /**
10947 * Handle disable events.
10948 *
10949 * @param {boolean} disabled Element is disabled
10950 * @private
10951 */
10952 OO.ui.SearchInputWidget.prototype.onDisable = function () {
10953 this.updateSearchIndicator();
10954 };
10955
10956 /**
10957 * @inheritdoc
10958 */
10959 OO.ui.SearchInputWidget.prototype.setReadOnly = function ( state ) {
10960 OO.ui.SearchInputWidget.parent.prototype.setReadOnly.call( this, state );
10961 this.updateSearchIndicator();
10962 return this;
10963 };
10964
10965 /**
10966 * @class
10967 * @extends OO.ui.TextInputWidget
10968 *
10969 * @constructor
10970 * @param {Object} [config] Configuration options
10971 * @cfg {number} [rows] Number of visible lines in textarea. If used with `autosize`,
10972 * specifies minimum number of rows to display.
10973 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
10974 * Use the #maxRows config to specify a maximum number of displayed rows.
10975 * @cfg {number} [maxRows] Maximum number of rows to display when #autosize is set to true.
10976 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
10977 */
10978 OO.ui.MultilineTextInputWidget = function OoUiMultilineTextInputWidget( config ) {
10979 config = $.extend( {
10980 type: 'text'
10981 }, config );
10982 // Parent constructor
10983 OO.ui.MultilineTextInputWidget.parent.call( this, config );
10984
10985 // Properties
10986 this.autosize = !!config.autosize;
10987 this.minRows = config.rows !== undefined ? config.rows : '';
10988 this.maxRows = config.maxRows || Math.max( 2 * ( this.minRows || 0 ), 10 );
10989
10990 // Clone for resizing
10991 if ( this.autosize ) {
10992 this.$clone = this.$input
10993 .clone()
10994 .removeAttr( 'id' )
10995 .removeAttr( 'name' )
10996 .insertAfter( this.$input )
10997 .attr( 'aria-hidden', 'true' )
10998 .addClass( 'oo-ui-element-hidden' );
10999 }
11000
11001 // Events
11002 this.connect( this, {
11003 change: 'onChange'
11004 } );
11005
11006 // Initialization
11007 if ( config.rows ) {
11008 this.$input.attr( 'rows', config.rows );
11009 }
11010 if ( this.autosize ) {
11011 this.$input.addClass( 'oo-ui-textInputWidget-autosized' );
11012 this.isWaitingToBeAttached = true;
11013 this.installParentChangeDetector();
11014 }
11015 };
11016
11017 /* Setup */
11018
11019 OO.inheritClass( OO.ui.MultilineTextInputWidget, OO.ui.TextInputWidget );
11020
11021 /* Static Methods */
11022
11023 /**
11024 * @inheritdoc
11025 */
11026 OO.ui.MultilineTextInputWidget.static.gatherPreInfuseState = function ( node, config ) {
11027 var state = OO.ui.MultilineTextInputWidget.parent.static.gatherPreInfuseState( node, config );
11028 state.scrollTop = config.$input.scrollTop();
11029 return state;
11030 };
11031
11032 /* Methods */
11033
11034 /**
11035 * @inheritdoc
11036 */
11037 OO.ui.MultilineTextInputWidget.prototype.onElementAttach = function () {
11038 OO.ui.MultilineTextInputWidget.parent.prototype.onElementAttach.call( this );
11039 this.adjustSize();
11040 };
11041
11042 /**
11043 * Handle change events.
11044 *
11045 * @private
11046 */
11047 OO.ui.MultilineTextInputWidget.prototype.onChange = function () {
11048 this.adjustSize();
11049 };
11050
11051 /**
11052 * @inheritdoc
11053 */
11054 OO.ui.MultilineTextInputWidget.prototype.updatePosition = function () {
11055 OO.ui.MultilineTextInputWidget.parent.prototype.updatePosition.call( this );
11056 this.adjustSize();
11057 };
11058
11059 /**
11060 * @inheritdoc
11061 *
11062 * Modify to emit 'enter' on Ctrl/Meta+Enter, instead of plain Enter
11063 */
11064 OO.ui.MultilineTextInputWidget.prototype.onKeyPress = function ( e ) {
11065 if (
11066 ( e.which === OO.ui.Keys.ENTER && ( e.ctrlKey || e.metaKey ) ) ||
11067 // Some platforms emit keycode 10 for ctrl+enter in a textarea
11068 e.which === 10
11069 ) {
11070 this.emit( 'enter', e );
11071 }
11072 };
11073
11074 /**
11075 * Automatically adjust the size of the text input.
11076 *
11077 * This only affects multiline inputs that are {@link #autosize autosized}.
11078 *
11079 * @chainable
11080 * @fires resize
11081 */
11082 OO.ui.MultilineTextInputWidget.prototype.adjustSize = function () {
11083 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError,
11084 idealHeight, newHeight, scrollWidth, property;
11085
11086 if ( this.$input.val() !== this.valCache ) {
11087 if ( this.autosize ) {
11088 this.$clone
11089 .val( this.$input.val() )
11090 .attr( 'rows', this.minRows )
11091 // Set inline height property to 0 to measure scroll height
11092 .css( 'height', 0 );
11093
11094 this.$clone.removeClass( 'oo-ui-element-hidden' );
11095
11096 this.valCache = this.$input.val();
11097
11098 scrollHeight = this.$clone[ 0 ].scrollHeight;
11099
11100 // Remove inline height property to measure natural heights
11101 this.$clone.css( 'height', '' );
11102 innerHeight = this.$clone.innerHeight();
11103 outerHeight = this.$clone.outerHeight();
11104
11105 // Measure max rows height
11106 this.$clone
11107 .attr( 'rows', this.maxRows )
11108 .css( 'height', 'auto' )
11109 .val( '' );
11110 maxInnerHeight = this.$clone.innerHeight();
11111
11112 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
11113 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
11114 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
11115 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
11116
11117 this.$clone.addClass( 'oo-ui-element-hidden' );
11118
11119 // Only apply inline height when expansion beyond natural height is needed
11120 // Use the difference between the inner and outer height as a buffer
11121 newHeight = idealHeight > innerHeight ? idealHeight + ( outerHeight - innerHeight ) : '';
11122 if ( newHeight !== this.styleHeight ) {
11123 this.$input.css( 'height', newHeight );
11124 this.styleHeight = newHeight;
11125 this.emit( 'resize' );
11126 }
11127 }
11128 scrollWidth = this.$input[ 0 ].offsetWidth - this.$input[ 0 ].clientWidth;
11129 if ( scrollWidth !== this.scrollWidth ) {
11130 property = this.$element.css( 'direction' ) === 'rtl' ? 'left' : 'right';
11131 // Reset
11132 this.$label.css( { right: '', left: '' } );
11133 this.$indicator.css( { right: '', left: '' } );
11134
11135 if ( scrollWidth ) {
11136 this.$indicator.css( property, scrollWidth );
11137 if ( this.labelPosition === 'after' ) {
11138 this.$label.css( property, scrollWidth );
11139 }
11140 }
11141
11142 this.scrollWidth = scrollWidth;
11143 this.positionLabel();
11144 }
11145 }
11146 return this;
11147 };
11148
11149 /**
11150 * @inheritdoc
11151 * @protected
11152 */
11153 OO.ui.MultilineTextInputWidget.prototype.getInputElement = function () {
11154 return $( '<textarea>' );
11155 };
11156
11157 /**
11158 * Check if the input automatically adjusts its size.
11159 *
11160 * @return {boolean}
11161 */
11162 OO.ui.MultilineTextInputWidget.prototype.isAutosizing = function () {
11163 return !!this.autosize;
11164 };
11165
11166 /**
11167 * @inheritdoc
11168 */
11169 OO.ui.MultilineTextInputWidget.prototype.restorePreInfuseState = function ( state ) {
11170 OO.ui.MultilineTextInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
11171 if ( state.scrollTop !== undefined ) {
11172 this.$input.scrollTop( state.scrollTop );
11173 }
11174 };
11175
11176 /**
11177 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
11178 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
11179 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
11180 *
11181 * - by typing a value in the text input field. If the value exactly matches the value of a menu
11182 * option, that option will appear to be selected.
11183 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
11184 * input field.
11185 *
11186 * After the user chooses an option, its `data` will be used as a new value for the widget.
11187 * A `label` also can be specified for each option: if given, it will be shown instead of the
11188 * `data` in the dropdown menu.
11189 *
11190 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
11191 *
11192 * For more information about menus and options, please see the [OOUI documentation on MediaWiki][1].
11193 *
11194 * @example
11195 * // Example: A ComboBoxInputWidget.
11196 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11197 * value: 'Option 1',
11198 * options: [
11199 * { data: 'Option 1' },
11200 * { data: 'Option 2' },
11201 * { data: 'Option 3' }
11202 * ]
11203 * } );
11204 * $( 'body' ).append( comboBox.$element );
11205 *
11206 * @example
11207 * // Example: A ComboBoxInputWidget with additional option labels.
11208 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11209 * value: 'Option 1',
11210 * options: [
11211 * {
11212 * data: 'Option 1',
11213 * label: 'Option One'
11214 * },
11215 * {
11216 * data: 'Option 2',
11217 * label: 'Option Two'
11218 * },
11219 * {
11220 * data: 'Option 3',
11221 * label: 'Option Three'
11222 * }
11223 * ]
11224 * } );
11225 * $( 'body' ).append( comboBox.$element );
11226 *
11227 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
11228 *
11229 * @class
11230 * @extends OO.ui.TextInputWidget
11231 *
11232 * @constructor
11233 * @param {Object} [config] Configuration options
11234 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
11235 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
11236 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
11237 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
11238 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
11239 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11240 */
11241 OO.ui.ComboBoxInputWidget = function OoUiComboBoxInputWidget( config ) {
11242 // Configuration initialization
11243 config = $.extend( {
11244 autocomplete: false
11245 }, config );
11246
11247 // ComboBoxInputWidget shouldn't support `multiline`
11248 config.multiline = false;
11249
11250 // See InputWidget#reusePreInfuseDOM about `config.$input`
11251 if ( config.$input ) {
11252 config.$input.removeAttr( 'list' );
11253 }
11254
11255 // Parent constructor
11256 OO.ui.ComboBoxInputWidget.parent.call( this, config );
11257
11258 // Properties
11259 this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
11260 this.dropdownButton = new OO.ui.ButtonWidget( {
11261 classes: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ],
11262 indicator: 'down',
11263 disabled: this.disabled
11264 } );
11265 this.menu = new OO.ui.MenuSelectWidget( $.extend(
11266 {
11267 widget: this,
11268 input: this,
11269 $floatableContainer: this.$element,
11270 disabled: this.isDisabled()
11271 },
11272 config.menu
11273 ) );
11274
11275 // Events
11276 this.connect( this, {
11277 change: 'onInputChange',
11278 enter: 'onInputEnter'
11279 } );
11280 this.dropdownButton.connect( this, {
11281 click: 'onDropdownButtonClick'
11282 } );
11283 this.menu.connect( this, {
11284 choose: 'onMenuChoose',
11285 add: 'onMenuItemsChange',
11286 remove: 'onMenuItemsChange',
11287 toggle: 'onMenuToggle'
11288 } );
11289
11290 // Initialization
11291 this.$input.attr( {
11292 role: 'combobox',
11293 'aria-owns': this.menu.getElementId(),
11294 'aria-autocomplete': 'list'
11295 } );
11296 // Do not override options set via config.menu.items
11297 if ( config.options !== undefined ) {
11298 this.setOptions( config.options );
11299 }
11300 this.$field = $( '<div>' )
11301 .addClass( 'oo-ui-comboBoxInputWidget-field' )
11302 .append( this.$input, this.dropdownButton.$element );
11303 this.$element
11304 .addClass( 'oo-ui-comboBoxInputWidget' )
11305 .append( this.$field );
11306 this.$overlay.append( this.menu.$element );
11307 this.onMenuItemsChange();
11308 };
11309
11310 /* Setup */
11311
11312 OO.inheritClass( OO.ui.ComboBoxInputWidget, OO.ui.TextInputWidget );
11313
11314 /* Methods */
11315
11316 /**
11317 * Get the combobox's menu.
11318 *
11319 * @return {OO.ui.MenuSelectWidget} Menu widget
11320 */
11321 OO.ui.ComboBoxInputWidget.prototype.getMenu = function () {
11322 return this.menu;
11323 };
11324
11325 /**
11326 * Get the combobox's text input widget.
11327 *
11328 * @return {OO.ui.TextInputWidget} Text input widget
11329 */
11330 OO.ui.ComboBoxInputWidget.prototype.getInput = function () {
11331 return this;
11332 };
11333
11334 /**
11335 * Handle input change events.
11336 *
11337 * @private
11338 * @param {string} value New value
11339 */
11340 OO.ui.ComboBoxInputWidget.prototype.onInputChange = function ( value ) {
11341 var match = this.menu.findItemFromData( value );
11342
11343 this.menu.selectItem( match );
11344 if ( this.menu.findHighlightedItem() ) {
11345 this.menu.highlightItem( match );
11346 }
11347
11348 if ( !this.isDisabled() ) {
11349 this.menu.toggle( true );
11350 }
11351 };
11352
11353 /**
11354 * Handle input enter events.
11355 *
11356 * @private
11357 */
11358 OO.ui.ComboBoxInputWidget.prototype.onInputEnter = function () {
11359 if ( !this.isDisabled() ) {
11360 this.menu.toggle( false );
11361 }
11362 };
11363
11364 /**
11365 * Handle button click events.
11366 *
11367 * @private
11368 */
11369 OO.ui.ComboBoxInputWidget.prototype.onDropdownButtonClick = function () {
11370 this.menu.toggle();
11371 this.focus();
11372 };
11373
11374 /**
11375 * Handle menu choose events.
11376 *
11377 * @private
11378 * @param {OO.ui.OptionWidget} item Chosen item
11379 */
11380 OO.ui.ComboBoxInputWidget.prototype.onMenuChoose = function ( item ) {
11381 this.setValue( item.getData() );
11382 };
11383
11384 /**
11385 * Handle menu item change events.
11386 *
11387 * @private
11388 */
11389 OO.ui.ComboBoxInputWidget.prototype.onMenuItemsChange = function () {
11390 var match = this.menu.findItemFromData( this.getValue() );
11391 this.menu.selectItem( match );
11392 if ( this.menu.findHighlightedItem() ) {
11393 this.menu.highlightItem( match );
11394 }
11395 this.$element.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu.isEmpty() );
11396 };
11397
11398 /**
11399 * Handle menu toggle events.
11400 *
11401 * @private
11402 * @param {boolean} isVisible Open state of the menu
11403 */
11404 OO.ui.ComboBoxInputWidget.prototype.onMenuToggle = function ( isVisible ) {
11405 this.$element.toggleClass( 'oo-ui-comboBoxInputWidget-open', isVisible );
11406 };
11407
11408 /**
11409 * @inheritdoc
11410 */
11411 OO.ui.ComboBoxInputWidget.prototype.setDisabled = function ( disabled ) {
11412 // Parent method
11413 OO.ui.ComboBoxInputWidget.parent.prototype.setDisabled.call( this, disabled );
11414
11415 if ( this.dropdownButton ) {
11416 this.dropdownButton.setDisabled( this.isDisabled() );
11417 }
11418 if ( this.menu ) {
11419 this.menu.setDisabled( this.isDisabled() );
11420 }
11421
11422 return this;
11423 };
11424
11425 /**
11426 * Set the options available for this input.
11427 *
11428 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
11429 * @chainable
11430 */
11431 OO.ui.ComboBoxInputWidget.prototype.setOptions = function ( options ) {
11432 this.getMenu()
11433 .clearItems()
11434 .addItems( options.map( function ( opt ) {
11435 return new OO.ui.MenuOptionWidget( {
11436 data: opt.data,
11437 label: opt.label !== undefined ? opt.label : opt.data
11438 } );
11439 } ) );
11440
11441 return this;
11442 };
11443
11444 /**
11445 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
11446 * which is a widget that is specified by reference before any optional configuration settings.
11447 *
11448 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
11449 *
11450 * - **left**: The label is placed before the field-widget and aligned with the left margin.
11451 * A left-alignment is used for forms with many fields.
11452 * - **right**: The label is placed before the field-widget and aligned to the right margin.
11453 * A right-alignment is used for long but familiar forms which users tab through,
11454 * verifying the current field with a quick glance at the label.
11455 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
11456 * that users fill out from top to bottom.
11457 * - **inline**: The label is placed after the field-widget and aligned to the left.
11458 * An inline-alignment is best used with checkboxes or radio buttons.
11459 *
11460 * Help text can either be:
11461 *
11462 * - accessed via a help icon that appears in the upper right corner of the rendered field layout, or
11463 * - shown as a subtle explanation below the label.
11464 *
11465 * If the help text is brief, or is essential to always expose it, set `helpInline` to `true`. If it
11466 * is long or not essential, leave `helpInline` to its default, `false`.
11467 *
11468 * Please see the [OOUI documentation on MediaWiki] [1] for examples and more information.
11469 *
11470 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
11471 *
11472 * @class
11473 * @extends OO.ui.Layout
11474 * @mixins OO.ui.mixin.LabelElement
11475 * @mixins OO.ui.mixin.TitledElement
11476 *
11477 * @constructor
11478 * @param {OO.ui.Widget} fieldWidget Field widget
11479 * @param {Object} [config] Configuration options
11480 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top'
11481 * or 'inline'
11482 * @cfg {Array} [errors] Error messages about the widget, which will be
11483 * displayed below the widget.
11484 * The array may contain strings or OO.ui.HtmlSnippet instances.
11485 * @cfg {Array} [notices] Notices about the widget, which will be displayed
11486 * below the widget.
11487 * The array may contain strings or OO.ui.HtmlSnippet instances.
11488 * These are more visible than `help` messages when `helpInline` is set, and so
11489 * might be good for transient messages.
11490 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified
11491 * and `helpInline` is `false`, a "help" icon will appear in the upper-right
11492 * corner of the rendered field; clicking it will display the text in a popup.
11493 * If `helpInline` is `true`, then a subtle description will be shown after the
11494 * label.
11495 * @cfg {boolean} [helpInline=false] Whether or not the help should be inline,
11496 * or shown when the "help" icon is clicked.
11497 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if
11498 * `help` is given.
11499 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11500 *
11501 * @throws {Error} An error is thrown if no widget is specified
11502 */
11503 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
11504 // Allow passing positional parameters inside the config object
11505 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
11506 config = fieldWidget;
11507 fieldWidget = config.fieldWidget;
11508 }
11509
11510 // Make sure we have required constructor arguments
11511 if ( fieldWidget === undefined ) {
11512 throw new Error( 'Widget not found' );
11513 }
11514
11515 // Configuration initialization
11516 config = $.extend( { align: 'left', helpInline: false }, config );
11517
11518 // Parent constructor
11519 OO.ui.FieldLayout.parent.call( this, config );
11520
11521 // Mixin constructors
11522 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, {
11523 $label: $( '<label>' )
11524 } ) );
11525 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
11526
11527 // Properties
11528 this.fieldWidget = fieldWidget;
11529 this.errors = [];
11530 this.notices = [];
11531 this.$field = this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
11532 this.$messages = $( '<ul>' );
11533 this.$header = $( '<span>' );
11534 this.$body = $( '<div>' );
11535 this.align = null;
11536 this.helpInline = config.helpInline;
11537
11538 // Events
11539 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
11540
11541 // Initialization
11542 this.$help = config.help ?
11543 this.createHelpElement( config.help, config.$overlay ) :
11544 $( [] );
11545 if ( this.fieldWidget.getInputId() ) {
11546 this.$label.attr( 'for', this.fieldWidget.getInputId() );
11547 if ( this.helpInline ) {
11548 this.$help.attr( 'for', this.fieldWidget.getInputId() );
11549 }
11550 } else {
11551 this.$label.on( 'click', function () {
11552 this.fieldWidget.simulateLabelClick();
11553 }.bind( this ) );
11554 if ( this.helpInline ) {
11555 this.$help.on( 'click', function () {
11556 this.fieldWidget.simulateLabelClick();
11557 }.bind( this ) );
11558 }
11559 }
11560 this.$element
11561 .addClass( 'oo-ui-fieldLayout' )
11562 .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget.isDisabled() )
11563 .append( this.$body );
11564 this.$body.addClass( 'oo-ui-fieldLayout-body' );
11565 this.$header.addClass( 'oo-ui-fieldLayout-header' );
11566 this.$messages.addClass( 'oo-ui-fieldLayout-messages' );
11567 this.$field
11568 .addClass( 'oo-ui-fieldLayout-field' )
11569 .append( this.fieldWidget.$element );
11570
11571 this.setErrors( config.errors || [] );
11572 this.setNotices( config.notices || [] );
11573 this.setAlignment( config.align );
11574 // Call this again to take into account the widget's accessKey
11575 this.updateTitle();
11576 };
11577
11578 /* Setup */
11579
11580 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
11581 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.LabelElement );
11582 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.TitledElement );
11583
11584 /* Methods */
11585
11586 /**
11587 * Handle field disable events.
11588 *
11589 * @private
11590 * @param {boolean} value Field is disabled
11591 */
11592 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
11593 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
11594 };
11595
11596 /**
11597 * Get the widget contained by the field.
11598 *
11599 * @return {OO.ui.Widget} Field widget
11600 */
11601 OO.ui.FieldLayout.prototype.getField = function () {
11602 return this.fieldWidget;
11603 };
11604
11605 /**
11606 * Return `true` if the given field widget can be used with `'inline'` alignment (see
11607 * #setAlignment). Return `false` if it can't or if this can't be determined.
11608 *
11609 * @return {boolean}
11610 */
11611 OO.ui.FieldLayout.prototype.isFieldInline = function () {
11612 // This is very simplistic, but should be good enough.
11613 return this.getField().$element.prop( 'tagName' ).toLowerCase() === 'span';
11614 };
11615
11616 /**
11617 * @protected
11618 * @param {string} kind 'error' or 'notice'
11619 * @param {string|OO.ui.HtmlSnippet} text
11620 * @return {jQuery}
11621 */
11622 OO.ui.FieldLayout.prototype.makeMessage = function ( kind, text ) {
11623 var $listItem, $icon, message;
11624 $listItem = $( '<li>' );
11625 if ( kind === 'error' ) {
11626 $icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'warning' ] } ).$element;
11627 $listItem.attr( 'role', 'alert' );
11628 } else if ( kind === 'notice' ) {
11629 $icon = new OO.ui.IconWidget( { icon: 'notice' } ).$element;
11630 } else {
11631 $icon = '';
11632 }
11633 message = new OO.ui.LabelWidget( { label: text } );
11634 $listItem
11635 .append( $icon, message.$element )
11636 .addClass( 'oo-ui-fieldLayout-messages-' + kind );
11637 return $listItem;
11638 };
11639
11640 /**
11641 * Set the field alignment mode.
11642 *
11643 * @private
11644 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
11645 * @chainable
11646 */
11647 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
11648 if ( value !== this.align ) {
11649 // Default to 'left'
11650 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
11651 value = 'left';
11652 }
11653 // Validate
11654 if ( value === 'inline' && !this.isFieldInline() ) {
11655 value = 'top';
11656 }
11657 // Reorder elements
11658
11659 if ( this.helpInline ) {
11660 if ( value === 'top' ) {
11661 this.$header.append( this.$label );
11662 this.$body.append( this.$header, this.$field, this.$help );
11663 } else if ( value === 'inline' ) {
11664 this.$header.append( this.$label, this.$help );
11665 this.$body.append( this.$field, this.$header );
11666 } else {
11667 this.$header.append( this.$label, this.$help );
11668 this.$body.append( this.$header, this.$field );
11669 }
11670 } else {
11671 if ( value === 'top' ) {
11672 this.$header.append( this.$help, this.$label );
11673 this.$body.append( this.$header, this.$field );
11674 } else if ( value === 'inline' ) {
11675 this.$header.append( this.$help, this.$label );
11676 this.$body.append( this.$field, this.$header );
11677 } else {
11678 this.$header.append( this.$label );
11679 this.$body.append( this.$header, this.$help, this.$field );
11680 }
11681 }
11682 // Set classes. The following classes can be used here:
11683 // * oo-ui-fieldLayout-align-left
11684 // * oo-ui-fieldLayout-align-right
11685 // * oo-ui-fieldLayout-align-top
11686 // * oo-ui-fieldLayout-align-inline
11687 if ( this.align ) {
11688 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
11689 }
11690 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
11691 this.align = value;
11692 }
11693
11694 return this;
11695 };
11696
11697 /**
11698 * Set the list of error messages.
11699 *
11700 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
11701 * The array may contain strings or OO.ui.HtmlSnippet instances.
11702 * @chainable
11703 */
11704 OO.ui.FieldLayout.prototype.setErrors = function ( errors ) {
11705 this.errors = errors.slice();
11706 this.updateMessages();
11707 return this;
11708 };
11709
11710 /**
11711 * Set the list of notice messages.
11712 *
11713 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
11714 * The array may contain strings or OO.ui.HtmlSnippet instances.
11715 * @chainable
11716 */
11717 OO.ui.FieldLayout.prototype.setNotices = function ( notices ) {
11718 this.notices = notices.slice();
11719 this.updateMessages();
11720 return this;
11721 };
11722
11723 /**
11724 * Update the rendering of error and notice messages.
11725 *
11726 * @private
11727 */
11728 OO.ui.FieldLayout.prototype.updateMessages = function () {
11729 var i;
11730 this.$messages.empty();
11731
11732 if ( this.errors.length || this.notices.length ) {
11733 this.$body.after( this.$messages );
11734 } else {
11735 this.$messages.remove();
11736 return;
11737 }
11738
11739 for ( i = 0; i < this.notices.length; i++ ) {
11740 this.$messages.append( this.makeMessage( 'notice', this.notices[ i ] ) );
11741 }
11742 for ( i = 0; i < this.errors.length; i++ ) {
11743 this.$messages.append( this.makeMessage( 'error', this.errors[ i ] ) );
11744 }
11745 };
11746
11747 /**
11748 * Include information about the widget's accessKey in our title. TitledElement calls this method.
11749 * (This is a bit of a hack.)
11750 *
11751 * @protected
11752 * @param {string} title Tooltip label for 'title' attribute
11753 * @return {string}
11754 */
11755 OO.ui.FieldLayout.prototype.formatTitleWithAccessKey = function ( title ) {
11756 if ( this.fieldWidget && this.fieldWidget.formatTitleWithAccessKey ) {
11757 return this.fieldWidget.formatTitleWithAccessKey( title );
11758 }
11759 return title;
11760 };
11761
11762 /**
11763 * Creates and returns the help element. Also sets the `aria-describedby`
11764 * attribute on the main element of the `fieldWidget`.
11765 *
11766 * @private
11767 * @param {string|OO.ui.HtmlSnippet} [help] Help text.
11768 * @param {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup.
11769 * @return {jQuery} The element that should become `this.$help`.
11770 */
11771 OO.ui.FieldLayout.prototype.createHelpElement = function ( help, $overlay ) {
11772 var helpId, helpWidget;
11773
11774 if ( this.helpInline ) {
11775 helpWidget = new OO.ui.LabelWidget( {
11776 label: help,
11777 classes: [ 'oo-ui-inline-help' ]
11778 } );
11779
11780 helpId = helpWidget.getElementId();
11781 } else {
11782 helpWidget = new OO.ui.PopupButtonWidget( {
11783 $overlay: $overlay,
11784 popup: {
11785 padded: true
11786 },
11787 classes: [ 'oo-ui-fieldLayout-help' ],
11788 framed: false,
11789 icon: 'info',
11790 label: OO.ui.msg( 'ooui-field-help' ),
11791 invisibleLabel: true
11792 } );
11793 if ( help instanceof OO.ui.HtmlSnippet ) {
11794 helpWidget.getPopup().$body.html( help.toString() );
11795 } else {
11796 helpWidget.getPopup().$body.text( help );
11797 }
11798
11799 helpId = helpWidget.getPopup().getBodyId();
11800 }
11801
11802 // Set the 'aria-describedby' attribute on the fieldWidget
11803 // Preference given to an input or a button
11804 (
11805 this.fieldWidget.$input ||
11806 this.fieldWidget.$button ||
11807 this.fieldWidget.$element
11808 ).attr( 'aria-describedby', helpId );
11809
11810 return helpWidget.$element;
11811 };
11812
11813 /**
11814 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
11815 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
11816 * is required and is specified before any optional configuration settings.
11817 *
11818 * Labels can be aligned in one of four ways:
11819 *
11820 * - **left**: The label is placed before the field-widget and aligned with the left margin.
11821 * A left-alignment is used for forms with many fields.
11822 * - **right**: The label is placed before the field-widget and aligned to the right margin.
11823 * A right-alignment is used for long but familiar forms which users tab through,
11824 * verifying the current field with a quick glance at the label.
11825 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
11826 * that users fill out from top to bottom.
11827 * - **inline**: The label is placed after the field-widget and aligned to the left.
11828 * An inline-alignment is best used with checkboxes or radio buttons.
11829 *
11830 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
11831 * text is specified.
11832 *
11833 * @example
11834 * // Example of an ActionFieldLayout
11835 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
11836 * new OO.ui.TextInputWidget( {
11837 * placeholder: 'Field widget'
11838 * } ),
11839 * new OO.ui.ButtonWidget( {
11840 * label: 'Button'
11841 * } ),
11842 * {
11843 * label: 'An ActionFieldLayout. This label is aligned top',
11844 * align: 'top',
11845 * help: 'This is help text'
11846 * }
11847 * );
11848 *
11849 * $( 'body' ).append( actionFieldLayout.$element );
11850 *
11851 * @class
11852 * @extends OO.ui.FieldLayout
11853 *
11854 * @constructor
11855 * @param {OO.ui.Widget} fieldWidget Field widget
11856 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
11857 * @param {Object} config
11858 */
11859 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
11860 // Allow passing positional parameters inside the config object
11861 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
11862 config = fieldWidget;
11863 fieldWidget = config.fieldWidget;
11864 buttonWidget = config.buttonWidget;
11865 }
11866
11867 // Parent constructor
11868 OO.ui.ActionFieldLayout.parent.call( this, fieldWidget, config );
11869
11870 // Properties
11871 this.buttonWidget = buttonWidget;
11872 this.$button = $( '<span>' );
11873 this.$input = this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
11874
11875 // Initialization
11876 this.$element
11877 .addClass( 'oo-ui-actionFieldLayout' );
11878 this.$button
11879 .addClass( 'oo-ui-actionFieldLayout-button' )
11880 .append( this.buttonWidget.$element );
11881 this.$input
11882 .addClass( 'oo-ui-actionFieldLayout-input' )
11883 .append( this.fieldWidget.$element );
11884 this.$field
11885 .append( this.$input, this.$button );
11886 };
11887
11888 /* Setup */
11889
11890 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
11891
11892 /**
11893 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
11894 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
11895 * configured with a label as well. For more information and examples,
11896 * please see the [OOUI documentation on MediaWiki][1].
11897 *
11898 * @example
11899 * // Example of a fieldset layout
11900 * var input1 = new OO.ui.TextInputWidget( {
11901 * placeholder: 'A text input field'
11902 * } );
11903 *
11904 * var input2 = new OO.ui.TextInputWidget( {
11905 * placeholder: 'A text input field'
11906 * } );
11907 *
11908 * var fieldset = new OO.ui.FieldsetLayout( {
11909 * label: 'Example of a fieldset layout'
11910 * } );
11911 *
11912 * fieldset.addItems( [
11913 * new OO.ui.FieldLayout( input1, {
11914 * label: 'Field One'
11915 * } ),
11916 * new OO.ui.FieldLayout( input2, {
11917 * label: 'Field Two'
11918 * } )
11919 * ] );
11920 * $( 'body' ).append( fieldset.$element );
11921 *
11922 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
11923 *
11924 * @class
11925 * @extends OO.ui.Layout
11926 * @mixins OO.ui.mixin.IconElement
11927 * @mixins OO.ui.mixin.LabelElement
11928 * @mixins OO.ui.mixin.GroupElement
11929 *
11930 * @constructor
11931 * @param {Object} [config] Configuration options
11932 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
11933 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
11934 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
11935 * For important messages, you are advised to use `notices`, as they are always shown.
11936 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
11937 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11938 */
11939 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
11940 // Configuration initialization
11941 config = config || {};
11942
11943 // Parent constructor
11944 OO.ui.FieldsetLayout.parent.call( this, config );
11945
11946 // Mixin constructors
11947 OO.ui.mixin.IconElement.call( this, config );
11948 OO.ui.mixin.LabelElement.call( this, config );
11949 OO.ui.mixin.GroupElement.call( this, config );
11950
11951 // Properties
11952 this.$header = $( '<legend>' );
11953 if ( config.help ) {
11954 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
11955 $overlay: config.$overlay,
11956 popup: {
11957 padded: true
11958 },
11959 classes: [ 'oo-ui-fieldsetLayout-help' ],
11960 framed: false,
11961 icon: 'info',
11962 label: OO.ui.msg( 'ooui-field-help' ),
11963 invisibleLabel: true
11964 } );
11965 if ( config.help instanceof OO.ui.HtmlSnippet ) {
11966 this.popupButtonWidget.getPopup().$body.html( config.help.toString() );
11967 } else {
11968 this.popupButtonWidget.getPopup().$body.text( config.help );
11969 }
11970 this.$help = this.popupButtonWidget.$element;
11971 } else {
11972 this.$help = $( [] );
11973 }
11974
11975 // Initialization
11976 this.$header
11977 .addClass( 'oo-ui-fieldsetLayout-header' )
11978 .append( this.$icon, this.$label, this.$help );
11979 this.$group.addClass( 'oo-ui-fieldsetLayout-group' );
11980 this.$element
11981 .addClass( 'oo-ui-fieldsetLayout' )
11982 .prepend( this.$header, this.$group );
11983 if ( Array.isArray( config.items ) ) {
11984 this.addItems( config.items );
11985 }
11986 };
11987
11988 /* Setup */
11989
11990 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
11991 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.IconElement );
11992 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.LabelElement );
11993 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.GroupElement );
11994
11995 /* Static Properties */
11996
11997 /**
11998 * @static
11999 * @inheritdoc
12000 */
12001 OO.ui.FieldsetLayout.static.tagName = 'fieldset';
12002
12003 /**
12004 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
12005 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
12006 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
12007 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
12008 *
12009 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
12010 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
12011 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
12012 * some fancier controls. Some controls have both regular and InputWidget variants, for example
12013 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
12014 * often have simplified APIs to match the capabilities of HTML forms.
12015 * See the [OOUI documentation on MediaWiki] [2] for more information about InputWidgets.
12016 *
12017 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Forms
12018 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
12019 *
12020 * @example
12021 * // Example of a form layout that wraps a fieldset layout
12022 * var input1 = new OO.ui.TextInputWidget( {
12023 * placeholder: 'Username'
12024 * } );
12025 * var input2 = new OO.ui.TextInputWidget( {
12026 * placeholder: 'Password',
12027 * type: 'password'
12028 * } );
12029 * var submit = new OO.ui.ButtonInputWidget( {
12030 * label: 'Submit'
12031 * } );
12032 *
12033 * var fieldset = new OO.ui.FieldsetLayout( {
12034 * label: 'A form layout'
12035 * } );
12036 * fieldset.addItems( [
12037 * new OO.ui.FieldLayout( input1, {
12038 * label: 'Username',
12039 * align: 'top'
12040 * } ),
12041 * new OO.ui.FieldLayout( input2, {
12042 * label: 'Password',
12043 * align: 'top'
12044 * } ),
12045 * new OO.ui.FieldLayout( submit )
12046 * ] );
12047 * var form = new OO.ui.FormLayout( {
12048 * items: [ fieldset ],
12049 * action: '/api/formhandler',
12050 * method: 'get'
12051 * } )
12052 * $( 'body' ).append( form.$element );
12053 *
12054 * @class
12055 * @extends OO.ui.Layout
12056 * @mixins OO.ui.mixin.GroupElement
12057 *
12058 * @constructor
12059 * @param {Object} [config] Configuration options
12060 * @cfg {string} [method] HTML form `method` attribute
12061 * @cfg {string} [action] HTML form `action` attribute
12062 * @cfg {string} [enctype] HTML form `enctype` attribute
12063 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
12064 */
12065 OO.ui.FormLayout = function OoUiFormLayout( config ) {
12066 var action;
12067
12068 // Configuration initialization
12069 config = config || {};
12070
12071 // Parent constructor
12072 OO.ui.FormLayout.parent.call( this, config );
12073
12074 // Mixin constructors
12075 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
12076
12077 // Events
12078 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
12079
12080 // Make sure the action is safe
12081 action = config.action;
12082 if ( action !== undefined && !OO.ui.isSafeUrl( action ) ) {
12083 action = './' + action;
12084 }
12085
12086 // Initialization
12087 this.$element
12088 .addClass( 'oo-ui-formLayout' )
12089 .attr( {
12090 method: config.method,
12091 action: action,
12092 enctype: config.enctype
12093 } );
12094 if ( Array.isArray( config.items ) ) {
12095 this.addItems( config.items );
12096 }
12097 };
12098
12099 /* Setup */
12100
12101 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
12102 OO.mixinClass( OO.ui.FormLayout, OO.ui.mixin.GroupElement );
12103
12104 /* Events */
12105
12106 /**
12107 * A 'submit' event is emitted when the form is submitted.
12108 *
12109 * @event submit
12110 */
12111
12112 /* Static Properties */
12113
12114 /**
12115 * @static
12116 * @inheritdoc
12117 */
12118 OO.ui.FormLayout.static.tagName = 'form';
12119
12120 /* Methods */
12121
12122 /**
12123 * Handle form submit events.
12124 *
12125 * @private
12126 * @param {jQuery.Event} e Submit event
12127 * @fires submit
12128 */
12129 OO.ui.FormLayout.prototype.onFormSubmit = function () {
12130 if ( this.emit( 'submit' ) ) {
12131 return false;
12132 }
12133 };
12134
12135 /**
12136 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
12137 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
12138 *
12139 * @example
12140 * // Example of a panel layout
12141 * var panel = new OO.ui.PanelLayout( {
12142 * expanded: false,
12143 * framed: true,
12144 * padded: true,
12145 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
12146 * } );
12147 * $( 'body' ).append( panel.$element );
12148 *
12149 * @class
12150 * @extends OO.ui.Layout
12151 *
12152 * @constructor
12153 * @param {Object} [config] Configuration options
12154 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
12155 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
12156 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
12157 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
12158 */
12159 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
12160 // Configuration initialization
12161 config = $.extend( {
12162 scrollable: false,
12163 padded: false,
12164 expanded: true,
12165 framed: false
12166 }, config );
12167
12168 // Parent constructor
12169 OO.ui.PanelLayout.parent.call( this, config );
12170
12171 // Initialization
12172 this.$element.addClass( 'oo-ui-panelLayout' );
12173 if ( config.scrollable ) {
12174 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
12175 }
12176 if ( config.padded ) {
12177 this.$element.addClass( 'oo-ui-panelLayout-padded' );
12178 }
12179 if ( config.expanded ) {
12180 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
12181 }
12182 if ( config.framed ) {
12183 this.$element.addClass( 'oo-ui-panelLayout-framed' );
12184 }
12185 };
12186
12187 /* Setup */
12188
12189 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
12190
12191 /* Methods */
12192
12193 /**
12194 * Focus the panel layout
12195 *
12196 * The default implementation just focuses the first focusable element in the panel
12197 */
12198 OO.ui.PanelLayout.prototype.focus = function () {
12199 OO.ui.findFocusable( this.$element ).focus();
12200 };
12201
12202 /**
12203 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
12204 * items), with small margins between them. Convenient when you need to put a number of block-level
12205 * widgets on a single line next to each other.
12206 *
12207 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
12208 *
12209 * @example
12210 * // HorizontalLayout with a text input and a label
12211 * var layout = new OO.ui.HorizontalLayout( {
12212 * items: [
12213 * new OO.ui.LabelWidget( { label: 'Label' } ),
12214 * new OO.ui.TextInputWidget( { value: 'Text' } )
12215 * ]
12216 * } );
12217 * $( 'body' ).append( layout.$element );
12218 *
12219 * @class
12220 * @extends OO.ui.Layout
12221 * @mixins OO.ui.mixin.GroupElement
12222 *
12223 * @constructor
12224 * @param {Object} [config] Configuration options
12225 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
12226 */
12227 OO.ui.HorizontalLayout = function OoUiHorizontalLayout( config ) {
12228 // Configuration initialization
12229 config = config || {};
12230
12231 // Parent constructor
12232 OO.ui.HorizontalLayout.parent.call( this, config );
12233
12234 // Mixin constructors
12235 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
12236
12237 // Initialization
12238 this.$element.addClass( 'oo-ui-horizontalLayout' );
12239 if ( Array.isArray( config.items ) ) {
12240 this.addItems( config.items );
12241 }
12242 };
12243
12244 /* Setup */
12245
12246 OO.inheritClass( OO.ui.HorizontalLayout, OO.ui.Layout );
12247 OO.mixinClass( OO.ui.HorizontalLayout, OO.ui.mixin.GroupElement );
12248
12249 /**
12250 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
12251 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
12252 * (to adjust the value in increments) to allow the user to enter a number.
12253 *
12254 * @example
12255 * // Example: A NumberInputWidget.
12256 * var numberInput = new OO.ui.NumberInputWidget( {
12257 * label: 'NumberInputWidget',
12258 * input: { value: 5 },
12259 * min: 1,
12260 * max: 10
12261 * } );
12262 * $( 'body' ).append( numberInput.$element );
12263 *
12264 * @class
12265 * @extends OO.ui.TextInputWidget
12266 *
12267 * @constructor
12268 * @param {Object} [config] Configuration options
12269 * @cfg {Object} [minusButton] Configuration options to pass to the
12270 * {@link OO.ui.ButtonWidget decrementing button widget}.
12271 * @cfg {Object} [plusButton] Configuration options to pass to the
12272 * {@link OO.ui.ButtonWidget incrementing button widget}.
12273 * @cfg {number} [min=-Infinity] Minimum allowed value
12274 * @cfg {number} [max=Infinity] Maximum allowed value
12275 * @cfg {number|null} [step] If specified, the field only accepts values that are multiples of this.
12276 * @cfg {number} [buttonStep=step||1] Delta when using the buttons or up/down arrow keys.
12277 * Defaults to `step` if specified, otherwise `1`.
12278 * @cfg {number} [pageStep=10*buttonStep] Delta when using the page-up/page-down keys.
12279 * Defaults to 10 times `buttonStep`.
12280 * @cfg {boolean} [showButtons=true] Whether to show the plus and minus buttons.
12281 */
12282 OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
12283 var $field = $( '<div>' )
12284 .addClass( 'oo-ui-numberInputWidget-field' );
12285
12286 // Configuration initialization
12287 config = $.extend( {
12288 min: -Infinity,
12289 max: Infinity,
12290 showButtons: true
12291 }, config );
12292
12293 // For backward compatibility
12294 $.extend( config, config.input );
12295 this.input = this;
12296
12297 // Parent constructor
12298 OO.ui.NumberInputWidget.parent.call( this, $.extend( config, {
12299 type: 'number'
12300 } ) );
12301
12302 if ( config.showButtons ) {
12303 this.minusButton = new OO.ui.ButtonWidget( $.extend(
12304 {
12305 disabled: this.isDisabled(),
12306 tabIndex: -1,
12307 classes: [ 'oo-ui-numberInputWidget-minusButton' ],
12308 icon: 'subtract'
12309 },
12310 config.minusButton
12311 ) );
12312 this.minusButton.$element.attr( 'aria-hidden', 'true' );
12313 this.plusButton = new OO.ui.ButtonWidget( $.extend(
12314 {
12315 disabled: this.isDisabled(),
12316 tabIndex: -1,
12317 classes: [ 'oo-ui-numberInputWidget-plusButton' ],
12318 icon: 'add'
12319 },
12320 config.plusButton
12321 ) );
12322 this.plusButton.$element.attr( 'aria-hidden', 'true' );
12323 }
12324
12325 // Events
12326 this.$input.on( {
12327 keydown: this.onKeyDown.bind( this ),
12328 'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
12329 } );
12330 if ( config.showButtons ) {
12331 this.plusButton.connect( this, {
12332 click: [ 'onButtonClick', +1 ]
12333 } );
12334 this.minusButton.connect( this, {
12335 click: [ 'onButtonClick', -1 ]
12336 } );
12337 }
12338
12339 // Build the field
12340 $field.append( this.$input );
12341 if ( config.showButtons ) {
12342 $field
12343 .prepend( this.minusButton.$element )
12344 .append( this.plusButton.$element );
12345 }
12346
12347 // Initialization
12348 if ( config.allowInteger || config.isInteger ) {
12349 // Backward compatibility
12350 config.step = 1;
12351 }
12352 this.setRange( config.min, config.max );
12353 this.setStep( config.buttonStep, config.pageStep, config.step );
12354 // Set the validation method after we set step and range
12355 // so that it doesn't immediately call setValidityFlag
12356 this.setValidation( this.validateNumber.bind( this ) );
12357
12358 this.$element
12359 .addClass( 'oo-ui-numberInputWidget' )
12360 .toggleClass( 'oo-ui-numberInputWidget-buttoned', config.showButtons )
12361 .append( $field );
12362 };
12363
12364 /* Setup */
12365
12366 OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.TextInputWidget );
12367
12368 /* Methods */
12369
12370 // Backward compatibility
12371 OO.ui.NumberInputWidget.prototype.setAllowInteger = function ( flag ) {
12372 this.setStep( flag ? 1 : null );
12373 };
12374 // Backward compatibility
12375 OO.ui.NumberInputWidget.prototype.setIsInteger = OO.ui.NumberInputWidget.prototype.setAllowInteger;
12376
12377 // Backward compatibility
12378 OO.ui.NumberInputWidget.prototype.getAllowInteger = function () {
12379 return this.step === 1;
12380 };
12381 // Backward compatibility
12382 OO.ui.NumberInputWidget.prototype.getIsInteger = OO.ui.NumberInputWidget.prototype.getAllowInteger;
12383
12384 /**
12385 * Set the range of allowed values
12386 *
12387 * @param {number} min Minimum allowed value
12388 * @param {number} max Maximum allowed value
12389 */
12390 OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
12391 if ( min > max ) {
12392 throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
12393 }
12394 this.min = min;
12395 this.max = max;
12396 this.$input.attr( 'min', this.min );
12397 this.$input.attr( 'max', this.max );
12398 this.setValidityFlag();
12399 };
12400
12401 /**
12402 * Get the current range
12403 *
12404 * @return {number[]} Minimum and maximum values
12405 */
12406 OO.ui.NumberInputWidget.prototype.getRange = function () {
12407 return [ this.min, this.max ];
12408 };
12409
12410 /**
12411 * Set the stepping deltas
12412 *
12413 * @param {number} [buttonStep=step||1] Delta when using the buttons or up/down arrow keys.
12414 * Defaults to `step` if specified, otherwise `1`.
12415 * @param {number} [pageStep=10*buttonStep] Delta when using the page-up/page-down keys.
12416 * Defaults to 10 times `buttonStep`.
12417 * @param {number|null} [step] If specified, the field only accepts values that are multiples of this.
12418 */
12419 OO.ui.NumberInputWidget.prototype.setStep = function ( buttonStep, pageStep, step ) {
12420 if ( buttonStep === undefined ) {
12421 buttonStep = step || 1;
12422 }
12423 if ( pageStep === undefined ) {
12424 pageStep = 10 * buttonStep;
12425 }
12426 if ( step !== null && step <= 0 ) {
12427 throw new Error( 'Step value, if given, must be positive' );
12428 }
12429 if ( buttonStep <= 0 ) {
12430 throw new Error( 'Button step value must be positive' );
12431 }
12432 if ( pageStep <= 0 ) {
12433 throw new Error( 'Page step value must be positive' );
12434 }
12435 this.step = step;
12436 this.buttonStep = buttonStep;
12437 this.pageStep = pageStep;
12438 this.$input.attr( 'step', this.step || 'any' );
12439 this.setValidityFlag();
12440 };
12441
12442 /**
12443 * @inheritdoc
12444 */
12445 OO.ui.NumberInputWidget.prototype.setValue = function ( value ) {
12446 if ( value === '' ) {
12447 // Some browsers allow a value in the input even if there isn't one reported by $input.val()
12448 // so here we make sure an 'empty' value is actually displayed as such.
12449 this.$input.val( '' );
12450 }
12451 return OO.ui.NumberInputWidget.parent.prototype.setValue.call( this, value );
12452 };
12453
12454 /**
12455 * Get the current stepping values
12456 *
12457 * @return {number[]} Button step, page step, and validity step
12458 */
12459 OO.ui.NumberInputWidget.prototype.getStep = function () {
12460 return [ this.buttonStep, this.pageStep, this.step ];
12461 };
12462
12463 /**
12464 * Get the current value of the widget as a number
12465 *
12466 * @return {number} May be NaN, or an invalid number
12467 */
12468 OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
12469 return +this.getValue();
12470 };
12471
12472 /**
12473 * Adjust the value of the widget
12474 *
12475 * @param {number} delta Adjustment amount
12476 */
12477 OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
12478 var n, v = this.getNumericValue();
12479
12480 delta = +delta;
12481 if ( isNaN( delta ) || !isFinite( delta ) ) {
12482 throw new Error( 'Delta must be a finite number' );
12483 }
12484
12485 if ( isNaN( v ) ) {
12486 n = 0;
12487 } else {
12488 n = v + delta;
12489 n = Math.max( Math.min( n, this.max ), this.min );
12490 if ( this.step ) {
12491 n = Math.round( n / this.step ) * this.step;
12492 }
12493 }
12494
12495 if ( n !== v ) {
12496 this.setValue( n );
12497 }
12498 };
12499 /**
12500 * Validate input
12501 *
12502 * @private
12503 * @param {string} value Field value
12504 * @return {boolean}
12505 */
12506 OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
12507 var n = +value;
12508 if ( value === '' ) {
12509 return !this.isRequired();
12510 }
12511
12512 if ( isNaN( n ) || !isFinite( n ) ) {
12513 return false;
12514 }
12515
12516 if ( this.step && Math.floor( n / this.step ) !== n / this.step ) {
12517 return false;
12518 }
12519
12520 if ( n < this.min || n > this.max ) {
12521 return false;
12522 }
12523
12524 return true;
12525 };
12526
12527 /**
12528 * Handle mouse click events.
12529 *
12530 * @private
12531 * @param {number} dir +1 or -1
12532 */
12533 OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
12534 this.adjustValue( dir * this.buttonStep );
12535 };
12536
12537 /**
12538 * Handle mouse wheel events.
12539 *
12540 * @private
12541 * @param {jQuery.Event} event
12542 */
12543 OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
12544 var delta = 0;
12545
12546 if ( !this.isDisabled() && this.$input.is( ':focus' ) ) {
12547 // Standard 'wheel' event
12548 if ( event.originalEvent.deltaMode !== undefined ) {
12549 this.sawWheelEvent = true;
12550 }
12551 if ( event.originalEvent.deltaY ) {
12552 delta = -event.originalEvent.deltaY;
12553 } else if ( event.originalEvent.deltaX ) {
12554 delta = event.originalEvent.deltaX;
12555 }
12556
12557 // Non-standard events
12558 if ( !this.sawWheelEvent ) {
12559 if ( event.originalEvent.wheelDeltaX ) {
12560 delta = -event.originalEvent.wheelDeltaX;
12561 } else if ( event.originalEvent.wheelDeltaY ) {
12562 delta = event.originalEvent.wheelDeltaY;
12563 } else if ( event.originalEvent.wheelDelta ) {
12564 delta = event.originalEvent.wheelDelta;
12565 } else if ( event.originalEvent.detail ) {
12566 delta = -event.originalEvent.detail;
12567 }
12568 }
12569
12570 if ( delta ) {
12571 delta = delta < 0 ? -1 : 1;
12572 this.adjustValue( delta * this.buttonStep );
12573 }
12574
12575 return false;
12576 }
12577 };
12578
12579 /**
12580 * Handle key down events.
12581 *
12582 * @private
12583 * @param {jQuery.Event} e Key down event
12584 */
12585 OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
12586 if ( !this.isDisabled() ) {
12587 switch ( e.which ) {
12588 case OO.ui.Keys.UP:
12589 this.adjustValue( this.buttonStep );
12590 return false;
12591 case OO.ui.Keys.DOWN:
12592 this.adjustValue( -this.buttonStep );
12593 return false;
12594 case OO.ui.Keys.PAGEUP:
12595 this.adjustValue( this.pageStep );
12596 return false;
12597 case OO.ui.Keys.PAGEDOWN:
12598 this.adjustValue( -this.pageStep );
12599 return false;
12600 }
12601 }
12602 };
12603
12604 /**
12605 * @inheritdoc
12606 */
12607 OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
12608 // Parent method
12609 OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
12610
12611 if ( this.minusButton ) {
12612 this.minusButton.setDisabled( this.isDisabled() );
12613 }
12614 if ( this.plusButton ) {
12615 this.plusButton.setDisabled( this.isDisabled() );
12616 }
12617
12618 return this;
12619 };
12620
12621 }( OO ) );
12622
12623 //# sourceMappingURL=oojs-ui-core.js.map.json