OOUI: Backport I407b0d6fe7b81465054b640d4b5ac4bf352a9901
[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 closestScrollableOfContainer = OO.ui.Element.static.getClosestScrollableContainer( this.$floatableContainer[ 0 ] );
4454 // If the scrollable is the root, we have to listen to scroll events
4455 // on the window because of browser inconsistencies.
4456 if ( $( closestScrollableOfContainer ).is( 'html, body' ) ) {
4457 closestScrollableOfContainer = OO.ui.Element.static.getWindow( closestScrollableOfContainer );
4458 }
4459
4460 if ( positioning ) {
4461 this.$floatableWindow = $( this.getElementWindow() );
4462 this.$floatableWindow.on( 'resize', this.onFloatableWindowResizeHandler );
4463
4464 this.$floatableClosestScrollable = $( closestScrollableOfContainer );
4465 this.$floatableClosestScrollable.on( 'scroll', this.onFloatableScrollHandler );
4466
4467 // Initial position after visible
4468 this.position();
4469 } else {
4470 if ( this.$floatableWindow ) {
4471 this.$floatableWindow.off( 'resize', this.onFloatableWindowResizeHandler );
4472 this.$floatableWindow = null;
4473 }
4474
4475 if ( this.$floatableClosestScrollable ) {
4476 this.$floatableClosestScrollable.off( 'scroll', this.onFloatableScrollHandler );
4477 this.$floatableClosestScrollable = null;
4478 }
4479
4480 this.$floatable.css( { left: '', right: '', top: '' } );
4481 }
4482 }
4483
4484 return this;
4485 };
4486
4487 /**
4488 * Check whether the bottom edge of the given element is within the viewport of the given container.
4489 *
4490 * @private
4491 * @param {jQuery} $element
4492 * @param {jQuery} $container
4493 * @return {boolean}
4494 */
4495 OO.ui.mixin.FloatableElement.prototype.isElementInViewport = function ( $element, $container ) {
4496 var elemRect, contRect, topEdgeInBounds, bottomEdgeInBounds, leftEdgeInBounds, rightEdgeInBounds,
4497 startEdgeInBounds, endEdgeInBounds, viewportSpacing,
4498 direction = $element.css( 'direction' );
4499
4500 elemRect = $element[ 0 ].getBoundingClientRect();
4501 if ( $container[ 0 ] === window ) {
4502 viewportSpacing = OO.ui.getViewportSpacing();
4503 contRect = {
4504 top: 0,
4505 left: 0,
4506 right: document.documentElement.clientWidth,
4507 bottom: document.documentElement.clientHeight
4508 };
4509 contRect.top += viewportSpacing.top;
4510 contRect.left += viewportSpacing.left;
4511 contRect.right -= viewportSpacing.right;
4512 contRect.bottom -= viewportSpacing.bottom;
4513 } else {
4514 contRect = $container[ 0 ].getBoundingClientRect();
4515 }
4516
4517 topEdgeInBounds = elemRect.top >= contRect.top && elemRect.top <= contRect.bottom;
4518 bottomEdgeInBounds = elemRect.bottom >= contRect.top && elemRect.bottom <= contRect.bottom;
4519 leftEdgeInBounds = elemRect.left >= contRect.left && elemRect.left <= contRect.right;
4520 rightEdgeInBounds = elemRect.right >= contRect.left && elemRect.right <= contRect.right;
4521 if ( direction === 'rtl' ) {
4522 startEdgeInBounds = rightEdgeInBounds;
4523 endEdgeInBounds = leftEdgeInBounds;
4524 } else {
4525 startEdgeInBounds = leftEdgeInBounds;
4526 endEdgeInBounds = rightEdgeInBounds;
4527 }
4528
4529 if ( this.verticalPosition === 'below' && !bottomEdgeInBounds ) {
4530 return false;
4531 }
4532 if ( this.verticalPosition === 'above' && !topEdgeInBounds ) {
4533 return false;
4534 }
4535 if ( this.horizontalPosition === 'before' && !startEdgeInBounds ) {
4536 return false;
4537 }
4538 if ( this.horizontalPosition === 'after' && !endEdgeInBounds ) {
4539 return false;
4540 }
4541
4542 // The other positioning values are all about being inside the container,
4543 // so in those cases all we care about is that any part of the container is visible.
4544 return elemRect.top <= contRect.bottom && elemRect.bottom >= contRect.top &&
4545 elemRect.left <= contRect.right && elemRect.right >= contRect.left;
4546 };
4547
4548 /**
4549 * Check if the floatable is hidden to the user because it was offscreen.
4550 *
4551 * @return {boolean} Floatable is out of view
4552 */
4553 OO.ui.mixin.FloatableElement.prototype.isFloatableOutOfView = function () {
4554 return this.floatableOutOfView;
4555 };
4556
4557 /**
4558 * Position the floatable below its container.
4559 *
4560 * This should only be done when both of them are attached to the DOM and visible.
4561 *
4562 * @chainable
4563 */
4564 OO.ui.mixin.FloatableElement.prototype.position = function () {
4565 if ( !this.positioning ) {
4566 return this;
4567 }
4568
4569 if ( !(
4570 // To continue, some things need to be true:
4571 // The element must actually be in the DOM
4572 this.isElementAttached() && (
4573 // The closest scrollable is the current window
4574 this.$floatableClosestScrollable[ 0 ] === this.getElementWindow() ||
4575 // OR is an element in the element's DOM
4576 $.contains( this.getElementDocument(), this.$floatableClosestScrollable[ 0 ] )
4577 )
4578 ) ) {
4579 // Abort early if important parts of the widget are no longer attached to the DOM
4580 return this;
4581 }
4582
4583 this.floatableOutOfView = this.hideWhenOutOfView && !this.isElementInViewport( this.$floatableContainer, this.$floatableClosestScrollable );
4584 if ( this.floatableOutOfView ) {
4585 this.$floatable.addClass( 'oo-ui-element-hidden' );
4586 return this;
4587 } else {
4588 this.$floatable.removeClass( 'oo-ui-element-hidden' );
4589 }
4590
4591 this.$floatable.css( this.computePosition() );
4592
4593 // We updated the position, so re-evaluate the clipping state.
4594 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
4595 // will not notice the need to update itself.)
4596 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
4597 // it not listen to the right events in the right places?
4598 if ( this.clip ) {
4599 this.clip();
4600 }
4601
4602 return this;
4603 };
4604
4605 /**
4606 * Compute how #$floatable should be positioned based on the position of #$floatableContainer
4607 * and the positioning settings. This is a helper for #position that shouldn't be called directly,
4608 * but may be overridden by subclasses if they want to change or add to the positioning logic.
4609 *
4610 * @return {Object} New position to apply with .css(). Keys are 'top', 'left', 'bottom' and 'right'.
4611 */
4612 OO.ui.mixin.FloatableElement.prototype.computePosition = function () {
4613 var isBody, scrollableX, scrollableY, containerPos,
4614 horizScrollbarHeight, vertScrollbarWidth, scrollTop, scrollLeft,
4615 newPos = { top: '', left: '', bottom: '', right: '' },
4616 direction = this.$floatableContainer.css( 'direction' ),
4617 $offsetParent = this.$floatable.offsetParent();
4618
4619 if ( $offsetParent.is( 'html' ) ) {
4620 // The innerHeight/Width and clientHeight/Width calculations don't work well on the
4621 // <html> element, but they do work on the <body>
4622 $offsetParent = $( $offsetParent[ 0 ].ownerDocument.body );
4623 }
4624 isBody = $offsetParent.is( 'body' );
4625 scrollableX = $offsetParent.css( 'overflow-x' ) === 'scroll' || $offsetParent.css( 'overflow-x' ) === 'auto';
4626 scrollableY = $offsetParent.css( 'overflow-y' ) === 'scroll' || $offsetParent.css( 'overflow-y' ) === 'auto';
4627
4628 vertScrollbarWidth = $offsetParent.innerWidth() - $offsetParent.prop( 'clientWidth' );
4629 horizScrollbarHeight = $offsetParent.innerHeight() - $offsetParent.prop( 'clientHeight' );
4630 // We don't need to compute and add scrollTop and scrollLeft if the scrollable container is the body,
4631 // or if it isn't scrollable
4632 scrollTop = scrollableY && !isBody ? $offsetParent.scrollTop() : 0;
4633 scrollLeft = scrollableX && !isBody ? OO.ui.Element.static.getScrollLeft( $offsetParent[ 0 ] ) : 0;
4634
4635 // Avoid passing the <body> to getRelativePosition(), because it won't return what we expect
4636 // if the <body> has a margin
4637 containerPos = isBody ?
4638 this.$floatableContainer.offset() :
4639 OO.ui.Element.static.getRelativePosition( this.$floatableContainer, $offsetParent );
4640 containerPos.bottom = containerPos.top + this.$floatableContainer.outerHeight();
4641 containerPos.right = containerPos.left + this.$floatableContainer.outerWidth();
4642 containerPos.start = direction === 'rtl' ? containerPos.right : containerPos.left;
4643 containerPos.end = direction === 'rtl' ? containerPos.left : containerPos.right;
4644
4645 if ( this.verticalPosition === 'below' ) {
4646 newPos.top = containerPos.bottom;
4647 } else if ( this.verticalPosition === 'above' ) {
4648 newPos.bottom = $offsetParent.outerHeight() - containerPos.top;
4649 } else if ( this.verticalPosition === 'top' ) {
4650 newPos.top = containerPos.top;
4651 } else if ( this.verticalPosition === 'bottom' ) {
4652 newPos.bottom = $offsetParent.outerHeight() - containerPos.bottom;
4653 } else if ( this.verticalPosition === 'center' ) {
4654 newPos.top = containerPos.top +
4655 ( this.$floatableContainer.height() - this.$floatable.height() ) / 2;
4656 }
4657
4658 if ( this.horizontalPosition === 'before' ) {
4659 newPos.end = containerPos.start;
4660 } else if ( this.horizontalPosition === 'after' ) {
4661 newPos.start = containerPos.end;
4662 } else if ( this.horizontalPosition === 'start' ) {
4663 newPos.start = containerPos.start;
4664 } else if ( this.horizontalPosition === 'end' ) {
4665 newPos.end = containerPos.end;
4666 } else if ( this.horizontalPosition === 'center' ) {
4667 newPos.left = containerPos.left +
4668 ( this.$floatableContainer.width() - this.$floatable.width() ) / 2;
4669 }
4670
4671 if ( newPos.start !== undefined ) {
4672 if ( direction === 'rtl' ) {
4673 newPos.right = ( isBody ? $( $offsetParent[ 0 ].ownerDocument.documentElement ) : $offsetParent ).outerWidth() - newPos.start;
4674 } else {
4675 newPos.left = newPos.start;
4676 }
4677 delete newPos.start;
4678 }
4679 if ( newPos.end !== undefined ) {
4680 if ( direction === 'rtl' ) {
4681 newPos.left = newPos.end;
4682 } else {
4683 newPos.right = ( isBody ? $( $offsetParent[ 0 ].ownerDocument.documentElement ) : $offsetParent ).outerWidth() - newPos.end;
4684 }
4685 delete newPos.end;
4686 }
4687
4688 // Account for scroll position
4689 if ( newPos.top !== '' ) {
4690 newPos.top += scrollTop;
4691 }
4692 if ( newPos.bottom !== '' ) {
4693 newPos.bottom -= scrollTop;
4694 }
4695 if ( newPos.left !== '' ) {
4696 newPos.left += scrollLeft;
4697 }
4698 if ( newPos.right !== '' ) {
4699 newPos.right -= scrollLeft;
4700 }
4701
4702 // Account for scrollbar gutter
4703 if ( newPos.bottom !== '' ) {
4704 newPos.bottom -= horizScrollbarHeight;
4705 }
4706 if ( direction === 'rtl' ) {
4707 if ( newPos.left !== '' ) {
4708 newPos.left -= vertScrollbarWidth;
4709 }
4710 } else {
4711 if ( newPos.right !== '' ) {
4712 newPos.right -= vertScrollbarWidth;
4713 }
4714 }
4715
4716 return newPos;
4717 };
4718
4719 /**
4720 * Element that can be automatically clipped to visible boundaries.
4721 *
4722 * Whenever the element's natural height changes, you have to call
4723 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
4724 * clipping correctly.
4725 *
4726 * The dimensions of #$clippableContainer will be compared to the boundaries of the
4727 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
4728 * then #$clippable will be given a fixed reduced height and/or width and will be made
4729 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
4730 * but you can build a static footer by setting #$clippableContainer to an element that contains
4731 * #$clippable and the footer.
4732 *
4733 * @abstract
4734 * @class
4735 *
4736 * @constructor
4737 * @param {Object} [config] Configuration options
4738 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
4739 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
4740 * omit to use #$clippable
4741 */
4742 OO.ui.mixin.ClippableElement = function OoUiMixinClippableElement( config ) {
4743 // Configuration initialization
4744 config = config || {};
4745
4746 // Properties
4747 this.$clippable = null;
4748 this.$clippableContainer = null;
4749 this.clipping = false;
4750 this.clippedHorizontally = false;
4751 this.clippedVertically = false;
4752 this.$clippableScrollableContainer = null;
4753 this.$clippableScroller = null;
4754 this.$clippableWindow = null;
4755 this.idealWidth = null;
4756 this.idealHeight = null;
4757 this.onClippableScrollHandler = this.clip.bind( this );
4758 this.onClippableWindowResizeHandler = this.clip.bind( this );
4759
4760 // Initialization
4761 if ( config.$clippableContainer ) {
4762 this.setClippableContainer( config.$clippableContainer );
4763 }
4764 this.setClippableElement( config.$clippable || this.$element );
4765 };
4766
4767 /* Methods */
4768
4769 /**
4770 * Set clippable element.
4771 *
4772 * If an element is already set, it will be cleaned up before setting up the new element.
4773 *
4774 * @param {jQuery} $clippable Element to make clippable
4775 */
4776 OO.ui.mixin.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
4777 if ( this.$clippable ) {
4778 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
4779 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
4780 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
4781 }
4782
4783 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
4784 this.clip();
4785 };
4786
4787 /**
4788 * Set clippable container.
4789 *
4790 * This is the container that will be measured when deciding whether to clip. When clipping,
4791 * #$clippable will be resized in order to keep the clippable container fully visible.
4792 *
4793 * If the clippable container is unset, #$clippable will be used.
4794 *
4795 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
4796 */
4797 OO.ui.mixin.ClippableElement.prototype.setClippableContainer = function ( $clippableContainer ) {
4798 this.$clippableContainer = $clippableContainer;
4799 if ( this.$clippable ) {
4800 this.clip();
4801 }
4802 };
4803
4804 /**
4805 * Toggle clipping.
4806 *
4807 * Do not turn clipping on until after the element is attached to the DOM and visible.
4808 *
4809 * @param {boolean} [clipping] Enable clipping, omit to toggle
4810 * @chainable
4811 */
4812 OO.ui.mixin.ClippableElement.prototype.toggleClipping = function ( clipping ) {
4813 clipping = clipping === undefined ? !this.clipping : !!clipping;
4814
4815 if ( clipping && !this.warnedUnattached && !this.isElementAttached() ) {
4816 OO.ui.warnDeprecation( 'ClippableElement#toggleClipping: Before calling this method, the element must be attached to the DOM.' );
4817 this.warnedUnattached = true;
4818 }
4819
4820 if ( this.clipping !== clipping ) {
4821 this.clipping = clipping;
4822 if ( clipping ) {
4823 this.$clippableScrollableContainer = $( this.getClosestScrollableElementContainer() );
4824 // If the clippable container is the root, we have to listen to scroll events and check
4825 // jQuery.scrollTop on the window because of browser inconsistencies
4826 this.$clippableScroller = this.$clippableScrollableContainer.is( 'html, body' ) ?
4827 $( OO.ui.Element.static.getWindow( this.$clippableScrollableContainer ) ) :
4828 this.$clippableScrollableContainer;
4829 this.$clippableScroller.on( 'scroll', this.onClippableScrollHandler );
4830 this.$clippableWindow = $( this.getElementWindow() )
4831 .on( 'resize', this.onClippableWindowResizeHandler );
4832 // Initial clip after visible
4833 this.clip();
4834 } else {
4835 this.$clippable.css( {
4836 width: '',
4837 height: '',
4838 maxWidth: '',
4839 maxHeight: '',
4840 overflowX: '',
4841 overflowY: ''
4842 } );
4843 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
4844
4845 this.$clippableScrollableContainer = null;
4846 this.$clippableScroller.off( 'scroll', this.onClippableScrollHandler );
4847 this.$clippableScroller = null;
4848 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
4849 this.$clippableWindow = null;
4850 }
4851 }
4852
4853 return this;
4854 };
4855
4856 /**
4857 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4858 *
4859 * @return {boolean} Element will be clipped to the visible area
4860 */
4861 OO.ui.mixin.ClippableElement.prototype.isClipping = function () {
4862 return this.clipping;
4863 };
4864
4865 /**
4866 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
4867 *
4868 * @return {boolean} Part of the element is being clipped
4869 */
4870 OO.ui.mixin.ClippableElement.prototype.isClipped = function () {
4871 return this.clippedHorizontally || this.clippedVertically;
4872 };
4873
4874 /**
4875 * Check if the 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.isClippedHorizontally = function () {
4880 return this.clippedHorizontally;
4881 };
4882
4883 /**
4884 * Check if the bottom 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.isClippedVertically = function () {
4889 return this.clippedVertically;
4890 };
4891
4892 /**
4893 * Set the ideal size. These are the dimensions #$clippable will have when it's not being clipped.
4894 *
4895 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
4896 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
4897 */
4898 OO.ui.mixin.ClippableElement.prototype.setIdealSize = function ( width, height ) {
4899 this.idealWidth = width;
4900 this.idealHeight = height;
4901
4902 if ( !this.clipping ) {
4903 // Update dimensions
4904 this.$clippable.css( { width: width, height: height } );
4905 }
4906 // While clipping, idealWidth and idealHeight are not considered
4907 };
4908
4909 /**
4910 * Return the side of the clippable on which it is "anchored" (aligned to something else).
4911 * ClippableElement will clip the opposite side when reducing element's width.
4912 *
4913 * Classes that mix in ClippableElement should override this to return 'right' if their
4914 * clippable is absolutely positioned and using 'right: Npx' (and not using 'left').
4915 * If your class also mixes in FloatableElement, this is handled automatically.
4916 *
4917 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
4918 * always in pixels, even if they were unset or set to 'auto'.)
4919 *
4920 * When in doubt, 'left' (or 'right' in RTL) is a sane fallback.
4921 *
4922 * @return {string} 'left' or 'right'
4923 */
4924 OO.ui.mixin.ClippableElement.prototype.getHorizontalAnchorEdge = function () {
4925 if ( this.computePosition && this.positioning && this.computePosition().right !== '' ) {
4926 return 'right';
4927 }
4928 return 'left';
4929 };
4930
4931 /**
4932 * Return the side of the clippable on which it is "anchored" (aligned to something else).
4933 * ClippableElement will clip the opposite side when reducing element's width.
4934 *
4935 * Classes that mix in ClippableElement should override this to return 'bottom' if their
4936 * clippable is absolutely positioned and using 'bottom: Npx' (and not using 'top').
4937 * If your class also mixes in FloatableElement, this is handled automatically.
4938 *
4939 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
4940 * always in pixels, even if they were unset or set to 'auto'.)
4941 *
4942 * When in doubt, 'top' is a sane fallback.
4943 *
4944 * @return {string} 'top' or 'bottom'
4945 */
4946 OO.ui.mixin.ClippableElement.prototype.getVerticalAnchorEdge = function () {
4947 if ( this.computePosition && this.positioning && this.computePosition().bottom !== '' ) {
4948 return 'bottom';
4949 }
4950 return 'top';
4951 };
4952
4953 /**
4954 * Clip element to visible boundaries and allow scrolling when needed. You should call this method
4955 * when the element's natural height changes.
4956 *
4957 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
4958 * overlapped by, the visible area of the nearest scrollable container.
4959 *
4960 * Because calling clip() when the natural height changes isn't always possible, we also set
4961 * max-height when the element isn't being clipped. This means that if the element tries to grow
4962 * beyond the edge, something reasonable will happen before clip() is called.
4963 *
4964 * @chainable
4965 */
4966 OO.ui.mixin.ClippableElement.prototype.clip = function () {
4967 var extraHeight, extraWidth, viewportSpacing,
4968 desiredWidth, desiredHeight, allotedWidth, allotedHeight,
4969 naturalWidth, naturalHeight, clipWidth, clipHeight,
4970 $item, itemRect, $viewport, viewportRect, availableRect,
4971 direction, vertScrollbarWidth, horizScrollbarHeight,
4972 // Extra tolerance so that the sloppy code below doesn't result in results that are off
4973 // by one or two pixels. (And also so that we have space to display drop shadows.)
4974 // Chosen by fair dice roll.
4975 buffer = 7;
4976
4977 if ( !this.clipping ) {
4978 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
4979 return this;
4980 }
4981
4982 function rectIntersection( a, b ) {
4983 var out = {};
4984 out.top = Math.max( a.top, b.top );
4985 out.left = Math.max( a.left, b.left );
4986 out.bottom = Math.min( a.bottom, b.bottom );
4987 out.right = Math.min( a.right, b.right );
4988 return out;
4989 }
4990
4991 viewportSpacing = OO.ui.getViewportSpacing();
4992
4993 if ( this.$clippableScrollableContainer.is( 'html, body' ) ) {
4994 $viewport = $( this.$clippableScrollableContainer[ 0 ].ownerDocument.body );
4995 // Dimensions of the browser window, rather than the element!
4996 viewportRect = {
4997 top: 0,
4998 left: 0,
4999 right: document.documentElement.clientWidth,
5000 bottom: document.documentElement.clientHeight
5001 };
5002 viewportRect.top += viewportSpacing.top;
5003 viewportRect.left += viewportSpacing.left;
5004 viewportRect.right -= viewportSpacing.right;
5005 viewportRect.bottom -= viewportSpacing.bottom;
5006 } else {
5007 $viewport = this.$clippableScrollableContainer;
5008 viewportRect = $viewport[ 0 ].getBoundingClientRect();
5009 // Convert into a plain object
5010 viewportRect = $.extend( {}, viewportRect );
5011 }
5012
5013 // Account for scrollbar gutter
5014 direction = $viewport.css( 'direction' );
5015 vertScrollbarWidth = $viewport.innerWidth() - $viewport.prop( 'clientWidth' );
5016 horizScrollbarHeight = $viewport.innerHeight() - $viewport.prop( 'clientHeight' );
5017 viewportRect.bottom -= horizScrollbarHeight;
5018 if ( direction === 'rtl' ) {
5019 viewportRect.left += vertScrollbarWidth;
5020 } else {
5021 viewportRect.right -= vertScrollbarWidth;
5022 }
5023
5024 // Add arbitrary tolerance
5025 viewportRect.top += buffer;
5026 viewportRect.left += buffer;
5027 viewportRect.right -= buffer;
5028 viewportRect.bottom -= buffer;
5029
5030 $item = this.$clippableContainer || this.$clippable;
5031
5032 extraHeight = $item.outerHeight() - this.$clippable.outerHeight();
5033 extraWidth = $item.outerWidth() - this.$clippable.outerWidth();
5034
5035 itemRect = $item[ 0 ].getBoundingClientRect();
5036 // Convert into a plain object
5037 itemRect = $.extend( {}, itemRect );
5038
5039 // Item might already be clipped, so we can't just use its dimensions (in case we might need to
5040 // make it larger than before). Extend the rectangle to the maximum size we are allowed to take.
5041 if ( this.getHorizontalAnchorEdge() === 'right' ) {
5042 itemRect.left = viewportRect.left;
5043 } else {
5044 itemRect.right = viewportRect.right;
5045 }
5046 if ( this.getVerticalAnchorEdge() === 'bottom' ) {
5047 itemRect.top = viewportRect.top;
5048 } else {
5049 itemRect.bottom = viewportRect.bottom;
5050 }
5051
5052 availableRect = rectIntersection( viewportRect, itemRect );
5053
5054 desiredWidth = Math.max( 0, availableRect.right - availableRect.left );
5055 desiredHeight = Math.max( 0, availableRect.bottom - availableRect.top );
5056 // It should never be desirable to exceed the dimensions of the browser viewport... right?
5057 desiredWidth = Math.min( desiredWidth,
5058 document.documentElement.clientWidth - viewportSpacing.left - viewportSpacing.right );
5059 desiredHeight = Math.min( desiredHeight,
5060 document.documentElement.clientHeight - viewportSpacing.top - viewportSpacing.right );
5061 allotedWidth = Math.ceil( desiredWidth - extraWidth );
5062 allotedHeight = Math.ceil( desiredHeight - extraHeight );
5063 naturalWidth = this.$clippable.prop( 'scrollWidth' );
5064 naturalHeight = this.$clippable.prop( 'scrollHeight' );
5065 clipWidth = allotedWidth < naturalWidth;
5066 clipHeight = allotedHeight < naturalHeight;
5067
5068 if ( clipWidth ) {
5069 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. See T157672.
5070 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
5071 this.$clippable.css( 'overflowX', 'scroll' );
5072 void this.$clippable[ 0 ].offsetHeight; // Force reflow
5073 this.$clippable.css( {
5074 width: Math.max( 0, allotedWidth ),
5075 maxWidth: ''
5076 } );
5077 } else {
5078 this.$clippable.css( {
5079 overflowX: '',
5080 width: this.idealWidth || '',
5081 maxWidth: Math.max( 0, allotedWidth )
5082 } );
5083 }
5084 if ( clipHeight ) {
5085 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. See T157672.
5086 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
5087 this.$clippable.css( 'overflowY', 'scroll' );
5088 void this.$clippable[ 0 ].offsetHeight; // Force reflow
5089 this.$clippable.css( {
5090 height: Math.max( 0, allotedHeight ),
5091 maxHeight: ''
5092 } );
5093 } else {
5094 this.$clippable.css( {
5095 overflowY: '',
5096 height: this.idealHeight || '',
5097 maxHeight: Math.max( 0, allotedHeight )
5098 } );
5099 }
5100
5101 // If we stopped clipping in at least one of the dimensions
5102 if ( ( this.clippedHorizontally && !clipWidth ) || ( this.clippedVertically && !clipHeight ) ) {
5103 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
5104 }
5105
5106 this.clippedHorizontally = clipWidth;
5107 this.clippedVertically = clipHeight;
5108
5109 return this;
5110 };
5111
5112 /**
5113 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
5114 * By default, each popup has an anchor that points toward its origin.
5115 * Please see the [OOUI documentation on MediaWiki.org] [1] for more information and examples.
5116 *
5117 * Unlike most widgets, PopupWidget is initially hidden and must be shown by calling #toggle.
5118 *
5119 * @example
5120 * // A popup widget.
5121 * var popup = new OO.ui.PopupWidget( {
5122 * $content: $( '<p>Hi there!</p>' ),
5123 * padded: true,
5124 * width: 300
5125 * } );
5126 *
5127 * $( 'body' ).append( popup.$element );
5128 * // To display the popup, toggle the visibility to 'true'.
5129 * popup.toggle( true );
5130 *
5131 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups
5132 *
5133 * @class
5134 * @extends OO.ui.Widget
5135 * @mixins OO.ui.mixin.LabelElement
5136 * @mixins OO.ui.mixin.ClippableElement
5137 * @mixins OO.ui.mixin.FloatableElement
5138 *
5139 * @constructor
5140 * @param {Object} [config] Configuration options
5141 * @cfg {number|null} [width=320] Width of popup in pixels. Pass `null` to use automatic width.
5142 * @cfg {number|null} [height=null] Height of popup in pixels. Pass `null` to use automatic height.
5143 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
5144 * @cfg {string} [position='below'] Where to position the popup relative to $floatableContainer
5145 * 'above': Put popup above $floatableContainer; anchor points down to the horizontal center
5146 * of $floatableContainer
5147 * 'below': Put popup below $floatableContainer; anchor points up to the horizontal center
5148 * of $floatableContainer
5149 * 'before': Put popup to the left (LTR) / right (RTL) of $floatableContainer; anchor points
5150 * endwards (right/left) to the vertical center of $floatableContainer
5151 * 'after': Put popup to the right (LTR) / left (RTL) of $floatableContainer; anchor points
5152 * startwards (left/right) to the vertical center of $floatableContainer
5153 * @cfg {string} [align='center'] How to align the popup to $floatableContainer
5154 * 'forwards': If position is above/below, move the popup as far endwards (right in LTR, left in RTL)
5155 * as possible while still keeping the anchor within the popup;
5156 * if position is before/after, move the popup as far downwards as possible.
5157 * 'backwards': If position is above/below, move the popup as far startwards (left in LTR, right in RTL)
5158 * as possible while still keeping the anchor within the popup;
5159 * if position in before/after, move the popup as far upwards as possible.
5160 * 'center': Horizontally (if position is above/below) or vertically (before/after) align the center
5161 * of the popup with the center of $floatableContainer.
5162 * 'force-left': Alias for 'forwards' in LTR and 'backwards' in RTL
5163 * 'force-right': Alias for 'backwards' in RTL and 'forwards' in LTR
5164 * @cfg {boolean} [autoFlip=true] Whether to automatically switch the popup's position between
5165 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5166 * desired direction to display the popup without clipping
5167 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
5168 * See the [OOUI docs on MediaWiki][3] for an example.
5169 * [3]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#containerExample
5170 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
5171 * @cfg {jQuery} [$content] Content to append to the popup's body
5172 * @cfg {jQuery} [$footer] Content to append to the popup's footer
5173 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
5174 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
5175 * This config option is only relevant if #autoClose is set to `true`. See the [OOUI documentation on MediaWiki][2]
5176 * for an example.
5177 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#autocloseExample
5178 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
5179 * button.
5180 * @cfg {boolean} [padded=false] Add padding to the popup's body
5181 */
5182 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
5183 // Configuration initialization
5184 config = config || {};
5185
5186 // Parent constructor
5187 OO.ui.PopupWidget.parent.call( this, config );
5188
5189 // Properties (must be set before ClippableElement constructor call)
5190 this.$body = $( '<div>' );
5191 this.$popup = $( '<div>' );
5192
5193 // Mixin constructors
5194 OO.ui.mixin.LabelElement.call( this, config );
5195 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, {
5196 $clippable: this.$body,
5197 $clippableContainer: this.$popup
5198 } ) );
5199 OO.ui.mixin.FloatableElement.call( this, config );
5200
5201 // Properties
5202 this.$anchor = $( '<div>' );
5203 // If undefined, will be computed lazily in computePosition()
5204 this.$container = config.$container;
5205 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
5206 this.autoClose = !!config.autoClose;
5207 this.transitionTimeout = null;
5208 this.anchored = false;
5209 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
5210 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
5211
5212 // Initialization
5213 this.setSize( config.width, config.height );
5214 this.toggleAnchor( config.anchor === undefined || config.anchor );
5215 this.setAlignment( config.align || 'center' );
5216 this.setPosition( config.position || 'below' );
5217 this.setAutoFlip( config.autoFlip === undefined || config.autoFlip );
5218 this.setAutoCloseIgnore( config.$autoCloseIgnore );
5219 this.$body.addClass( 'oo-ui-popupWidget-body' );
5220 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
5221 this.$popup
5222 .addClass( 'oo-ui-popupWidget-popup' )
5223 .append( this.$body );
5224 this.$element
5225 .addClass( 'oo-ui-popupWidget' )
5226 .append( this.$popup, this.$anchor );
5227 // Move content, which was added to #$element by OO.ui.Widget, to the body
5228 // FIXME This is gross, we should use '$body' or something for the config
5229 if ( config.$content instanceof jQuery ) {
5230 this.$body.append( config.$content );
5231 }
5232
5233 if ( config.padded ) {
5234 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
5235 }
5236
5237 if ( config.head ) {
5238 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
5239 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
5240 this.$head = $( '<div>' )
5241 .addClass( 'oo-ui-popupWidget-head' )
5242 .append( this.$label, this.closeButton.$element );
5243 this.$popup.prepend( this.$head );
5244 }
5245
5246 if ( config.$footer ) {
5247 this.$footer = $( '<div>' )
5248 .addClass( 'oo-ui-popupWidget-footer' )
5249 .append( config.$footer );
5250 this.$popup.append( this.$footer );
5251 }
5252
5253 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
5254 // that reference properties not initialized at that time of parent class construction
5255 // TODO: Find a better way to handle post-constructor setup
5256 this.visible = false;
5257 this.$element.addClass( 'oo-ui-element-hidden' );
5258 };
5259
5260 /* Setup */
5261
5262 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
5263 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.LabelElement );
5264 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.ClippableElement );
5265 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.FloatableElement );
5266
5267 /* Events */
5268
5269 /**
5270 * @event ready
5271 *
5272 * The popup is ready: it is visible and has been positioned and clipped.
5273 */
5274
5275 /* Methods */
5276
5277 /**
5278 * Handles document mouse down events.
5279 *
5280 * @private
5281 * @param {MouseEvent} e Mouse down event
5282 */
5283 OO.ui.PopupWidget.prototype.onDocumentMouseDown = function ( e ) {
5284 if (
5285 this.isVisible() &&
5286 !OO.ui.contains( this.$element.add( this.$autoCloseIgnore ).get(), e.target, true )
5287 ) {
5288 this.toggle( false );
5289 }
5290 };
5291
5292 // Deprecated alias since 0.28.3
5293 OO.ui.PopupWidget.prototype.onMouseDown = function () {
5294 OO.ui.warnDeprecation( 'onMouseDown is deprecated, use onDocumentMouseDown instead' );
5295 this.onDocumentMouseDown.apply( this, arguments );
5296 };
5297
5298 /**
5299 * Bind document mouse down listener.
5300 *
5301 * @private
5302 */
5303 OO.ui.PopupWidget.prototype.bindDocumentMouseDownListener = function () {
5304 // Capture clicks outside popup
5305 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
5306 // We add 'click' event because iOS safari needs to respond to this event.
5307 // We can't use 'touchstart' (as is usually the equivalent to 'mousedown') because
5308 // then it will trigger when scrolling. While iOS Safari has some reported behavior
5309 // of occasionally not emitting 'click' properly, that event seems to be the standard
5310 // that it should be emitting, so we add it to this and will operate the event handler
5311 // on whichever of these events was triggered first
5312 this.getElementDocument().addEventListener( 'click', this.onDocumentMouseDownHandler, true );
5313 };
5314
5315 // Deprecated alias since 0.28.3
5316 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
5317 OO.ui.warnDeprecation( 'bindMouseDownListener is deprecated, use bindDocumentMouseDownListener instead' );
5318 this.bindDocumentMouseDownListener.apply( this, arguments );
5319 };
5320
5321 /**
5322 * Handles close button click events.
5323 *
5324 * @private
5325 */
5326 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
5327 if ( this.isVisible() ) {
5328 this.toggle( false );
5329 }
5330 };
5331
5332 /**
5333 * Unbind document mouse down listener.
5334 *
5335 * @private
5336 */
5337 OO.ui.PopupWidget.prototype.unbindDocumentMouseDownListener = function () {
5338 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
5339 this.getElementDocument().removeEventListener( 'click', this.onDocumentMouseDownHandler, true );
5340 };
5341
5342 // Deprecated alias since 0.28.3
5343 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
5344 OO.ui.warnDeprecation( 'unbindMouseDownListener is deprecated, use unbindDocumentMouseDownListener instead' );
5345 this.unbindDocumentMouseDownListener.apply( this, arguments );
5346 };
5347
5348 /**
5349 * Handles document key down events.
5350 *
5351 * @private
5352 * @param {KeyboardEvent} e Key down event
5353 */
5354 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
5355 if (
5356 e.which === OO.ui.Keys.ESCAPE &&
5357 this.isVisible()
5358 ) {
5359 this.toggle( false );
5360 e.preventDefault();
5361 e.stopPropagation();
5362 }
5363 };
5364
5365 /**
5366 * Bind document key down listener.
5367 *
5368 * @private
5369 */
5370 OO.ui.PopupWidget.prototype.bindDocumentKeyDownListener = function () {
5371 this.getElementDocument().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
5372 };
5373
5374 // Deprecated alias since 0.28.3
5375 OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
5376 OO.ui.warnDeprecation( 'bindKeyDownListener is deprecated, use bindDocumentKeyDownListener instead' );
5377 this.bindDocumentKeyDownListener.apply( this, arguments );
5378 };
5379
5380 /**
5381 * Unbind document key down listener.
5382 *
5383 * @private
5384 */
5385 OO.ui.PopupWidget.prototype.unbindDocumentKeyDownListener = function () {
5386 this.getElementDocument().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
5387 };
5388
5389 // Deprecated alias since 0.28.3
5390 OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
5391 OO.ui.warnDeprecation( 'unbindKeyDownListener is deprecated, use unbindDocumentKeyDownListener instead' );
5392 this.unbindDocumentKeyDownListener.apply( this, arguments );
5393 };
5394
5395 /**
5396 * Show, hide, or toggle the visibility of the anchor.
5397 *
5398 * @param {boolean} [show] Show anchor, omit to toggle
5399 */
5400 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
5401 show = show === undefined ? !this.anchored : !!show;
5402
5403 if ( this.anchored !== show ) {
5404 if ( show ) {
5405 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
5406 this.$element.addClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge );
5407 } else {
5408 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
5409 this.$element.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge );
5410 }
5411 this.anchored = show;
5412 }
5413 };
5414
5415 /**
5416 * Change which edge the anchor appears on.
5417 *
5418 * @param {string} edge 'top', 'bottom', 'start' or 'end'
5419 */
5420 OO.ui.PopupWidget.prototype.setAnchorEdge = function ( edge ) {
5421 if ( [ 'top', 'bottom', 'start', 'end' ].indexOf( edge ) === -1 ) {
5422 throw new Error( 'Invalid value for edge: ' + edge );
5423 }
5424 if ( this.anchorEdge !== null ) {
5425 this.$element.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge );
5426 }
5427 this.anchorEdge = edge;
5428 if ( this.anchored ) {
5429 this.$element.addClass( 'oo-ui-popupWidget-anchored-' + edge );
5430 }
5431 };
5432
5433 /**
5434 * Check if the anchor is visible.
5435 *
5436 * @return {boolean} Anchor is visible
5437 */
5438 OO.ui.PopupWidget.prototype.hasAnchor = function () {
5439 return this.anchored;
5440 };
5441
5442 /**
5443 * Toggle visibility of the popup. The popup is initially hidden and must be shown by calling
5444 * `.toggle( true )` after its #$element is attached to the DOM.
5445 *
5446 * Do not show the popup while it is not attached to the DOM. The calculations required to display
5447 * it in the right place and with the right dimensions only work correctly while it is attached.
5448 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
5449 * strictly enforced, so currently it only generates a warning in the browser console.
5450 *
5451 * @fires ready
5452 * @inheritdoc
5453 */
5454 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
5455 var change, normalHeight, oppositeHeight, normalWidth, oppositeWidth;
5456 show = show === undefined ? !this.isVisible() : !!show;
5457
5458 change = show !== this.isVisible();
5459
5460 if ( show && !this.warnedUnattached && !this.isElementAttached() ) {
5461 OO.ui.warnDeprecation( 'PopupWidget#toggle: Before calling this method, the popup must be attached to the DOM.' );
5462 this.warnedUnattached = true;
5463 }
5464 if ( show && !this.$floatableContainer && this.isElementAttached() ) {
5465 // Fall back to the parent node if the floatableContainer is not set
5466 this.setFloatableContainer( this.$element.parent() );
5467 }
5468
5469 if ( change && show && this.autoFlip ) {
5470 // Reset auto-flipping before showing the popup again. It's possible we no longer need to flip
5471 // (e.g. if the user scrolled).
5472 this.isAutoFlipped = false;
5473 }
5474
5475 // Parent method
5476 OO.ui.PopupWidget.parent.prototype.toggle.call( this, show );
5477
5478 if ( change ) {
5479 this.togglePositioning( show && !!this.$floatableContainer );
5480
5481 if ( show ) {
5482 if ( this.autoClose ) {
5483 this.bindDocumentMouseDownListener();
5484 this.bindDocumentKeyDownListener();
5485 }
5486 this.updateDimensions();
5487 this.toggleClipping( true );
5488
5489 if ( this.autoFlip ) {
5490 if ( this.popupPosition === 'above' || this.popupPosition === 'below' ) {
5491 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5492 // If opening the popup in the normal direction causes it to be clipped, open
5493 // in the opposite one instead
5494 normalHeight = this.$element.height();
5495 this.isAutoFlipped = !this.isAutoFlipped;
5496 this.position();
5497 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5498 // If that also causes it to be clipped, open in whichever direction
5499 // we have more space
5500 oppositeHeight = this.$element.height();
5501 if ( oppositeHeight < normalHeight ) {
5502 this.isAutoFlipped = !this.isAutoFlipped;
5503 this.position();
5504 }
5505 }
5506 }
5507 }
5508 if ( this.popupPosition === 'before' || this.popupPosition === 'after' ) {
5509 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5510 // If opening the popup in the normal direction causes it to be clipped, open
5511 // in the opposite one instead
5512 normalWidth = this.$element.width();
5513 this.isAutoFlipped = !this.isAutoFlipped;
5514 // Due to T180173 horizontally clipped PopupWidgets have messed up dimensions,
5515 // which causes positioning to be off. Toggle clipping back and fort to work around.
5516 this.toggleClipping( false );
5517 this.position();
5518 this.toggleClipping( true );
5519 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5520 // If that also causes it to be clipped, open in whichever direction
5521 // we have more space
5522 oppositeWidth = this.$element.width();
5523 if ( oppositeWidth < normalWidth ) {
5524 this.isAutoFlipped = !this.isAutoFlipped;
5525 // Due to T180173 horizontally clipped PopupWidgets have messed up dimensions,
5526 // which causes positioning to be off. Toggle clipping back and fort to work around.
5527 this.toggleClipping( false );
5528 this.position();
5529 this.toggleClipping( true );
5530 }
5531 }
5532 }
5533 }
5534 }
5535
5536 this.emit( 'ready' );
5537 } else {
5538 this.toggleClipping( false );
5539 if ( this.autoClose ) {
5540 this.unbindDocumentMouseDownListener();
5541 this.unbindDocumentKeyDownListener();
5542 }
5543 }
5544 }
5545
5546 return this;
5547 };
5548
5549 /**
5550 * Set the size of the popup.
5551 *
5552 * Changing the size may also change the popup's position depending on the alignment.
5553 *
5554 * @param {number|null} [width=320] Width in pixels. Pass `null` to use automatic width.
5555 * @param {number|null} [height=null] Height in pixels. Pass `null` to use automatic height.
5556 * @param {boolean} [transition=false] Use a smooth transition
5557 * @chainable
5558 */
5559 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
5560 this.width = width !== undefined ? width : 320;
5561 this.height = height !== undefined ? height : null;
5562 if ( this.isVisible() ) {
5563 this.updateDimensions( transition );
5564 }
5565 };
5566
5567 /**
5568 * Update the size and position.
5569 *
5570 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
5571 * be called automatically.
5572 *
5573 * @param {boolean} [transition=false] Use a smooth transition
5574 * @chainable
5575 */
5576 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
5577 var widget = this;
5578
5579 // Prevent transition from being interrupted
5580 clearTimeout( this.transitionTimeout );
5581 if ( transition ) {
5582 // Enable transition
5583 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
5584 }
5585
5586 this.position();
5587
5588 if ( transition ) {
5589 // Prevent transitioning after transition is complete
5590 this.transitionTimeout = setTimeout( function () {
5591 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
5592 }, 200 );
5593 } else {
5594 // Prevent transitioning immediately
5595 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
5596 }
5597 };
5598
5599 /**
5600 * @inheritdoc
5601 */
5602 OO.ui.PopupWidget.prototype.computePosition = function () {
5603 var direction, align, vertical, start, end, near, far, sizeProp, popupSize, anchorSize, anchorPos,
5604 anchorOffset, anchorMargin, parentPosition, positionProp, positionAdjustment, floatablePos,
5605 offsetParentPos, containerPos, popupPosition, viewportSpacing,
5606 popupPos = {},
5607 anchorCss = { left: '', right: '', top: '', bottom: '' },
5608 popupPositionOppositeMap = {
5609 above: 'below',
5610 below: 'above',
5611 before: 'after',
5612 after: 'before'
5613 },
5614 alignMap = {
5615 ltr: {
5616 'force-left': 'backwards',
5617 'force-right': 'forwards'
5618 },
5619 rtl: {
5620 'force-left': 'forwards',
5621 'force-right': 'backwards'
5622 }
5623 },
5624 anchorEdgeMap = {
5625 above: 'bottom',
5626 below: 'top',
5627 before: 'end',
5628 after: 'start'
5629 },
5630 hPosMap = {
5631 forwards: 'start',
5632 center: 'center',
5633 backwards: this.anchored ? 'before' : 'end'
5634 },
5635 vPosMap = {
5636 forwards: 'top',
5637 center: 'center',
5638 backwards: 'bottom'
5639 };
5640
5641 if ( !this.$container ) {
5642 // Lazy-initialize $container if not specified in constructor
5643 this.$container = $( this.getClosestScrollableElementContainer() );
5644 }
5645 direction = this.$container.css( 'direction' );
5646
5647 // Set height and width before we do anything else, since it might cause our measurements
5648 // to change (e.g. due to scrollbars appearing or disappearing), and it also affects centering
5649 this.$popup.css( {
5650 width: this.width !== null ? this.width : 'auto',
5651 height: this.height !== null ? this.height : 'auto'
5652 } );
5653
5654 align = alignMap[ direction ][ this.align ] || this.align;
5655 popupPosition = this.popupPosition;
5656 if ( this.isAutoFlipped ) {
5657 popupPosition = popupPositionOppositeMap[ popupPosition ];
5658 }
5659
5660 // If the popup is positioned before or after, then the anchor positioning is vertical, otherwise horizontal
5661 vertical = popupPosition === 'before' || popupPosition === 'after';
5662 start = vertical ? 'top' : ( direction === 'rtl' ? 'right' : 'left' );
5663 end = vertical ? 'bottom' : ( direction === 'rtl' ? 'left' : 'right' );
5664 near = vertical ? 'top' : 'left';
5665 far = vertical ? 'bottom' : 'right';
5666 sizeProp = vertical ? 'Height' : 'Width';
5667 popupSize = vertical ? ( this.height || this.$popup.height() ) : ( this.width || this.$popup.width() );
5668
5669 this.setAnchorEdge( anchorEdgeMap[ popupPosition ] );
5670 this.horizontalPosition = vertical ? popupPosition : hPosMap[ align ];
5671 this.verticalPosition = vertical ? vPosMap[ align ] : popupPosition;
5672
5673 // Parent method
5674 parentPosition = OO.ui.mixin.FloatableElement.prototype.computePosition.call( this );
5675 // Find out which property FloatableElement used for positioning, and adjust that value
5676 positionProp = vertical ?
5677 ( parentPosition.top !== '' ? 'top' : 'bottom' ) :
5678 ( parentPosition.left !== '' ? 'left' : 'right' );
5679
5680 // Figure out where the near and far edges of the popup and $floatableContainer are
5681 floatablePos = this.$floatableContainer.offset();
5682 floatablePos[ far ] = floatablePos[ near ] + this.$floatableContainer[ 'outer' + sizeProp ]();
5683 // Measure where the offsetParent is and compute our position based on that and parentPosition
5684 offsetParentPos = this.$element.offsetParent()[ 0 ] === document.documentElement ?
5685 { top: 0, left: 0 } :
5686 this.$element.offsetParent().offset();
5687
5688 if ( positionProp === near ) {
5689 popupPos[ near ] = offsetParentPos[ near ] + parentPosition[ near ];
5690 popupPos[ far ] = popupPos[ near ] + popupSize;
5691 } else {
5692 popupPos[ far ] = offsetParentPos[ near ] +
5693 this.$element.offsetParent()[ 'inner' + sizeProp ]() - parentPosition[ far ];
5694 popupPos[ near ] = popupPos[ far ] - popupSize;
5695 }
5696
5697 if ( this.anchored ) {
5698 // Position the anchor (which is positioned relative to the popup) to point to $floatableContainer
5699 anchorPos = ( floatablePos[ start ] + floatablePos[ end ] ) / 2;
5700 anchorOffset = ( start === far ? -1 : 1 ) * ( anchorPos - popupPos[ start ] );
5701
5702 // If the anchor is less than 2*anchorSize from either edge, move the popup to make more space
5703 // this.$anchor.width()/height() returns 0 because of the CSS trickery we use, so use scrollWidth/Height
5704 anchorSize = this.$anchor[ 0 ][ 'scroll' + sizeProp ];
5705 anchorMargin = parseFloat( this.$anchor.css( 'margin-' + start ) );
5706 if ( anchorOffset + anchorMargin < 2 * anchorSize ) {
5707 // Not enough space for the anchor on the start side; pull the popup startwards
5708 positionAdjustment = ( positionProp === start ? -1 : 1 ) *
5709 ( 2 * anchorSize - ( anchorOffset + anchorMargin ) );
5710 } else if ( anchorOffset + anchorMargin > popupSize - 2 * anchorSize ) {
5711 // Not enough space for the anchor on the end side; pull the popup endwards
5712 positionAdjustment = ( positionProp === end ? -1 : 1 ) *
5713 ( anchorOffset + anchorMargin - ( popupSize - 2 * anchorSize ) );
5714 } else {
5715 positionAdjustment = 0;
5716 }
5717 } else {
5718 positionAdjustment = 0;
5719 }
5720
5721 // Check if the popup will go beyond the edge of this.$container
5722 containerPos = this.$container[ 0 ] === document.documentElement ?
5723 { top: 0, left: 0 } :
5724 this.$container.offset();
5725 containerPos[ far ] = containerPos[ near ] + this.$container[ 'inner' + sizeProp ]();
5726 if ( this.$container[ 0 ] === document.documentElement ) {
5727 viewportSpacing = OO.ui.getViewportSpacing();
5728 containerPos[ near ] += viewportSpacing[ near ];
5729 containerPos[ far ] -= viewportSpacing[ far ];
5730 }
5731 // Take into account how much the popup will move because of the adjustments we're going to make
5732 popupPos[ near ] += ( positionProp === near ? 1 : -1 ) * positionAdjustment;
5733 popupPos[ far ] += ( positionProp === near ? 1 : -1 ) * positionAdjustment;
5734 if ( containerPos[ near ] + this.containerPadding > popupPos[ near ] ) {
5735 // Popup goes beyond the near (left/top) edge, move it to the right/bottom
5736 positionAdjustment += ( positionProp === near ? 1 : -1 ) *
5737 ( containerPos[ near ] + this.containerPadding - popupPos[ near ] );
5738 } else if ( containerPos[ far ] - this.containerPadding < popupPos[ far ] ) {
5739 // Popup goes beyond the far (right/bottom) edge, move it to the left/top
5740 positionAdjustment += ( positionProp === far ? 1 : -1 ) *
5741 ( popupPos[ far ] - ( containerPos[ far ] - this.containerPadding ) );
5742 }
5743
5744 if ( this.anchored ) {
5745 // Adjust anchorOffset for positionAdjustment
5746 anchorOffset += ( positionProp === start ? -1 : 1 ) * positionAdjustment;
5747
5748 // Position the anchor
5749 anchorCss[ start ] = anchorOffset;
5750 this.$anchor.css( anchorCss );
5751 }
5752
5753 // Move the popup if needed
5754 parentPosition[ positionProp ] += positionAdjustment;
5755
5756 return parentPosition;
5757 };
5758
5759 /**
5760 * Set popup alignment
5761 *
5762 * @param {string} [align=center] Alignment of the popup, `center`, `force-left`, `force-right`,
5763 * `backwards` or `forwards`.
5764 */
5765 OO.ui.PopupWidget.prototype.setAlignment = function ( align ) {
5766 // Validate alignment
5767 if ( [ 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align ) > -1 ) {
5768 this.align = align;
5769 } else {
5770 this.align = 'center';
5771 }
5772 this.position();
5773 };
5774
5775 /**
5776 * Get popup alignment
5777 *
5778 * @return {string} Alignment of the popup, `center`, `force-left`, `force-right`,
5779 * `backwards` or `forwards`.
5780 */
5781 OO.ui.PopupWidget.prototype.getAlignment = function () {
5782 return this.align;
5783 };
5784
5785 /**
5786 * Change the positioning of the popup.
5787 *
5788 * @param {string} position 'above', 'below', 'before' or 'after'
5789 */
5790 OO.ui.PopupWidget.prototype.setPosition = function ( position ) {
5791 if ( [ 'above', 'below', 'before', 'after' ].indexOf( position ) === -1 ) {
5792 position = 'below';
5793 }
5794 this.popupPosition = position;
5795 this.position();
5796 };
5797
5798 /**
5799 * Get popup positioning.
5800 *
5801 * @return {string} 'above', 'below', 'before' or 'after'
5802 */
5803 OO.ui.PopupWidget.prototype.getPosition = function () {
5804 return this.popupPosition;
5805 };
5806
5807 /**
5808 * Set popup auto-flipping.
5809 *
5810 * @param {boolean} autoFlip Whether to automatically switch the popup's position between
5811 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5812 * desired direction to display the popup without clipping
5813 */
5814 OO.ui.PopupWidget.prototype.setAutoFlip = function ( autoFlip ) {
5815 autoFlip = !!autoFlip;
5816
5817 if ( this.autoFlip !== autoFlip ) {
5818 this.autoFlip = autoFlip;
5819 }
5820 };
5821
5822 /**
5823 * Set which elements will not close the popup when clicked.
5824 *
5825 * For auto-closing popups, clicks on these elements will not cause the popup to auto-close.
5826 *
5827 * @param {jQuery} $autoCloseIgnore Elements to ignore for auto-closing
5828 */
5829 OO.ui.PopupWidget.prototype.setAutoCloseIgnore = function ( $autoCloseIgnore ) {
5830 this.$autoCloseIgnore = $autoCloseIgnore;
5831 };
5832
5833 /**
5834 * Get an ID of the body element, this can be used as the
5835 * `aria-describedby` attribute for an input field.
5836 *
5837 * @return {string} The ID of the body element
5838 */
5839 OO.ui.PopupWidget.prototype.getBodyId = function () {
5840 var id = this.$body.attr( 'id' );
5841 if ( id === undefined ) {
5842 id = OO.ui.generateElementId();
5843 this.$body.attr( 'id', id );
5844 }
5845 return id;
5846 };
5847
5848 /**
5849 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5850 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5851 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5852 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5853 *
5854 * @abstract
5855 * @class
5856 *
5857 * @constructor
5858 * @param {Object} [config] Configuration options
5859 * @cfg {Object} [popup] Configuration to pass to popup
5860 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5861 */
5862 OO.ui.mixin.PopupElement = function OoUiMixinPopupElement( config ) {
5863 // Configuration initialization
5864 config = config || {};
5865
5866 // Properties
5867 this.popup = new OO.ui.PopupWidget( $.extend(
5868 {
5869 autoClose: true,
5870 $floatableContainer: this.$element
5871 },
5872 config.popup,
5873 {
5874 $autoCloseIgnore: this.$element.add( config.popup && config.popup.$autoCloseIgnore )
5875 }
5876 ) );
5877 };
5878
5879 /* Methods */
5880
5881 /**
5882 * Get popup.
5883 *
5884 * @return {OO.ui.PopupWidget} Popup widget
5885 */
5886 OO.ui.mixin.PopupElement.prototype.getPopup = function () {
5887 return this.popup;
5888 };
5889
5890 /**
5891 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
5892 * which is used to display additional information or options.
5893 *
5894 * @example
5895 * // Example of a popup button.
5896 * var popupButton = new OO.ui.PopupButtonWidget( {
5897 * label: 'Popup button with options',
5898 * icon: 'menu',
5899 * popup: {
5900 * $content: $( '<p>Additional options here.</p>' ),
5901 * padded: true,
5902 * align: 'force-left'
5903 * }
5904 * } );
5905 * // Append the button to the DOM.
5906 * $( 'body' ).append( popupButton.$element );
5907 *
5908 * @class
5909 * @extends OO.ui.ButtonWidget
5910 * @mixins OO.ui.mixin.PopupElement
5911 *
5912 * @constructor
5913 * @param {Object} [config] Configuration options
5914 * @cfg {jQuery} [$overlay] Render the popup into a separate layer. This configuration is useful in cases where
5915 * the expanded popup is larger than its containing `<div>`. The specified overlay layer is usually on top of the
5916 * containing `<div>` and has a larger area. By default, the popup uses relative positioning.
5917 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
5918 */
5919 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
5920 // Configuration initialization
5921 config = config || {};
5922
5923 // Parent constructor
5924 OO.ui.PopupButtonWidget.parent.call( this, config );
5925
5926 // Mixin constructors
5927 OO.ui.mixin.PopupElement.call( this, config );
5928
5929 // Properties
5930 this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
5931
5932 // Events
5933 this.connect( this, { click: 'onAction' } );
5934
5935 // Initialization
5936 this.$element
5937 .addClass( 'oo-ui-popupButtonWidget' );
5938 this.popup.$element
5939 .addClass( 'oo-ui-popupButtonWidget-popup' )
5940 .toggleClass( 'oo-ui-popupButtonWidget-framed-popup', this.isFramed() )
5941 .toggleClass( 'oo-ui-popupButtonWidget-frameless-popup', !this.isFramed() );
5942 this.$overlay.append( this.popup.$element );
5943 };
5944
5945 /* Setup */
5946
5947 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
5948 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.mixin.PopupElement );
5949
5950 /* Methods */
5951
5952 /**
5953 * Handle the button action being triggered.
5954 *
5955 * @private
5956 */
5957 OO.ui.PopupButtonWidget.prototype.onAction = function () {
5958 this.popup.toggle();
5959 };
5960
5961 /**
5962 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
5963 *
5964 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
5965 *
5966 * @private
5967 * @abstract
5968 * @class
5969 * @mixins OO.ui.mixin.GroupElement
5970 *
5971 * @constructor
5972 * @param {Object} [config] Configuration options
5973 */
5974 OO.ui.mixin.GroupWidget = function OoUiMixinGroupWidget( config ) {
5975 // Mixin constructors
5976 OO.ui.mixin.GroupElement.call( this, config );
5977 };
5978
5979 /* Setup */
5980
5981 OO.mixinClass( OO.ui.mixin.GroupWidget, OO.ui.mixin.GroupElement );
5982
5983 /* Methods */
5984
5985 /**
5986 * Set the disabled state of the widget.
5987 *
5988 * This will also update the disabled state of child widgets.
5989 *
5990 * @param {boolean} disabled Disable widget
5991 * @chainable
5992 */
5993 OO.ui.mixin.GroupWidget.prototype.setDisabled = function ( disabled ) {
5994 var i, len;
5995
5996 // Parent method
5997 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
5998 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
5999
6000 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
6001 if ( this.items ) {
6002 for ( i = 0, len = this.items.length; i < len; i++ ) {
6003 this.items[ i ].updateDisabled();
6004 }
6005 }
6006
6007 return this;
6008 };
6009
6010 /**
6011 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
6012 *
6013 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
6014 * allows bidirectional communication.
6015 *
6016 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
6017 *
6018 * @private
6019 * @abstract
6020 * @class
6021 *
6022 * @constructor
6023 */
6024 OO.ui.mixin.ItemWidget = function OoUiMixinItemWidget() {
6025 //
6026 };
6027
6028 /* Methods */
6029
6030 /**
6031 * Check if widget is disabled.
6032 *
6033 * Checks parent if present, making disabled state inheritable.
6034 *
6035 * @return {boolean} Widget is disabled
6036 */
6037 OO.ui.mixin.ItemWidget.prototype.isDisabled = function () {
6038 return this.disabled ||
6039 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
6040 };
6041
6042 /**
6043 * Set group element is in.
6044 *
6045 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
6046 * @chainable
6047 */
6048 OO.ui.mixin.ItemWidget.prototype.setElementGroup = function ( group ) {
6049 // Parent method
6050 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
6051 OO.ui.Element.prototype.setElementGroup.call( this, group );
6052
6053 // Initialize item disabled states
6054 this.updateDisabled();
6055
6056 return this;
6057 };
6058
6059 /**
6060 * OptionWidgets are special elements that can be selected and configured with data. The
6061 * data is often unique for each option, but it does not have to be. OptionWidgets are used
6062 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
6063 * and examples, please see the [OOUI documentation on MediaWiki][1].
6064 *
6065 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6066 *
6067 * @class
6068 * @extends OO.ui.Widget
6069 * @mixins OO.ui.mixin.ItemWidget
6070 * @mixins OO.ui.mixin.LabelElement
6071 * @mixins OO.ui.mixin.FlaggedElement
6072 * @mixins OO.ui.mixin.AccessKeyedElement
6073 *
6074 * @constructor
6075 * @param {Object} [config] Configuration options
6076 */
6077 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
6078 // Configuration initialization
6079 config = config || {};
6080
6081 // Parent constructor
6082 OO.ui.OptionWidget.parent.call( this, config );
6083
6084 // Mixin constructors
6085 OO.ui.mixin.ItemWidget.call( this );
6086 OO.ui.mixin.LabelElement.call( this, config );
6087 OO.ui.mixin.FlaggedElement.call( this, config );
6088 OO.ui.mixin.AccessKeyedElement.call( this, config );
6089
6090 // Properties
6091 this.selected = false;
6092 this.highlighted = false;
6093 this.pressed = false;
6094
6095 // Initialization
6096 this.$element
6097 .data( 'oo-ui-optionWidget', this )
6098 // Allow programmatic focussing (and by accesskey), but not tabbing
6099 .attr( 'tabindex', '-1' )
6100 .attr( 'role', 'option' )
6101 .attr( 'aria-selected', 'false' )
6102 .addClass( 'oo-ui-optionWidget' )
6103 .append( this.$label );
6104 };
6105
6106 /* Setup */
6107
6108 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
6109 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.ItemWidget );
6110 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.LabelElement );
6111 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.FlaggedElement );
6112 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.AccessKeyedElement );
6113
6114 /* Static Properties */
6115
6116 /**
6117 * Whether this option can be selected. See #setSelected.
6118 *
6119 * @static
6120 * @inheritable
6121 * @property {boolean}
6122 */
6123 OO.ui.OptionWidget.static.selectable = true;
6124
6125 /**
6126 * Whether this option can be highlighted. See #setHighlighted.
6127 *
6128 * @static
6129 * @inheritable
6130 * @property {boolean}
6131 */
6132 OO.ui.OptionWidget.static.highlightable = true;
6133
6134 /**
6135 * Whether this option can be pressed. See #setPressed.
6136 *
6137 * @static
6138 * @inheritable
6139 * @property {boolean}
6140 */
6141 OO.ui.OptionWidget.static.pressable = true;
6142
6143 /**
6144 * Whether this option will be scrolled into view when it is selected.
6145 *
6146 * @static
6147 * @inheritable
6148 * @property {boolean}
6149 */
6150 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
6151
6152 /* Methods */
6153
6154 /**
6155 * Check if the option can be selected.
6156 *
6157 * @return {boolean} Item is selectable
6158 */
6159 OO.ui.OptionWidget.prototype.isSelectable = function () {
6160 return this.constructor.static.selectable && !this.disabled && this.isVisible();
6161 };
6162
6163 /**
6164 * Check if the option can be highlighted. A highlight indicates that the option
6165 * may be selected when a user presses enter or clicks. Disabled items cannot
6166 * be highlighted.
6167 *
6168 * @return {boolean} Item is highlightable
6169 */
6170 OO.ui.OptionWidget.prototype.isHighlightable = function () {
6171 return this.constructor.static.highlightable && !this.disabled && this.isVisible();
6172 };
6173
6174 /**
6175 * Check if the option can be pressed. The pressed state occurs when a user mouses
6176 * down on an item, but has not yet let go of the mouse.
6177 *
6178 * @return {boolean} Item is pressable
6179 */
6180 OO.ui.OptionWidget.prototype.isPressable = function () {
6181 return this.constructor.static.pressable && !this.disabled && this.isVisible();
6182 };
6183
6184 /**
6185 * Check if the option is selected.
6186 *
6187 * @return {boolean} Item is selected
6188 */
6189 OO.ui.OptionWidget.prototype.isSelected = function () {
6190 return this.selected;
6191 };
6192
6193 /**
6194 * Check if the option is highlighted. A highlight indicates that the
6195 * item may be selected when a user presses enter or clicks.
6196 *
6197 * @return {boolean} Item is highlighted
6198 */
6199 OO.ui.OptionWidget.prototype.isHighlighted = function () {
6200 return this.highlighted;
6201 };
6202
6203 /**
6204 * Check if the option is pressed. The pressed state occurs when a user mouses
6205 * down on an item, but has not yet let go of the mouse. The item may appear
6206 * selected, but it will not be selected until the user releases the mouse.
6207 *
6208 * @return {boolean} Item is pressed
6209 */
6210 OO.ui.OptionWidget.prototype.isPressed = function () {
6211 return this.pressed;
6212 };
6213
6214 /**
6215 * Set the option’s selected state. In general, all modifications to the selection
6216 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
6217 * method instead of this method.
6218 *
6219 * @param {boolean} [state=false] Select option
6220 * @chainable
6221 */
6222 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
6223 if ( this.constructor.static.selectable ) {
6224 this.selected = !!state;
6225 this.$element
6226 .toggleClass( 'oo-ui-optionWidget-selected', state )
6227 .attr( 'aria-selected', state.toString() );
6228 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
6229 this.scrollElementIntoView();
6230 }
6231 this.updateThemeClasses();
6232 }
6233 return this;
6234 };
6235
6236 /**
6237 * Set the option’s highlighted state. In general, all programmatic
6238 * modifications to the highlight should be handled by the
6239 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
6240 * method instead of this method.
6241 *
6242 * @param {boolean} [state=false] Highlight option
6243 * @chainable
6244 */
6245 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
6246 if ( this.constructor.static.highlightable ) {
6247 this.highlighted = !!state;
6248 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
6249 this.updateThemeClasses();
6250 }
6251 return this;
6252 };
6253
6254 /**
6255 * Set the option’s pressed state. In general, all
6256 * programmatic modifications to the pressed state should be handled by the
6257 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
6258 * method instead of this method.
6259 *
6260 * @param {boolean} [state=false] Press option
6261 * @chainable
6262 */
6263 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
6264 if ( this.constructor.static.pressable ) {
6265 this.pressed = !!state;
6266 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
6267 this.updateThemeClasses();
6268 }
6269 return this;
6270 };
6271
6272 /**
6273 * Get text to match search strings against.
6274 *
6275 * The default implementation returns the label text, but subclasses
6276 * can override this to provide more complex behavior.
6277 *
6278 * @return {string|boolean} String to match search string against
6279 */
6280 OO.ui.OptionWidget.prototype.getMatchText = function () {
6281 var label = this.getLabel();
6282 return typeof label === 'string' ? label : this.$label.text();
6283 };
6284
6285 /**
6286 * A SelectWidget is of a generic selection of options. The OOUI library contains several types of
6287 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
6288 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
6289 * menu selects}.
6290 *
6291 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
6292 * information, please see the [OOUI documentation on MediaWiki][1].
6293 *
6294 * @example
6295 * // Example of a select widget with three options
6296 * var select = new OO.ui.SelectWidget( {
6297 * items: [
6298 * new OO.ui.OptionWidget( {
6299 * data: 'a',
6300 * label: 'Option One',
6301 * } ),
6302 * new OO.ui.OptionWidget( {
6303 * data: 'b',
6304 * label: 'Option Two',
6305 * } ),
6306 * new OO.ui.OptionWidget( {
6307 * data: 'c',
6308 * label: 'Option Three',
6309 * } )
6310 * ]
6311 * } );
6312 * $( 'body' ).append( select.$element );
6313 *
6314 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6315 *
6316 * @abstract
6317 * @class
6318 * @extends OO.ui.Widget
6319 * @mixins OO.ui.mixin.GroupWidget
6320 *
6321 * @constructor
6322 * @param {Object} [config] Configuration options
6323 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
6324 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
6325 * the [OOUI documentation on MediaWiki] [2] for examples.
6326 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6327 */
6328 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
6329 // Configuration initialization
6330 config = config || {};
6331
6332 // Parent constructor
6333 OO.ui.SelectWidget.parent.call( this, config );
6334
6335 // Mixin constructors
6336 OO.ui.mixin.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
6337
6338 // Properties
6339 this.pressed = false;
6340 this.selecting = null;
6341 this.onDocumentMouseUpHandler = this.onDocumentMouseUp.bind( this );
6342 this.onDocumentMouseMoveHandler = this.onDocumentMouseMove.bind( this );
6343 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
6344 this.onDocumentKeyPressHandler = this.onDocumentKeyPress.bind( this );
6345 this.keyPressBuffer = '';
6346 this.keyPressBufferTimer = null;
6347 this.blockMouseOverEvents = 0;
6348
6349 // Events
6350 this.connect( this, {
6351 toggle: 'onToggle'
6352 } );
6353 this.$element.on( {
6354 focusin: this.onFocus.bind( this ),
6355 mousedown: this.onMouseDown.bind( this ),
6356 mouseover: this.onMouseOver.bind( this ),
6357 mouseleave: this.onMouseLeave.bind( this )
6358 } );
6359
6360 // Initialization
6361 this.$element
6362 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
6363 .attr( 'role', 'listbox' );
6364 this.setFocusOwner( this.$element );
6365 if ( Array.isArray( config.items ) ) {
6366 this.addItems( config.items );
6367 }
6368 };
6369
6370 /* Setup */
6371
6372 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
6373 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupWidget );
6374
6375 /* Events */
6376
6377 /**
6378 * @event highlight
6379 *
6380 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
6381 *
6382 * @param {OO.ui.OptionWidget|null} item Highlighted item
6383 */
6384
6385 /**
6386 * @event press
6387 *
6388 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
6389 * pressed state of an option.
6390 *
6391 * @param {OO.ui.OptionWidget|null} item Pressed item
6392 */
6393
6394 /**
6395 * @event select
6396 *
6397 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
6398 *
6399 * @param {OO.ui.OptionWidget|null} item Selected item
6400 */
6401
6402 /**
6403 * @event choose
6404 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
6405 * @param {OO.ui.OptionWidget} item Chosen item
6406 */
6407
6408 /**
6409 * @event add
6410 *
6411 * An `add` event is emitted when options are added to the select with the #addItems method.
6412 *
6413 * @param {OO.ui.OptionWidget[]} items Added items
6414 * @param {number} index Index of insertion point
6415 */
6416
6417 /**
6418 * @event remove
6419 *
6420 * A `remove` event is emitted when options are removed from the select with the #clearItems
6421 * or #removeItems methods.
6422 *
6423 * @param {OO.ui.OptionWidget[]} items Removed items
6424 */
6425
6426 /* Methods */
6427
6428 /**
6429 * Handle focus events
6430 *
6431 * @private
6432 * @param {jQuery.Event} event
6433 */
6434 OO.ui.SelectWidget.prototype.onFocus = function ( event ) {
6435 var item;
6436 if ( event.target === this.$element[ 0 ] ) {
6437 // This widget was focussed, e.g. by the user tabbing to it.
6438 // The styles for focus state depend on one of the items being selected.
6439 if ( !this.findSelectedItem() ) {
6440 item = this.findFirstSelectableItem();
6441 }
6442 } else {
6443 if ( event.target.tabIndex === -1 ) {
6444 // One of the options got focussed (and the event bubbled up here).
6445 // They can't be tabbed to, but they can be activated using accesskeys.
6446 // OptionWidgets and focusable UI elements inside them have tabindex="-1" set.
6447 item = this.findTargetItem( event );
6448 } else {
6449 // There is something actually user-focusable in one of the labels of the options, and the
6450 // user focussed it (e.g. by tabbing to it). Do nothing (especially, don't change the focus).
6451 return;
6452 }
6453 }
6454
6455 if ( item ) {
6456 if ( item.constructor.static.highlightable ) {
6457 this.highlightItem( item );
6458 } else {
6459 this.selectItem( item );
6460 }
6461 }
6462
6463 if ( event.target !== this.$element[ 0 ] ) {
6464 this.$focusOwner.focus();
6465 }
6466 };
6467
6468 /**
6469 * Handle mouse down events.
6470 *
6471 * @private
6472 * @param {jQuery.Event} e Mouse down event
6473 */
6474 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
6475 var item;
6476
6477 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
6478 this.togglePressed( true );
6479 item = this.findTargetItem( e );
6480 if ( item && item.isSelectable() ) {
6481 this.pressItem( item );
6482 this.selecting = item;
6483 this.getElementDocument().addEventListener( 'mouseup', this.onDocumentMouseUpHandler, true );
6484 this.getElementDocument().addEventListener( 'mousemove', this.onDocumentMouseMoveHandler, true );
6485 }
6486 }
6487 return false;
6488 };
6489
6490 /**
6491 * Handle document mouse up events.
6492 *
6493 * @private
6494 * @param {MouseEvent} e Mouse up event
6495 */
6496 OO.ui.SelectWidget.prototype.onDocumentMouseUp = function ( e ) {
6497 var item;
6498
6499 this.togglePressed( false );
6500 if ( !this.selecting ) {
6501 item = this.findTargetItem( e );
6502 if ( item && item.isSelectable() ) {
6503 this.selecting = item;
6504 }
6505 }
6506 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT && this.selecting ) {
6507 this.pressItem( null );
6508 this.chooseItem( this.selecting );
6509 this.selecting = null;
6510 }
6511
6512 this.getElementDocument().removeEventListener( 'mouseup', this.onDocumentMouseUpHandler, true );
6513 this.getElementDocument().removeEventListener( 'mousemove', this.onDocumentMouseMoveHandler, true );
6514
6515 return false;
6516 };
6517
6518 // Deprecated alias since 0.28.3
6519 OO.ui.SelectWidget.prototype.onMouseUp = function () {
6520 OO.ui.warnDeprecation( 'onMouseUp is deprecated, use onDocumentMouseUp instead' );
6521 this.onDocumentMouseUp.apply( this, arguments );
6522 };
6523
6524 /**
6525 * Handle document mouse move events.
6526 *
6527 * @private
6528 * @param {MouseEvent} e Mouse move event
6529 */
6530 OO.ui.SelectWidget.prototype.onDocumentMouseMove = function ( e ) {
6531 var item;
6532
6533 if ( !this.isDisabled() && this.pressed ) {
6534 item = this.findTargetItem( e );
6535 if ( item && item !== this.selecting && item.isSelectable() ) {
6536 this.pressItem( item );
6537 this.selecting = item;
6538 }
6539 }
6540 };
6541
6542 // Deprecated alias since 0.28.3
6543 OO.ui.SelectWidget.prototype.onMouseMove = function () {
6544 OO.ui.warnDeprecation( 'onMouseMove is deprecated, use onDocumentMouseMove instead' );
6545 this.onDocumentMouseMove.apply( this, arguments );
6546 };
6547
6548 /**
6549 * Handle mouse over events.
6550 *
6551 * @private
6552 * @param {jQuery.Event} e Mouse over event
6553 */
6554 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
6555 var item;
6556 if ( this.blockMouseOverEvents ) {
6557 return;
6558 }
6559 if ( !this.isDisabled() ) {
6560 item = this.findTargetItem( e );
6561 this.highlightItem( item && item.isHighlightable() ? item : null );
6562 }
6563 return false;
6564 };
6565
6566 /**
6567 * Handle mouse leave events.
6568 *
6569 * @private
6570 * @param {jQuery.Event} e Mouse over event
6571 */
6572 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
6573 if ( !this.isDisabled() ) {
6574 this.highlightItem( null );
6575 }
6576 return false;
6577 };
6578
6579 /**
6580 * Handle document key down events.
6581 *
6582 * @protected
6583 * @param {KeyboardEvent} e Key down event
6584 */
6585 OO.ui.SelectWidget.prototype.onDocumentKeyDown = function ( e ) {
6586 var nextItem,
6587 handled = false,
6588 currentItem = this.findHighlightedItem() || this.findSelectedItem();
6589
6590 if ( !this.isDisabled() && this.isVisible() ) {
6591 switch ( e.keyCode ) {
6592 case OO.ui.Keys.ENTER:
6593 if ( currentItem && currentItem.constructor.static.highlightable ) {
6594 // Was only highlighted, now let's select it. No-op if already selected.
6595 this.chooseItem( currentItem );
6596 handled = true;
6597 }
6598 break;
6599 case OO.ui.Keys.UP:
6600 case OO.ui.Keys.LEFT:
6601 this.clearKeyPressBuffer();
6602 nextItem = this.findRelativeSelectableItem( currentItem, -1 );
6603 handled = true;
6604 break;
6605 case OO.ui.Keys.DOWN:
6606 case OO.ui.Keys.RIGHT:
6607 this.clearKeyPressBuffer();
6608 nextItem = this.findRelativeSelectableItem( currentItem, 1 );
6609 handled = true;
6610 break;
6611 case OO.ui.Keys.ESCAPE:
6612 case OO.ui.Keys.TAB:
6613 if ( currentItem && currentItem.constructor.static.highlightable ) {
6614 currentItem.setHighlighted( false );
6615 }
6616 this.unbindDocumentKeyDownListener();
6617 this.unbindDocumentKeyPressListener();
6618 // Don't prevent tabbing away / defocusing
6619 handled = false;
6620 break;
6621 }
6622
6623 if ( nextItem ) {
6624 if ( nextItem.constructor.static.highlightable ) {
6625 this.highlightItem( nextItem );
6626 } else {
6627 this.chooseItem( nextItem );
6628 }
6629 this.scrollItemIntoView( nextItem );
6630 }
6631
6632 if ( handled ) {
6633 e.preventDefault();
6634 e.stopPropagation();
6635 }
6636 }
6637 };
6638
6639 // Deprecated alias since 0.28.3
6640 OO.ui.SelectWidget.prototype.onKeyDown = function () {
6641 OO.ui.warnDeprecation( 'onKeyDown is deprecated, use onDocumentKeyDown instead' );
6642 this.onDocumentKeyDown.apply( this, arguments );
6643 };
6644
6645 /**
6646 * Bind document key down listener.
6647 *
6648 * @protected
6649 */
6650 OO.ui.SelectWidget.prototype.bindDocumentKeyDownListener = function () {
6651 this.getElementDocument().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
6652 };
6653
6654 // Deprecated alias since 0.28.3
6655 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
6656 OO.ui.warnDeprecation( 'bindKeyDownListener is deprecated, use bindDocumentKeyDownListener instead' );
6657 this.bindDocumentKeyDownListener.apply( this, arguments );
6658 };
6659
6660 /**
6661 * Unbind document key down listener.
6662 *
6663 * @protected
6664 */
6665 OO.ui.SelectWidget.prototype.unbindDocumentKeyDownListener = function () {
6666 this.getElementDocument().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
6667 };
6668
6669 // Deprecated alias since 0.28.3
6670 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
6671 OO.ui.warnDeprecation( 'unbindKeyDownListener is deprecated, use unbindDocumentKeyDownListener instead' );
6672 this.unbindDocumentKeyDownListener.apply( this, arguments );
6673 };
6674
6675 /**
6676 * Scroll item into view, preventing spurious mouse highlight actions from happening.
6677 *
6678 * @param {OO.ui.OptionWidget} item Item to scroll into view
6679 */
6680 OO.ui.SelectWidget.prototype.scrollItemIntoView = function ( item ) {
6681 var widget = this;
6682 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling
6683 // and around 100-150 ms after it is finished.
6684 this.blockMouseOverEvents++;
6685 item.scrollElementIntoView().done( function () {
6686 setTimeout( function () {
6687 widget.blockMouseOverEvents--;
6688 }, 200 );
6689 } );
6690 };
6691
6692 /**
6693 * Clear the key-press buffer
6694 *
6695 * @protected
6696 */
6697 OO.ui.SelectWidget.prototype.clearKeyPressBuffer = function () {
6698 if ( this.keyPressBufferTimer ) {
6699 clearTimeout( this.keyPressBufferTimer );
6700 this.keyPressBufferTimer = null;
6701 }
6702 this.keyPressBuffer = '';
6703 };
6704
6705 /**
6706 * Handle key press events.
6707 *
6708 * @protected
6709 * @param {KeyboardEvent} e Key press event
6710 */
6711 OO.ui.SelectWidget.prototype.onDocumentKeyPress = function ( e ) {
6712 var c, filter, item;
6713
6714 if ( !e.charCode ) {
6715 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.keyPressBuffer !== '' ) {
6716 this.keyPressBuffer = this.keyPressBuffer.substr( 0, this.keyPressBuffer.length - 1 );
6717 return false;
6718 }
6719 return;
6720 }
6721 if ( String.fromCodePoint ) {
6722 c = String.fromCodePoint( e.charCode );
6723 } else {
6724 c = String.fromCharCode( e.charCode );
6725 }
6726
6727 if ( this.keyPressBufferTimer ) {
6728 clearTimeout( this.keyPressBufferTimer );
6729 }
6730 this.keyPressBufferTimer = setTimeout( this.clearKeyPressBuffer.bind( this ), 1500 );
6731
6732 item = this.findHighlightedItem() || this.findSelectedItem();
6733
6734 if ( this.keyPressBuffer === c ) {
6735 // Common (if weird) special case: typing "xxxx" will cycle through all
6736 // the items beginning with "x".
6737 if ( item ) {
6738 item = this.findRelativeSelectableItem( item, 1 );
6739 }
6740 } else {
6741 this.keyPressBuffer += c;
6742 }
6743
6744 filter = this.getItemMatcher( this.keyPressBuffer, false );
6745 if ( !item || !filter( item ) ) {
6746 item = this.findRelativeSelectableItem( item, 1, filter );
6747 }
6748 if ( item ) {
6749 if ( this.isVisible() && item.constructor.static.highlightable ) {
6750 this.highlightItem( item );
6751 } else {
6752 this.chooseItem( item );
6753 }
6754 this.scrollItemIntoView( item );
6755 }
6756
6757 e.preventDefault();
6758 e.stopPropagation();
6759 };
6760
6761 // Deprecated alias since 0.28.3
6762 OO.ui.SelectWidget.prototype.onKeyPress = function () {
6763 OO.ui.warnDeprecation( 'onKeyPress is deprecated, use onDocumentKeyPress instead' );
6764 this.onDocumentKeyPress.apply( this, arguments );
6765 };
6766
6767 /**
6768 * Get a matcher for the specific string
6769 *
6770 * @protected
6771 * @param {string} s String to match against items
6772 * @param {boolean} [exact=false] Only accept exact matches
6773 * @return {Function} function ( OO.ui.OptionWidget ) => boolean
6774 */
6775 OO.ui.SelectWidget.prototype.getItemMatcher = function ( s, exact ) {
6776 var re;
6777
6778 if ( s.normalize ) {
6779 s = s.normalize();
6780 }
6781 s = exact ? s.trim() : s.replace( /^\s+/, '' );
6782 re = '^\\s*' + s.replace( /([\\{}()|.?*+\-^$[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
6783 if ( exact ) {
6784 re += '\\s*$';
6785 }
6786 re = new RegExp( re, 'i' );
6787 return function ( item ) {
6788 var matchText = item.getMatchText();
6789 if ( matchText.normalize ) {
6790 matchText = matchText.normalize();
6791 }
6792 return re.test( matchText );
6793 };
6794 };
6795
6796 /**
6797 * Bind document key press listener.
6798 *
6799 * @protected
6800 */
6801 OO.ui.SelectWidget.prototype.bindDocumentKeyPressListener = function () {
6802 this.getElementDocument().addEventListener( 'keypress', this.onDocumentKeyPressHandler, true );
6803 };
6804
6805 // Deprecated alias since 0.28.3
6806 OO.ui.SelectWidget.prototype.bindKeyPressListener = function () {
6807 OO.ui.warnDeprecation( 'bindKeyPressListener is deprecated, use bindDocumentKeyPressListener instead' );
6808 this.bindDocumentKeyPressListener.apply( this, arguments );
6809 };
6810
6811 /**
6812 * Unbind document key down listener.
6813 *
6814 * If you override this, be sure to call this.clearKeyPressBuffer() from your
6815 * implementation.
6816 *
6817 * @protected
6818 */
6819 OO.ui.SelectWidget.prototype.unbindDocumentKeyPressListener = function () {
6820 this.getElementDocument().removeEventListener( 'keypress', this.onDocumentKeyPressHandler, true );
6821 this.clearKeyPressBuffer();
6822 };
6823
6824 // Deprecated alias since 0.28.3
6825 OO.ui.SelectWidget.prototype.unbindKeyPressListener = function () {
6826 OO.ui.warnDeprecation( 'unbindKeyPressListener is deprecated, use unbindDocumentKeyPressListener instead' );
6827 this.unbindDocumentKeyPressListener.apply( this, arguments );
6828 };
6829
6830 /**
6831 * Visibility change handler
6832 *
6833 * @protected
6834 * @param {boolean} visible
6835 */
6836 OO.ui.SelectWidget.prototype.onToggle = function ( visible ) {
6837 if ( !visible ) {
6838 this.clearKeyPressBuffer();
6839 }
6840 };
6841
6842 /**
6843 * Get the closest item to a jQuery.Event.
6844 *
6845 * @private
6846 * @param {jQuery.Event} e
6847 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
6848 */
6849 OO.ui.SelectWidget.prototype.findTargetItem = function ( e ) {
6850 var $option = $( e.target ).closest( '.oo-ui-optionWidget' );
6851 if ( !$option.closest( '.oo-ui-selectWidget' ).is( this.$element ) ) {
6852 return null;
6853 }
6854 return $option.data( 'oo-ui-optionWidget' ) || null;
6855 };
6856
6857 /**
6858 * Find selected item.
6859 *
6860 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
6861 */
6862 OO.ui.SelectWidget.prototype.findSelectedItem = function () {
6863 var i, len;
6864
6865 for ( i = 0, len = this.items.length; i < len; i++ ) {
6866 if ( this.items[ i ].isSelected() ) {
6867 return this.items[ i ];
6868 }
6869 }
6870 return null;
6871 };
6872
6873 /**
6874 * Find highlighted item.
6875 *
6876 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
6877 */
6878 OO.ui.SelectWidget.prototype.findHighlightedItem = function () {
6879 var i, len;
6880
6881 for ( i = 0, len = this.items.length; i < len; i++ ) {
6882 if ( this.items[ i ].isHighlighted() ) {
6883 return this.items[ i ];
6884 }
6885 }
6886 return null;
6887 };
6888
6889 /**
6890 * Toggle pressed state.
6891 *
6892 * Press is a state that occurs when a user mouses down on an item, but
6893 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
6894 * until the user releases the mouse.
6895 *
6896 * @param {boolean} pressed An option is being pressed
6897 */
6898 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
6899 if ( pressed === undefined ) {
6900 pressed = !this.pressed;
6901 }
6902 if ( pressed !== this.pressed ) {
6903 this.$element
6904 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
6905 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
6906 this.pressed = pressed;
6907 }
6908 };
6909
6910 /**
6911 * Highlight an option. If the `item` param is omitted, no options will be highlighted
6912 * and any existing highlight will be removed. The highlight is mutually exclusive.
6913 *
6914 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
6915 * @fires highlight
6916 * @chainable
6917 */
6918 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
6919 var i, len, highlighted,
6920 changed = false;
6921
6922 for ( i = 0, len = this.items.length; i < len; i++ ) {
6923 highlighted = this.items[ i ] === item;
6924 if ( this.items[ i ].isHighlighted() !== highlighted ) {
6925 this.items[ i ].setHighlighted( highlighted );
6926 changed = true;
6927 }
6928 }
6929 if ( changed ) {
6930 if ( item ) {
6931 this.$focusOwner.attr( 'aria-activedescendant', item.getElementId() );
6932 } else {
6933 this.$focusOwner.removeAttr( 'aria-activedescendant' );
6934 }
6935 this.emit( 'highlight', item );
6936 }
6937
6938 return this;
6939 };
6940
6941 /**
6942 * Fetch an item by its label.
6943 *
6944 * @param {string} label Label of the item to select.
6945 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
6946 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
6947 */
6948 OO.ui.SelectWidget.prototype.getItemFromLabel = function ( label, prefix ) {
6949 var i, item, found,
6950 len = this.items.length,
6951 filter = this.getItemMatcher( label, true );
6952
6953 for ( i = 0; i < len; i++ ) {
6954 item = this.items[ i ];
6955 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
6956 return item;
6957 }
6958 }
6959
6960 if ( prefix ) {
6961 found = null;
6962 filter = this.getItemMatcher( label, false );
6963 for ( i = 0; i < len; i++ ) {
6964 item = this.items[ i ];
6965 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
6966 if ( found ) {
6967 return null;
6968 }
6969 found = item;
6970 }
6971 }
6972 if ( found ) {
6973 return found;
6974 }
6975 }
6976
6977 return null;
6978 };
6979
6980 /**
6981 * Programmatically select an option by its label. If the item does not exist,
6982 * all options will be deselected.
6983 *
6984 * @param {string} [label] Label of the item to select.
6985 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
6986 * @fires select
6987 * @chainable
6988 */
6989 OO.ui.SelectWidget.prototype.selectItemByLabel = function ( label, prefix ) {
6990 var itemFromLabel = this.getItemFromLabel( label, !!prefix );
6991 if ( label === undefined || !itemFromLabel ) {
6992 return this.selectItem();
6993 }
6994 return this.selectItem( itemFromLabel );
6995 };
6996
6997 /**
6998 * Programmatically select an option by its data. If the `data` parameter is omitted,
6999 * or if the item does not exist, all options will be deselected.
7000 *
7001 * @param {Object|string} [data] Value of the item to select, omit to deselect all
7002 * @fires select
7003 * @chainable
7004 */
7005 OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) {
7006 var itemFromData = this.findItemFromData( data );
7007 if ( data === undefined || !itemFromData ) {
7008 return this.selectItem();
7009 }
7010 return this.selectItem( itemFromData );
7011 };
7012
7013 /**
7014 * Programmatically select an option by its reference. If the `item` parameter is omitted,
7015 * all options will be deselected.
7016 *
7017 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
7018 * @fires select
7019 * @chainable
7020 */
7021 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
7022 var i, len, selected,
7023 changed = false;
7024
7025 for ( i = 0, len = this.items.length; i < len; i++ ) {
7026 selected = this.items[ i ] === item;
7027 if ( this.items[ i ].isSelected() !== selected ) {
7028 this.items[ i ].setSelected( selected );
7029 changed = true;
7030 }
7031 }
7032 if ( changed ) {
7033 if ( item && !item.constructor.static.highlightable ) {
7034 if ( item ) {
7035 this.$focusOwner.attr( 'aria-activedescendant', item.getElementId() );
7036 } else {
7037 this.$focusOwner.removeAttr( 'aria-activedescendant' );
7038 }
7039 }
7040 this.emit( 'select', item );
7041 }
7042
7043 return this;
7044 };
7045
7046 /**
7047 * Press an item.
7048 *
7049 * Press is a state that occurs when a user mouses down on an item, but has not
7050 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
7051 * releases the mouse.
7052 *
7053 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
7054 * @fires press
7055 * @chainable
7056 */
7057 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
7058 var i, len, pressed,
7059 changed = false;
7060
7061 for ( i = 0, len = this.items.length; i < len; i++ ) {
7062 pressed = this.items[ i ] === item;
7063 if ( this.items[ i ].isPressed() !== pressed ) {
7064 this.items[ i ].setPressed( pressed );
7065 changed = true;
7066 }
7067 }
7068 if ( changed ) {
7069 this.emit( 'press', item );
7070 }
7071
7072 return this;
7073 };
7074
7075 /**
7076 * Choose an item.
7077 *
7078 * Note that ‘choose’ should never be modified programmatically. A user can choose
7079 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
7080 * use the #selectItem method.
7081 *
7082 * This method is identical to #selectItem, but may vary in subclasses that take additional action
7083 * when users choose an item with the keyboard or mouse.
7084 *
7085 * @param {OO.ui.OptionWidget} item Item to choose
7086 * @fires choose
7087 * @chainable
7088 */
7089 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
7090 if ( item ) {
7091 this.selectItem( item );
7092 this.emit( 'choose', item );
7093 }
7094
7095 return this;
7096 };
7097
7098 /**
7099 * Find an option by its position relative to the specified item (or to the start of the option array,
7100 * if item is `null`). The direction in which to search through the option array is specified with a
7101 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
7102 * `null` if there are no options in the array.
7103 *
7104 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
7105 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
7106 * @param {Function} [filter] Only consider items for which this function returns
7107 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
7108 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
7109 */
7110 OO.ui.SelectWidget.prototype.findRelativeSelectableItem = function ( item, direction, filter ) {
7111 var currentIndex, nextIndex, i,
7112 increase = direction > 0 ? 1 : -1,
7113 len = this.items.length;
7114
7115 if ( item instanceof OO.ui.OptionWidget ) {
7116 currentIndex = this.items.indexOf( item );
7117 nextIndex = ( currentIndex + increase + len ) % len;
7118 } else {
7119 // If no item is selected and moving forward, start at the beginning.
7120 // If moving backward, start at the end.
7121 nextIndex = direction > 0 ? 0 : len - 1;
7122 }
7123
7124 for ( i = 0; i < len; i++ ) {
7125 item = this.items[ nextIndex ];
7126 if (
7127 item instanceof OO.ui.OptionWidget && item.isSelectable() &&
7128 ( !filter || filter( item ) )
7129 ) {
7130 return item;
7131 }
7132 nextIndex = ( nextIndex + increase + len ) % len;
7133 }
7134 return null;
7135 };
7136
7137 /**
7138 * Find the next selectable item or `null` if there are no selectable items.
7139 * Disabled options and menu-section markers and breaks are not selectable.
7140 *
7141 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
7142 */
7143 OO.ui.SelectWidget.prototype.findFirstSelectableItem = function () {
7144 return this.findRelativeSelectableItem( null, 1 );
7145 };
7146
7147 /**
7148 * Add an array of options to the select. Optionally, an index number can be used to
7149 * specify an insertion point.
7150 *
7151 * @param {OO.ui.OptionWidget[]} items Items to add
7152 * @param {number} [index] Index to insert items after
7153 * @fires add
7154 * @chainable
7155 */
7156 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
7157 // Mixin method
7158 OO.ui.mixin.GroupWidget.prototype.addItems.call( this, items, index );
7159
7160 // Always provide an index, even if it was omitted
7161 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
7162
7163 return this;
7164 };
7165
7166 /**
7167 * Remove the specified array of options from the select. Options will be detached
7168 * from the DOM, not removed, so they can be reused later. To remove all options from
7169 * the select, you may wish to use the #clearItems method instead.
7170 *
7171 * @param {OO.ui.OptionWidget[]} items Items to remove
7172 * @fires remove
7173 * @chainable
7174 */
7175 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
7176 var i, len, item;
7177
7178 // Deselect items being removed
7179 for ( i = 0, len = items.length; i < len; i++ ) {
7180 item = items[ i ];
7181 if ( item.isSelected() ) {
7182 this.selectItem( null );
7183 }
7184 }
7185
7186 // Mixin method
7187 OO.ui.mixin.GroupWidget.prototype.removeItems.call( this, items );
7188
7189 this.emit( 'remove', items );
7190
7191 return this;
7192 };
7193
7194 /**
7195 * Clear all options from the select. Options will be detached from the DOM, not removed,
7196 * so that they can be reused later. To remove a subset of options from the select, use
7197 * the #removeItems method.
7198 *
7199 * @fires remove
7200 * @chainable
7201 */
7202 OO.ui.SelectWidget.prototype.clearItems = function () {
7203 var items = this.items.slice();
7204
7205 // Mixin method
7206 OO.ui.mixin.GroupWidget.prototype.clearItems.call( this );
7207
7208 // Clear selection
7209 this.selectItem( null );
7210
7211 this.emit( 'remove', items );
7212
7213 return this;
7214 };
7215
7216 /**
7217 * Set the DOM element which has focus while the user is interacting with this SelectWidget.
7218 *
7219 * Currently this is just used to set `aria-activedescendant` on it.
7220 *
7221 * @protected
7222 * @param {jQuery} $focusOwner
7223 */
7224 OO.ui.SelectWidget.prototype.setFocusOwner = function ( $focusOwner ) {
7225 this.$focusOwner = $focusOwner;
7226 };
7227
7228 /**
7229 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
7230 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
7231 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
7232 * options. For more information about options and selects, please see the
7233 * [OOUI documentation on MediaWiki][1].
7234 *
7235 * @example
7236 * // Decorated options in a select widget
7237 * var select = new OO.ui.SelectWidget( {
7238 * items: [
7239 * new OO.ui.DecoratedOptionWidget( {
7240 * data: 'a',
7241 * label: 'Option with icon',
7242 * icon: 'help'
7243 * } ),
7244 * new OO.ui.DecoratedOptionWidget( {
7245 * data: 'b',
7246 * label: 'Option with indicator',
7247 * indicator: 'next'
7248 * } )
7249 * ]
7250 * } );
7251 * $( 'body' ).append( select.$element );
7252 *
7253 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7254 *
7255 * @class
7256 * @extends OO.ui.OptionWidget
7257 * @mixins OO.ui.mixin.IconElement
7258 * @mixins OO.ui.mixin.IndicatorElement
7259 *
7260 * @constructor
7261 * @param {Object} [config] Configuration options
7262 */
7263 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
7264 // Parent constructor
7265 OO.ui.DecoratedOptionWidget.parent.call( this, config );
7266
7267 // Mixin constructors
7268 OO.ui.mixin.IconElement.call( this, config );
7269 OO.ui.mixin.IndicatorElement.call( this, config );
7270
7271 // Initialization
7272 this.$element
7273 .addClass( 'oo-ui-decoratedOptionWidget' )
7274 .prepend( this.$icon )
7275 .append( this.$indicator );
7276 };
7277
7278 /* Setup */
7279
7280 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
7281 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IconElement );
7282 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IndicatorElement );
7283
7284 /**
7285 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
7286 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
7287 * the [OOUI documentation on MediaWiki] [1] for more information.
7288 *
7289 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
7290 *
7291 * @class
7292 * @extends OO.ui.DecoratedOptionWidget
7293 *
7294 * @constructor
7295 * @param {Object} [config] Configuration options
7296 */
7297 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
7298 // Parent constructor
7299 OO.ui.MenuOptionWidget.parent.call( this, config );
7300
7301 // Properties
7302 this.checkIcon = new OO.ui.IconWidget( {
7303 icon: 'check',
7304 classes: [ 'oo-ui-menuOptionWidget-checkIcon' ]
7305 } );
7306
7307 // Initialization
7308 this.$element
7309 .prepend( this.checkIcon.$element )
7310 .addClass( 'oo-ui-menuOptionWidget' );
7311 };
7312
7313 /* Setup */
7314
7315 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
7316
7317 /* Static Properties */
7318
7319 /**
7320 * @static
7321 * @inheritdoc
7322 */
7323 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
7324
7325 /**
7326 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
7327 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
7328 *
7329 * @example
7330 * var myDropdown = new OO.ui.DropdownWidget( {
7331 * menu: {
7332 * items: [
7333 * new OO.ui.MenuSectionOptionWidget( {
7334 * label: 'Dogs'
7335 * } ),
7336 * new OO.ui.MenuOptionWidget( {
7337 * data: 'corgi',
7338 * label: 'Welsh Corgi'
7339 * } ),
7340 * new OO.ui.MenuOptionWidget( {
7341 * data: 'poodle',
7342 * label: 'Standard Poodle'
7343 * } ),
7344 * new OO.ui.MenuSectionOptionWidget( {
7345 * label: 'Cats'
7346 * } ),
7347 * new OO.ui.MenuOptionWidget( {
7348 * data: 'lion',
7349 * label: 'Lion'
7350 * } )
7351 * ]
7352 * }
7353 * } );
7354 * $( 'body' ).append( myDropdown.$element );
7355 *
7356 * @class
7357 * @extends OO.ui.DecoratedOptionWidget
7358 *
7359 * @constructor
7360 * @param {Object} [config] Configuration options
7361 */
7362 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
7363 // Parent constructor
7364 OO.ui.MenuSectionOptionWidget.parent.call( this, config );
7365
7366 // Initialization
7367 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' )
7368 .removeAttr( 'role aria-selected' );
7369 };
7370
7371 /* Setup */
7372
7373 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
7374
7375 /* Static Properties */
7376
7377 /**
7378 * @static
7379 * @inheritdoc
7380 */
7381 OO.ui.MenuSectionOptionWidget.static.selectable = false;
7382
7383 /**
7384 * @static
7385 * @inheritdoc
7386 */
7387 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
7388
7389 /**
7390 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
7391 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
7392 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
7393 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
7394 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
7395 * and customized to be opened, closed, and displayed as needed.
7396 *
7397 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
7398 * mouse outside the menu.
7399 *
7400 * Menus also have support for keyboard interaction:
7401 *
7402 * - Enter/Return key: choose and select a menu option
7403 * - Up-arrow key: highlight the previous menu option
7404 * - Down-arrow key: highlight the next menu option
7405 * - Esc key: hide the menu
7406 *
7407 * Unlike most widgets, MenuSelectWidget is initially hidden and must be shown by calling #toggle.
7408 *
7409 * Please see the [OOUI documentation on MediaWiki][1] for more information.
7410 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7411 *
7412 * @class
7413 * @extends OO.ui.SelectWidget
7414 * @mixins OO.ui.mixin.ClippableElement
7415 * @mixins OO.ui.mixin.FloatableElement
7416 *
7417 * @constructor
7418 * @param {Object} [config] Configuration options
7419 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
7420 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
7421 * and {@link OO.ui.mixin.LookupElement LookupElement}
7422 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
7423 * the text the user types. This config is used by {@link OO.ui.TagMultiselectWidget TagMultiselectWidget}
7424 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
7425 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
7426 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
7427 * that button, unless the button (or its parent widget) is passed in here.
7428 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
7429 * @cfg {jQuery} [$autoCloseIgnore] If these elements are clicked, don't auto-hide the menu.
7430 * @cfg {boolean} [hideOnChoose=true] Hide the menu when the user chooses an option.
7431 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
7432 * @cfg {boolean} [highlightOnFilter] Highlight the first result when filtering
7433 * @cfg {number} [width] Width of the menu
7434 */
7435 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
7436 // Configuration initialization
7437 config = config || {};
7438
7439 // Parent constructor
7440 OO.ui.MenuSelectWidget.parent.call( this, config );
7441
7442 // Mixin constructors
7443 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
7444 OO.ui.mixin.FloatableElement.call( this, config );
7445
7446 // Initial vertical positions other than 'center' will result in
7447 // the menu being flipped if there is not enough space in the container.
7448 // Store the original position so we know what to reset to.
7449 this.originalVerticalPosition = this.verticalPosition;
7450
7451 // Properties
7452 this.autoHide = config.autoHide === undefined || !!config.autoHide;
7453 this.hideOnChoose = config.hideOnChoose === undefined || !!config.hideOnChoose;
7454 this.filterFromInput = !!config.filterFromInput;
7455 this.$input = config.$input ? config.$input : config.input ? config.input.$input : null;
7456 this.$widget = config.widget ? config.widget.$element : null;
7457 this.$autoCloseIgnore = config.$autoCloseIgnore || $( [] );
7458 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
7459 this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 );
7460 this.highlightOnFilter = !!config.highlightOnFilter;
7461 this.width = config.width;
7462
7463 // Initialization
7464 this.$element.addClass( 'oo-ui-menuSelectWidget' );
7465 if ( config.widget ) {
7466 this.setFocusOwner( config.widget.$tabIndexed );
7467 }
7468
7469 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
7470 // that reference properties not initialized at that time of parent class construction
7471 // TODO: Find a better way to handle post-constructor setup
7472 this.visible = false;
7473 this.$element.addClass( 'oo-ui-element-hidden' );
7474 };
7475
7476 /* Setup */
7477
7478 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
7479 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement );
7480 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.FloatableElement );
7481
7482 /* Events */
7483
7484 /**
7485 * @event ready
7486 *
7487 * The menu is ready: it is visible and has been positioned and clipped.
7488 */
7489
7490 /* Static properties */
7491
7492 /**
7493 * Positions to flip to if there isn't room in the container for the
7494 * menu in a specific direction.
7495 *
7496 * @property {Object.<string,string>}
7497 */
7498 OO.ui.MenuSelectWidget.static.flippedPositions = {
7499 below: 'above',
7500 above: 'below',
7501 top: 'bottom',
7502 bottom: 'top'
7503 };
7504
7505 /* Methods */
7506
7507 /**
7508 * Handles document mouse down events.
7509 *
7510 * @protected
7511 * @param {MouseEvent} e Mouse down event
7512 */
7513 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
7514 if (
7515 this.isVisible() &&
7516 !OO.ui.contains(
7517 this.$element.add( this.$widget ).add( this.$autoCloseIgnore ).get(),
7518 e.target,
7519 true
7520 )
7521 ) {
7522 this.toggle( false );
7523 }
7524 };
7525
7526 /**
7527 * @inheritdoc
7528 */
7529 OO.ui.MenuSelectWidget.prototype.onDocumentKeyDown = function ( e ) {
7530 var currentItem = this.findHighlightedItem() || this.findSelectedItem();
7531
7532 if ( !this.isDisabled() && this.isVisible() ) {
7533 switch ( e.keyCode ) {
7534 case OO.ui.Keys.LEFT:
7535 case OO.ui.Keys.RIGHT:
7536 // Do nothing if a text field is associated, arrow keys will be handled natively
7537 if ( !this.$input ) {
7538 OO.ui.MenuSelectWidget.parent.prototype.onDocumentKeyDown.call( this, e );
7539 }
7540 break;
7541 case OO.ui.Keys.ESCAPE:
7542 case OO.ui.Keys.TAB:
7543 if ( currentItem ) {
7544 currentItem.setHighlighted( false );
7545 }
7546 this.toggle( false );
7547 // Don't prevent tabbing away, prevent defocusing
7548 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
7549 e.preventDefault();
7550 e.stopPropagation();
7551 }
7552 break;
7553 default:
7554 OO.ui.MenuSelectWidget.parent.prototype.onDocumentKeyDown.call( this, e );
7555 return;
7556 }
7557 }
7558 };
7559
7560 /**
7561 * Update menu item visibility and clipping after input changes (if filterFromInput is enabled)
7562 * or after items were added/removed (always).
7563 *
7564 * @protected
7565 */
7566 OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () {
7567 var i, item, items, visible, section, sectionEmpty, filter, exactFilter,
7568 anyVisible = false,
7569 len = this.items.length,
7570 showAll = !this.isVisible(),
7571 exactMatch = false;
7572
7573 if ( this.$input && this.filterFromInput ) {
7574 filter = showAll ? null : this.getItemMatcher( this.$input.val() );
7575 exactFilter = this.getItemMatcher( this.$input.val(), true );
7576 // Hide non-matching options, and also hide section headers if all options
7577 // in their section are hidden.
7578 for ( i = 0; i < len; i++ ) {
7579 item = this.items[ i ];
7580 if ( item instanceof OO.ui.MenuSectionOptionWidget ) {
7581 if ( section ) {
7582 // If the previous section was empty, hide its header
7583 section.toggle( showAll || !sectionEmpty );
7584 }
7585 section = item;
7586 sectionEmpty = true;
7587 } else if ( item instanceof OO.ui.OptionWidget ) {
7588 visible = showAll || filter( item );
7589 exactMatch = exactMatch || exactFilter( item );
7590 anyVisible = anyVisible || visible;
7591 sectionEmpty = sectionEmpty && !visible;
7592 item.toggle( visible );
7593 }
7594 }
7595 // Process the final section
7596 if ( section ) {
7597 section.toggle( showAll || !sectionEmpty );
7598 }
7599
7600 if ( anyVisible && this.items.length && !exactMatch ) {
7601 this.scrollItemIntoView( this.items[ 0 ] );
7602 }
7603
7604 this.$element.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible );
7605
7606 if ( this.highlightOnFilter ) {
7607 // Highlight the first item on the list
7608 item = null;
7609 items = this.getItems();
7610 for ( i = 0; i < items.length; i++ ) {
7611 if ( items[ i ].isVisible() ) {
7612 item = items[ i ];
7613 break;
7614 }
7615 }
7616 this.highlightItem( item );
7617 }
7618
7619 }
7620
7621 // Reevaluate clipping
7622 this.clip();
7623 };
7624
7625 /**
7626 * @inheritdoc
7627 */
7628 OO.ui.MenuSelectWidget.prototype.bindDocumentKeyDownListener = function () {
7629 if ( this.$input ) {
7630 this.$input.on( 'keydown', this.onDocumentKeyDownHandler );
7631 } else {
7632 OO.ui.MenuSelectWidget.parent.prototype.bindDocumentKeyDownListener.call( this );
7633 }
7634 };
7635
7636 /**
7637 * @inheritdoc
7638 */
7639 OO.ui.MenuSelectWidget.prototype.unbindDocumentKeyDownListener = function () {
7640 if ( this.$input ) {
7641 this.$input.off( 'keydown', this.onDocumentKeyDownHandler );
7642 } else {
7643 OO.ui.MenuSelectWidget.parent.prototype.unbindDocumentKeyDownListener.call( this );
7644 }
7645 };
7646
7647 /**
7648 * @inheritdoc
7649 */
7650 OO.ui.MenuSelectWidget.prototype.bindDocumentKeyPressListener = function () {
7651 if ( this.$input ) {
7652 if ( this.filterFromInput ) {
7653 this.$input.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
7654 this.updateItemVisibility();
7655 }
7656 } else {
7657 OO.ui.MenuSelectWidget.parent.prototype.bindDocumentKeyPressListener.call( this );
7658 }
7659 };
7660
7661 /**
7662 * @inheritdoc
7663 */
7664 OO.ui.MenuSelectWidget.prototype.unbindDocumentKeyPressListener = function () {
7665 if ( this.$input ) {
7666 if ( this.filterFromInput ) {
7667 this.$input.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
7668 this.updateItemVisibility();
7669 }
7670 } else {
7671 OO.ui.MenuSelectWidget.parent.prototype.unbindDocumentKeyPressListener.call( this );
7672 }
7673 };
7674
7675 /**
7676 * Choose an item.
7677 *
7678 * When a user chooses an item, the menu is closed, unless the hideOnChoose config option is set to false.
7679 *
7680 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
7681 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
7682 *
7683 * @param {OO.ui.OptionWidget} item Item to choose
7684 * @chainable
7685 */
7686 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
7687 OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item );
7688 if ( this.hideOnChoose ) {
7689 this.toggle( false );
7690 }
7691 return this;
7692 };
7693
7694 /**
7695 * @inheritdoc
7696 */
7697 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
7698 // Parent method
7699 OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index );
7700
7701 this.updateItemVisibility();
7702
7703 return this;
7704 };
7705
7706 /**
7707 * @inheritdoc
7708 */
7709 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
7710 // Parent method
7711 OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items );
7712
7713 this.updateItemVisibility();
7714
7715 return this;
7716 };
7717
7718 /**
7719 * @inheritdoc
7720 */
7721 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
7722 // Parent method
7723 OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this );
7724
7725 this.updateItemVisibility();
7726
7727 return this;
7728 };
7729
7730 /**
7731 * Toggle visibility of the menu. The menu is initially hidden and must be shown by calling
7732 * `.toggle( true )` after its #$element is attached to the DOM.
7733 *
7734 * Do not show the menu while it is not attached to the DOM. The calculations required to display
7735 * it in the right place and with the right dimensions only work correctly while it is attached.
7736 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
7737 * strictly enforced, so currently it only generates a warning in the browser console.
7738 *
7739 * @fires ready
7740 * @inheritdoc
7741 */
7742 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
7743 var change, originalHeight, flippedHeight;
7744
7745 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
7746 change = visible !== this.isVisible();
7747
7748 if ( visible && !this.warnedUnattached && !this.isElementAttached() ) {
7749 OO.ui.warnDeprecation( 'MenuSelectWidget#toggle: Before calling this method, the menu must be attached to the DOM.' );
7750 this.warnedUnattached = true;
7751 }
7752
7753 if ( change && visible ) {
7754 // Reset position before showing the popup again. It's possible we no longer need to flip
7755 // (e.g. if the user scrolled).
7756 this.setVerticalPosition( this.originalVerticalPosition );
7757 }
7758
7759 // Parent method
7760 OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible );
7761
7762 if ( change ) {
7763 if ( visible ) {
7764
7765 if ( this.width ) {
7766 this.setIdealSize( this.width );
7767 } else if ( this.$floatableContainer ) {
7768 this.$clippable.css( 'width', 'auto' );
7769 this.setIdealSize(
7770 this.$floatableContainer[ 0 ].offsetWidth > this.$clippable[ 0 ].offsetWidth ?
7771 // Dropdown is smaller than handle so expand to width
7772 this.$floatableContainer[ 0 ].offsetWidth :
7773 // Dropdown is larger than handle so auto size
7774 'auto'
7775 );
7776 this.$clippable.css( 'width', '' );
7777 }
7778
7779 this.togglePositioning( !!this.$floatableContainer );
7780 this.toggleClipping( true );
7781
7782 this.bindDocumentKeyDownListener();
7783 this.bindDocumentKeyPressListener();
7784
7785 if (
7786 ( this.isClippedVertically() || this.isFloatableOutOfView() ) &&
7787 this.originalVerticalPosition !== 'center'
7788 ) {
7789 // If opening the menu in one direction causes it to be clipped, flip it
7790 originalHeight = this.$element.height();
7791 this.setVerticalPosition(
7792 this.constructor.static.flippedPositions[ this.originalVerticalPosition ]
7793 );
7794 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
7795 // If flipping also causes it to be clipped, open in whichever direction
7796 // we have more space
7797 flippedHeight = this.$element.height();
7798 if ( originalHeight > flippedHeight ) {
7799 this.setVerticalPosition( this.originalVerticalPosition );
7800 }
7801 }
7802 }
7803 // Note that we do not flip the menu's opening direction if the clipping changes
7804 // later (e.g. after the user scrolls), that seems like it would be annoying
7805
7806 this.$focusOwner.attr( 'aria-expanded', 'true' );
7807
7808 if ( this.findSelectedItem() ) {
7809 this.$focusOwner.attr( 'aria-activedescendant', this.findSelectedItem().getElementId() );
7810 this.findSelectedItem().scrollElementIntoView( { duration: 0 } );
7811 }
7812
7813 // Auto-hide
7814 if ( this.autoHide ) {
7815 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
7816 }
7817
7818 this.emit( 'ready' );
7819 } else {
7820 this.$focusOwner.removeAttr( 'aria-activedescendant' );
7821 this.unbindDocumentKeyDownListener();
7822 this.unbindDocumentKeyPressListener();
7823 this.$focusOwner.attr( 'aria-expanded', 'false' );
7824 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
7825 this.togglePositioning( false );
7826 this.toggleClipping( false );
7827 }
7828 }
7829
7830 return this;
7831 };
7832
7833 /**
7834 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
7835 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
7836 * users can interact with it.
7837 *
7838 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7839 * OO.ui.DropdownInputWidget instead.
7840 *
7841 * @example
7842 * // Example: A DropdownWidget with a menu that contains three options
7843 * var dropDown = new OO.ui.DropdownWidget( {
7844 * label: 'Dropdown menu: Select a menu option',
7845 * menu: {
7846 * items: [
7847 * new OO.ui.MenuOptionWidget( {
7848 * data: 'a',
7849 * label: 'First'
7850 * } ),
7851 * new OO.ui.MenuOptionWidget( {
7852 * data: 'b',
7853 * label: 'Second'
7854 * } ),
7855 * new OO.ui.MenuOptionWidget( {
7856 * data: 'c',
7857 * label: 'Third'
7858 * } )
7859 * ]
7860 * }
7861 * } );
7862 *
7863 * $( 'body' ).append( dropDown.$element );
7864 *
7865 * dropDown.getMenu().selectItemByData( 'b' );
7866 *
7867 * dropDown.getMenu().findSelectedItem().getData(); // returns 'b'
7868 *
7869 * For more information, please see the [OOUI documentation on MediaWiki] [1].
7870 *
7871 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
7872 *
7873 * @class
7874 * @extends OO.ui.Widget
7875 * @mixins OO.ui.mixin.IconElement
7876 * @mixins OO.ui.mixin.IndicatorElement
7877 * @mixins OO.ui.mixin.LabelElement
7878 * @mixins OO.ui.mixin.TitledElement
7879 * @mixins OO.ui.mixin.TabIndexedElement
7880 *
7881 * @constructor
7882 * @param {Object} [config] Configuration options
7883 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.MenuSelectWidget menu select widget}
7884 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
7885 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
7886 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
7887 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
7888 */
7889 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
7890 // Configuration initialization
7891 config = $.extend( { indicator: 'down' }, config );
7892
7893 // Parent constructor
7894 OO.ui.DropdownWidget.parent.call( this, config );
7895
7896 // Properties (must be set before TabIndexedElement constructor call)
7897 this.$handle = $( '<span>' );
7898 this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
7899
7900 // Mixin constructors
7901 OO.ui.mixin.IconElement.call( this, config );
7902 OO.ui.mixin.IndicatorElement.call( this, config );
7903 OO.ui.mixin.LabelElement.call( this, config );
7904 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
7905 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
7906
7907 // Properties
7908 this.menu = new OO.ui.MenuSelectWidget( $.extend( {
7909 widget: this,
7910 $floatableContainer: this.$element
7911 }, config.menu ) );
7912
7913 // Events
7914 this.$handle.on( {
7915 click: this.onClick.bind( this ),
7916 keydown: this.onKeyDown.bind( this ),
7917 // Hack? Handle type-to-search when menu is not expanded and not handling its own events
7918 keypress: this.menu.onDocumentKeyPressHandler,
7919 blur: this.menu.clearKeyPressBuffer.bind( this.menu )
7920 } );
7921 this.menu.connect( this, {
7922 select: 'onMenuSelect',
7923 toggle: 'onMenuToggle'
7924 } );
7925
7926 // Initialization
7927 this.$handle
7928 .addClass( 'oo-ui-dropdownWidget-handle' )
7929 .attr( {
7930 role: 'combobox',
7931 'aria-owns': this.menu.getElementId(),
7932 'aria-autocomplete': 'list'
7933 } )
7934 .append( this.$icon, this.$label, this.$indicator );
7935 this.$element
7936 .addClass( 'oo-ui-dropdownWidget' )
7937 .append( this.$handle );
7938 this.$overlay.append( this.menu.$element );
7939 };
7940
7941 /* Setup */
7942
7943 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
7944 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IconElement );
7945 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IndicatorElement );
7946 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.LabelElement );
7947 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TitledElement );
7948 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TabIndexedElement );
7949
7950 /* Methods */
7951
7952 /**
7953 * Get the menu.
7954 *
7955 * @return {OO.ui.MenuSelectWidget} Menu of widget
7956 */
7957 OO.ui.DropdownWidget.prototype.getMenu = function () {
7958 return this.menu;
7959 };
7960
7961 /**
7962 * Handles menu select events.
7963 *
7964 * @private
7965 * @param {OO.ui.MenuOptionWidget} item Selected menu item
7966 */
7967 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
7968 var selectedLabel;
7969
7970 if ( !item ) {
7971 this.setLabel( null );
7972 return;
7973 }
7974
7975 selectedLabel = item.getLabel();
7976
7977 // If the label is a DOM element, clone it, because setLabel will append() it
7978 if ( selectedLabel instanceof jQuery ) {
7979 selectedLabel = selectedLabel.clone();
7980 }
7981
7982 this.setLabel( selectedLabel );
7983 };
7984
7985 /**
7986 * Handle menu toggle events.
7987 *
7988 * @private
7989 * @param {boolean} isVisible Open state of the menu
7990 */
7991 OO.ui.DropdownWidget.prototype.onMenuToggle = function ( isVisible ) {
7992 this.$element.toggleClass( 'oo-ui-dropdownWidget-open', isVisible );
7993 this.$handle.attr(
7994 'aria-expanded',
7995 this.$element.hasClass( 'oo-ui-dropdownWidget-open' ).toString()
7996 );
7997 };
7998
7999 /**
8000 * Handle mouse click events.
8001 *
8002 * @private
8003 * @param {jQuery.Event} e Mouse click event
8004 */
8005 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
8006 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
8007 this.menu.toggle();
8008 }
8009 return false;
8010 };
8011
8012 /**
8013 * Handle key down events.
8014 *
8015 * @private
8016 * @param {jQuery.Event} e Key down event
8017 */
8018 OO.ui.DropdownWidget.prototype.onKeyDown = function ( e ) {
8019 if (
8020 !this.isDisabled() &&
8021 (
8022 e.which === OO.ui.Keys.ENTER ||
8023 (
8024 e.which === OO.ui.Keys.SPACE &&
8025 // Avoid conflicts with type-to-search, see SelectWidget#onKeyPress.
8026 // Space only closes the menu is the user is not typing to search.
8027 this.menu.keyPressBuffer === ''
8028 ) ||
8029 (
8030 !this.menu.isVisible() &&
8031 (
8032 e.which === OO.ui.Keys.UP ||
8033 e.which === OO.ui.Keys.DOWN
8034 )
8035 )
8036 )
8037 ) {
8038 this.menu.toggle();
8039 return false;
8040 }
8041 };
8042
8043 /**
8044 * RadioOptionWidget is an option widget that looks like a radio button.
8045 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
8046 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8047 *
8048 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8049 *
8050 * @class
8051 * @extends OO.ui.OptionWidget
8052 *
8053 * @constructor
8054 * @param {Object} [config] Configuration options
8055 */
8056 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
8057 // Configuration initialization
8058 config = config || {};
8059
8060 // Properties (must be done before parent constructor which calls #setDisabled)
8061 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
8062
8063 // Parent constructor
8064 OO.ui.RadioOptionWidget.parent.call( this, config );
8065
8066 // Initialization
8067 // Remove implicit role, we're handling it ourselves
8068 this.radio.$input.attr( 'role', 'presentation' );
8069 this.$element
8070 .addClass( 'oo-ui-radioOptionWidget' )
8071 .attr( 'role', 'radio' )
8072 .attr( 'aria-checked', 'false' )
8073 .removeAttr( 'aria-selected' )
8074 .prepend( this.radio.$element );
8075 };
8076
8077 /* Setup */
8078
8079 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
8080
8081 /* Static Properties */
8082
8083 /**
8084 * @static
8085 * @inheritdoc
8086 */
8087 OO.ui.RadioOptionWidget.static.highlightable = false;
8088
8089 /**
8090 * @static
8091 * @inheritdoc
8092 */
8093 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
8094
8095 /**
8096 * @static
8097 * @inheritdoc
8098 */
8099 OO.ui.RadioOptionWidget.static.pressable = false;
8100
8101 /**
8102 * @static
8103 * @inheritdoc
8104 */
8105 OO.ui.RadioOptionWidget.static.tagName = 'label';
8106
8107 /* Methods */
8108
8109 /**
8110 * @inheritdoc
8111 */
8112 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
8113 OO.ui.RadioOptionWidget.parent.prototype.setSelected.call( this, state );
8114
8115 this.radio.setSelected( state );
8116 this.$element
8117 .attr( 'aria-checked', state.toString() )
8118 .removeAttr( 'aria-selected' );
8119
8120 return this;
8121 };
8122
8123 /**
8124 * @inheritdoc
8125 */
8126 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
8127 OO.ui.RadioOptionWidget.parent.prototype.setDisabled.call( this, disabled );
8128
8129 this.radio.setDisabled( this.isDisabled() );
8130
8131 return this;
8132 };
8133
8134 /**
8135 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
8136 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
8137 * an interface for adding, removing and selecting options.
8138 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8139 *
8140 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8141 * OO.ui.RadioSelectInputWidget instead.
8142 *
8143 * @example
8144 * // A RadioSelectWidget with RadioOptions.
8145 * var option1 = new OO.ui.RadioOptionWidget( {
8146 * data: 'a',
8147 * label: 'Selected radio option'
8148 * } );
8149 *
8150 * var option2 = new OO.ui.RadioOptionWidget( {
8151 * data: 'b',
8152 * label: 'Unselected radio option'
8153 * } );
8154 *
8155 * var radioSelect=new OO.ui.RadioSelectWidget( {
8156 * items: [ option1, option2 ]
8157 * } );
8158 *
8159 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
8160 * radioSelect.selectItem( option1 );
8161 *
8162 * $( 'body' ).append( radioSelect.$element );
8163 *
8164 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8165
8166 *
8167 * @class
8168 * @extends OO.ui.SelectWidget
8169 * @mixins OO.ui.mixin.TabIndexedElement
8170 *
8171 * @constructor
8172 * @param {Object} [config] Configuration options
8173 */
8174 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
8175 // Parent constructor
8176 OO.ui.RadioSelectWidget.parent.call( this, config );
8177
8178 // Mixin constructors
8179 OO.ui.mixin.TabIndexedElement.call( this, config );
8180
8181 // Events
8182 this.$element.on( {
8183 focus: this.bindDocumentKeyDownListener.bind( this ),
8184 blur: this.unbindDocumentKeyDownListener.bind( this )
8185 } );
8186
8187 // Initialization
8188 this.$element
8189 .addClass( 'oo-ui-radioSelectWidget' )
8190 .attr( 'role', 'radiogroup' );
8191 };
8192
8193 /* Setup */
8194
8195 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
8196 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.mixin.TabIndexedElement );
8197
8198 /**
8199 * MultioptionWidgets are special elements that can be selected and configured with data. The
8200 * data is often unique for each option, but it does not have to be. MultioptionWidgets are used
8201 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
8202 * and examples, please see the [OOUI documentation on MediaWiki][1].
8203 *
8204 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Multioptions
8205 *
8206 * @class
8207 * @extends OO.ui.Widget
8208 * @mixins OO.ui.mixin.ItemWidget
8209 * @mixins OO.ui.mixin.LabelElement
8210 *
8211 * @constructor
8212 * @param {Object} [config] Configuration options
8213 * @cfg {boolean} [selected=false] Whether the option is initially selected
8214 */
8215 OO.ui.MultioptionWidget = function OoUiMultioptionWidget( config ) {
8216 // Configuration initialization
8217 config = config || {};
8218
8219 // Parent constructor
8220 OO.ui.MultioptionWidget.parent.call( this, config );
8221
8222 // Mixin constructors
8223 OO.ui.mixin.ItemWidget.call( this );
8224 OO.ui.mixin.LabelElement.call( this, config );
8225
8226 // Properties
8227 this.selected = null;
8228
8229 // Initialization
8230 this.$element
8231 .addClass( 'oo-ui-multioptionWidget' )
8232 .append( this.$label );
8233 this.setSelected( config.selected );
8234 };
8235
8236 /* Setup */
8237
8238 OO.inheritClass( OO.ui.MultioptionWidget, OO.ui.Widget );
8239 OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.ItemWidget );
8240 OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.LabelElement );
8241
8242 /* Events */
8243
8244 /**
8245 * @event change
8246 *
8247 * A change event is emitted when the selected state of the option changes.
8248 *
8249 * @param {boolean} selected Whether the option is now selected
8250 */
8251
8252 /* Methods */
8253
8254 /**
8255 * Check if the option is selected.
8256 *
8257 * @return {boolean} Item is selected
8258 */
8259 OO.ui.MultioptionWidget.prototype.isSelected = function () {
8260 return this.selected;
8261 };
8262
8263 /**
8264 * Set the option’s selected state. In general, all modifications to the selection
8265 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
8266 * method instead of this method.
8267 *
8268 * @param {boolean} [state=false] Select option
8269 * @chainable
8270 */
8271 OO.ui.MultioptionWidget.prototype.setSelected = function ( state ) {
8272 state = !!state;
8273 if ( this.selected !== state ) {
8274 this.selected = state;
8275 this.emit( 'change', state );
8276 this.$element.toggleClass( 'oo-ui-multioptionWidget-selected', state );
8277 }
8278 return this;
8279 };
8280
8281 /**
8282 * MultiselectWidget allows selecting multiple options from a list.
8283 *
8284 * For more information about menus and options, please see the [OOUI documentation on MediaWiki][1].
8285 *
8286 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
8287 *
8288 * @class
8289 * @abstract
8290 * @extends OO.ui.Widget
8291 * @mixins OO.ui.mixin.GroupWidget
8292 *
8293 * @constructor
8294 * @param {Object} [config] Configuration options
8295 * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
8296 */
8297 OO.ui.MultiselectWidget = function OoUiMultiselectWidget( config ) {
8298 // Parent constructor
8299 OO.ui.MultiselectWidget.parent.call( this, config );
8300
8301 // Configuration initialization
8302 config = config || {};
8303
8304 // Mixin constructors
8305 OO.ui.mixin.GroupWidget.call( this, config );
8306
8307 // Events
8308 this.aggregate( { change: 'select' } );
8309 // This is mostly for compatibility with TagMultiselectWidget... normally, 'change' is emitted
8310 // by GroupElement only when items are added/removed
8311 this.connect( this, { select: [ 'emit', 'change' ] } );
8312
8313 // Initialization
8314 if ( config.items ) {
8315 this.addItems( config.items );
8316 }
8317 this.$group.addClass( 'oo-ui-multiselectWidget-group' );
8318 this.$element.addClass( 'oo-ui-multiselectWidget' )
8319 .append( this.$group );
8320 };
8321
8322 /* Setup */
8323
8324 OO.inheritClass( OO.ui.MultiselectWidget, OO.ui.Widget );
8325 OO.mixinClass( OO.ui.MultiselectWidget, OO.ui.mixin.GroupWidget );
8326
8327 /* Events */
8328
8329 /**
8330 * @event change
8331 *
8332 * A change event is emitted when the set of items changes, or an item is selected or deselected.
8333 */
8334
8335 /**
8336 * @event select
8337 *
8338 * A select event is emitted when an item is selected or deselected.
8339 */
8340
8341 /* Methods */
8342
8343 /**
8344 * Find options that are selected.
8345 *
8346 * @return {OO.ui.MultioptionWidget[]} Selected options
8347 */
8348 OO.ui.MultiselectWidget.prototype.findSelectedItems = function () {
8349 return this.items.filter( function ( item ) {
8350 return item.isSelected();
8351 } );
8352 };
8353
8354 /**
8355 * Find the data of options that are selected.
8356 *
8357 * @return {Object[]|string[]} Values of selected options
8358 */
8359 OO.ui.MultiselectWidget.prototype.findSelectedItemsData = function () {
8360 return this.findSelectedItems().map( function ( item ) {
8361 return item.data;
8362 } );
8363 };
8364
8365 /**
8366 * Select options by reference. Options not mentioned in the `items` array will be deselected.
8367 *
8368 * @param {OO.ui.MultioptionWidget[]} items Items to select
8369 * @chainable
8370 */
8371 OO.ui.MultiselectWidget.prototype.selectItems = function ( items ) {
8372 this.items.forEach( function ( item ) {
8373 var selected = items.indexOf( item ) !== -1;
8374 item.setSelected( selected );
8375 } );
8376 return this;
8377 };
8378
8379 /**
8380 * Select items by their data. Options not mentioned in the `datas` array will be deselected.
8381 *
8382 * @param {Object[]|string[]} datas Values of items to select
8383 * @chainable
8384 */
8385 OO.ui.MultiselectWidget.prototype.selectItemsByData = function ( datas ) {
8386 var items,
8387 widget = this;
8388 items = datas.map( function ( data ) {
8389 return widget.findItemFromData( data );
8390 } );
8391 this.selectItems( items );
8392 return this;
8393 };
8394
8395 /**
8396 * CheckboxMultioptionWidget is an option widget that looks like a checkbox.
8397 * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
8398 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8399 *
8400 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8401 *
8402 * @class
8403 * @extends OO.ui.MultioptionWidget
8404 *
8405 * @constructor
8406 * @param {Object} [config] Configuration options
8407 */
8408 OO.ui.CheckboxMultioptionWidget = function OoUiCheckboxMultioptionWidget( config ) {
8409 // Configuration initialization
8410 config = config || {};
8411
8412 // Properties (must be done before parent constructor which calls #setDisabled)
8413 this.checkbox = new OO.ui.CheckboxInputWidget();
8414
8415 // Parent constructor
8416 OO.ui.CheckboxMultioptionWidget.parent.call( this, config );
8417
8418 // Events
8419 this.checkbox.on( 'change', this.onCheckboxChange.bind( this ) );
8420 this.$element.on( 'keydown', this.onKeyDown.bind( this ) );
8421
8422 // Initialization
8423 this.$element
8424 .addClass( 'oo-ui-checkboxMultioptionWidget' )
8425 .prepend( this.checkbox.$element );
8426 };
8427
8428 /* Setup */
8429
8430 OO.inheritClass( OO.ui.CheckboxMultioptionWidget, OO.ui.MultioptionWidget );
8431
8432 /* Static Properties */
8433
8434 /**
8435 * @static
8436 * @inheritdoc
8437 */
8438 OO.ui.CheckboxMultioptionWidget.static.tagName = 'label';
8439
8440 /* Methods */
8441
8442 /**
8443 * Handle checkbox selected state change.
8444 *
8445 * @private
8446 */
8447 OO.ui.CheckboxMultioptionWidget.prototype.onCheckboxChange = function () {
8448 this.setSelected( this.checkbox.isSelected() );
8449 };
8450
8451 /**
8452 * @inheritdoc
8453 */
8454 OO.ui.CheckboxMultioptionWidget.prototype.setSelected = function ( state ) {
8455 OO.ui.CheckboxMultioptionWidget.parent.prototype.setSelected.call( this, state );
8456 this.checkbox.setSelected( state );
8457 return this;
8458 };
8459
8460 /**
8461 * @inheritdoc
8462 */
8463 OO.ui.CheckboxMultioptionWidget.prototype.setDisabled = function ( disabled ) {
8464 OO.ui.CheckboxMultioptionWidget.parent.prototype.setDisabled.call( this, disabled );
8465 this.checkbox.setDisabled( this.isDisabled() );
8466 return this;
8467 };
8468
8469 /**
8470 * Focus the widget.
8471 */
8472 OO.ui.CheckboxMultioptionWidget.prototype.focus = function () {
8473 this.checkbox.focus();
8474 };
8475
8476 /**
8477 * Handle key down events.
8478 *
8479 * @protected
8480 * @param {jQuery.Event} e
8481 */
8482 OO.ui.CheckboxMultioptionWidget.prototype.onKeyDown = function ( e ) {
8483 var
8484 element = this.getElementGroup(),
8485 nextItem;
8486
8487 if ( e.keyCode === OO.ui.Keys.LEFT || e.keyCode === OO.ui.Keys.UP ) {
8488 nextItem = element.getRelativeFocusableItem( this, -1 );
8489 } else if ( e.keyCode === OO.ui.Keys.RIGHT || e.keyCode === OO.ui.Keys.DOWN ) {
8490 nextItem = element.getRelativeFocusableItem( this, 1 );
8491 }
8492
8493 if ( nextItem ) {
8494 e.preventDefault();
8495 nextItem.focus();
8496 }
8497 };
8498
8499 /**
8500 * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
8501 * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
8502 * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
8503 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8504 *
8505 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8506 * OO.ui.CheckboxMultiselectInputWidget instead.
8507 *
8508 * @example
8509 * // A CheckboxMultiselectWidget with CheckboxMultioptions.
8510 * var option1 = new OO.ui.CheckboxMultioptionWidget( {
8511 * data: 'a',
8512 * selected: true,
8513 * label: 'Selected checkbox'
8514 * } );
8515 *
8516 * var option2 = new OO.ui.CheckboxMultioptionWidget( {
8517 * data: 'b',
8518 * label: 'Unselected checkbox'
8519 * } );
8520 *
8521 * var multiselect=new OO.ui.CheckboxMultiselectWidget( {
8522 * items: [ option1, option2 ]
8523 * } );
8524 *
8525 * $( 'body' ).append( multiselect.$element );
8526 *
8527 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8528 *
8529 * @class
8530 * @extends OO.ui.MultiselectWidget
8531 *
8532 * @constructor
8533 * @param {Object} [config] Configuration options
8534 */
8535 OO.ui.CheckboxMultiselectWidget = function OoUiCheckboxMultiselectWidget( config ) {
8536 // Parent constructor
8537 OO.ui.CheckboxMultiselectWidget.parent.call( this, config );
8538
8539 // Properties
8540 this.$lastClicked = null;
8541
8542 // Events
8543 this.$group.on( 'click', this.onClick.bind( this ) );
8544
8545 // Initialization
8546 this.$element
8547 .addClass( 'oo-ui-checkboxMultiselectWidget' );
8548 };
8549
8550 /* Setup */
8551
8552 OO.inheritClass( OO.ui.CheckboxMultiselectWidget, OO.ui.MultiselectWidget );
8553
8554 /* Methods */
8555
8556 /**
8557 * Get an option by its position relative to the specified item (or to the start of the option array,
8558 * if item is `null`). The direction in which to search through the option array is specified with a
8559 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
8560 * `null` if there are no options in the array.
8561 *
8562 * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
8563 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
8564 * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items in the select
8565 */
8566 OO.ui.CheckboxMultiselectWidget.prototype.getRelativeFocusableItem = function ( item, direction ) {
8567 var currentIndex, nextIndex, i,
8568 increase = direction > 0 ? 1 : -1,
8569 len = this.items.length;
8570
8571 if ( item ) {
8572 currentIndex = this.items.indexOf( item );
8573 nextIndex = ( currentIndex + increase + len ) % len;
8574 } else {
8575 // If no item is selected and moving forward, start at the beginning.
8576 // If moving backward, start at the end.
8577 nextIndex = direction > 0 ? 0 : len - 1;
8578 }
8579
8580 for ( i = 0; i < len; i++ ) {
8581 item = this.items[ nextIndex ];
8582 if ( item && !item.isDisabled() ) {
8583 return item;
8584 }
8585 nextIndex = ( nextIndex + increase + len ) % len;
8586 }
8587 return null;
8588 };
8589
8590 /**
8591 * Handle click events on checkboxes.
8592 *
8593 * @param {jQuery.Event} e
8594 */
8595 OO.ui.CheckboxMultiselectWidget.prototype.onClick = function ( e ) {
8596 var $options, lastClickedIndex, nowClickedIndex, i, direction, wasSelected, items,
8597 $lastClicked = this.$lastClicked,
8598 $nowClicked = $( e.target ).closest( '.oo-ui-checkboxMultioptionWidget' )
8599 .not( '.oo-ui-widget-disabled' );
8600
8601 // Allow selecting multiple options at once by Shift-clicking them
8602 if ( $lastClicked && $nowClicked.length && e.shiftKey ) {
8603 $options = this.$group.find( '.oo-ui-checkboxMultioptionWidget' );
8604 lastClickedIndex = $options.index( $lastClicked );
8605 nowClickedIndex = $options.index( $nowClicked );
8606 // If it's the same item, either the user is being silly, or it's a fake event generated by the
8607 // browser. In either case we don't need custom handling.
8608 if ( nowClickedIndex !== lastClickedIndex ) {
8609 items = this.items;
8610 wasSelected = items[ nowClickedIndex ].isSelected();
8611 direction = nowClickedIndex > lastClickedIndex ? 1 : -1;
8612
8613 // This depends on the DOM order of the items and the order of the .items array being the same.
8614 for ( i = lastClickedIndex; i !== nowClickedIndex; i += direction ) {
8615 if ( !items[ i ].isDisabled() ) {
8616 items[ i ].setSelected( !wasSelected );
8617 }
8618 }
8619 // For the now-clicked element, use immediate timeout to allow the browser to do its own
8620 // handling first, then set our value. The order in which events happen is different for
8621 // clicks on the <input> and on the <label> and there are additional fake clicks fired for
8622 // non-click actions that change the checkboxes.
8623 e.preventDefault();
8624 setTimeout( function () {
8625 if ( !items[ nowClickedIndex ].isDisabled() ) {
8626 items[ nowClickedIndex ].setSelected( !wasSelected );
8627 }
8628 } );
8629 }
8630 }
8631
8632 if ( $nowClicked.length ) {
8633 this.$lastClicked = $nowClicked;
8634 }
8635 };
8636
8637 /**
8638 * Focus the widget
8639 *
8640 * @chainable
8641 */
8642 OO.ui.CheckboxMultiselectWidget.prototype.focus = function () {
8643 var item;
8644 if ( !this.isDisabled() ) {
8645 item = this.getRelativeFocusableItem( null, 1 );
8646 if ( item ) {
8647 item.focus();
8648 }
8649 }
8650 return this;
8651 };
8652
8653 /**
8654 * @inheritdoc
8655 */
8656 OO.ui.CheckboxMultiselectWidget.prototype.simulateLabelClick = function () {
8657 this.focus();
8658 };
8659
8660 /**
8661 * Progress bars visually display the status of an operation, such as a download,
8662 * and can be either determinate or indeterminate:
8663 *
8664 * - **determinate** process bars show the percent of an operation that is complete.
8665 *
8666 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
8667 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
8668 * not use percentages.
8669 *
8670 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
8671 *
8672 * @example
8673 * // Examples of determinate and indeterminate progress bars.
8674 * var progressBar1 = new OO.ui.ProgressBarWidget( {
8675 * progress: 33
8676 * } );
8677 * var progressBar2 = new OO.ui.ProgressBarWidget();
8678 *
8679 * // Create a FieldsetLayout to layout progress bars
8680 * var fieldset = new OO.ui.FieldsetLayout;
8681 * fieldset.addItems( [
8682 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
8683 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
8684 * ] );
8685 * $( 'body' ).append( fieldset.$element );
8686 *
8687 * @class
8688 * @extends OO.ui.Widget
8689 *
8690 * @constructor
8691 * @param {Object} [config] Configuration options
8692 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
8693 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
8694 * By default, the progress bar is indeterminate.
8695 */
8696 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
8697 // Configuration initialization
8698 config = config || {};
8699
8700 // Parent constructor
8701 OO.ui.ProgressBarWidget.parent.call( this, config );
8702
8703 // Properties
8704 this.$bar = $( '<div>' );
8705 this.progress = null;
8706
8707 // Initialization
8708 this.setProgress( config.progress !== undefined ? config.progress : false );
8709 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
8710 this.$element
8711 .attr( {
8712 role: 'progressbar',
8713 'aria-valuemin': 0,
8714 'aria-valuemax': 100
8715 } )
8716 .addClass( 'oo-ui-progressBarWidget' )
8717 .append( this.$bar );
8718 };
8719
8720 /* Setup */
8721
8722 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
8723
8724 /* Static Properties */
8725
8726 /**
8727 * @static
8728 * @inheritdoc
8729 */
8730 OO.ui.ProgressBarWidget.static.tagName = 'div';
8731
8732 /* Methods */
8733
8734 /**
8735 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
8736 *
8737 * @return {number|boolean} Progress percent
8738 */
8739 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
8740 return this.progress;
8741 };
8742
8743 /**
8744 * Set the percent of the process completed or `false` for an indeterminate process.
8745 *
8746 * @param {number|boolean} progress Progress percent or `false` for indeterminate
8747 */
8748 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
8749 this.progress = progress;
8750
8751 if ( progress !== false ) {
8752 this.$bar.css( 'width', this.progress + '%' );
8753 this.$element.attr( 'aria-valuenow', this.progress );
8754 } else {
8755 this.$bar.css( 'width', '' );
8756 this.$element.removeAttr( 'aria-valuenow' );
8757 }
8758 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress === false );
8759 };
8760
8761 /**
8762 * InputWidget is the base class for all input widgets, which
8763 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
8764 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
8765 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
8766 *
8767 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
8768 *
8769 * @abstract
8770 * @class
8771 * @extends OO.ui.Widget
8772 * @mixins OO.ui.mixin.FlaggedElement
8773 * @mixins OO.ui.mixin.TabIndexedElement
8774 * @mixins OO.ui.mixin.TitledElement
8775 * @mixins OO.ui.mixin.AccessKeyedElement
8776 *
8777 * @constructor
8778 * @param {Object} [config] Configuration options
8779 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
8780 * @cfg {string} [value=''] The value of the input.
8781 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
8782 * @cfg {string} [inputId] The value of the input’s HTML `id` attribute.
8783 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
8784 * before it is accepted.
8785 */
8786 OO.ui.InputWidget = function OoUiInputWidget( config ) {
8787 // Configuration initialization
8788 config = config || {};
8789
8790 // Parent constructor
8791 OO.ui.InputWidget.parent.call( this, config );
8792
8793 // Properties
8794 // See #reusePreInfuseDOM about config.$input
8795 this.$input = config.$input || this.getInputElement( config );
8796 this.value = '';
8797 this.inputFilter = config.inputFilter;
8798
8799 // Mixin constructors
8800 OO.ui.mixin.FlaggedElement.call( this, config );
8801 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
8802 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
8803 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$input } ) );
8804
8805 // Events
8806 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
8807
8808 // Initialization
8809 this.$input
8810 .addClass( 'oo-ui-inputWidget-input' )
8811 .attr( 'name', config.name )
8812 .prop( 'disabled', this.isDisabled() );
8813 this.$element
8814 .addClass( 'oo-ui-inputWidget' )
8815 .append( this.$input );
8816 this.setValue( config.value );
8817 if ( config.dir ) {
8818 this.setDir( config.dir );
8819 }
8820 if ( config.inputId !== undefined ) {
8821 this.setInputId( config.inputId );
8822 }
8823 };
8824
8825 /* Setup */
8826
8827 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
8828 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.FlaggedElement );
8829 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TabIndexedElement );
8830 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TitledElement );
8831 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.AccessKeyedElement );
8832
8833 /* Static Methods */
8834
8835 /**
8836 * @inheritdoc
8837 */
8838 OO.ui.InputWidget.static.reusePreInfuseDOM = function ( node, config ) {
8839 config = OO.ui.InputWidget.parent.static.reusePreInfuseDOM( node, config );
8840 // Reusing `$input` lets browsers preserve inputted values across page reloads, see T114134.
8841 config.$input = $( node ).find( '.oo-ui-inputWidget-input' );
8842 return config;
8843 };
8844
8845 /**
8846 * @inheritdoc
8847 */
8848 OO.ui.InputWidget.static.gatherPreInfuseState = function ( node, config ) {
8849 var state = OO.ui.InputWidget.parent.static.gatherPreInfuseState( node, config );
8850 if ( config.$input && config.$input.length ) {
8851 state.value = config.$input.val();
8852 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
8853 state.focus = config.$input.is( ':focus' );
8854 }
8855 return state;
8856 };
8857
8858 /* Events */
8859
8860 /**
8861 * @event change
8862 *
8863 * A change event is emitted when the value of the input changes.
8864 *
8865 * @param {string} value
8866 */
8867
8868 /* Methods */
8869
8870 /**
8871 * Get input element.
8872 *
8873 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
8874 * different circumstances. The element must have a `value` property (like form elements).
8875 *
8876 * @protected
8877 * @param {Object} config Configuration options
8878 * @return {jQuery} Input element
8879 */
8880 OO.ui.InputWidget.prototype.getInputElement = function () {
8881 return $( '<input>' );
8882 };
8883
8884 /**
8885 * Handle potentially value-changing events.
8886 *
8887 * @private
8888 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
8889 */
8890 OO.ui.InputWidget.prototype.onEdit = function () {
8891 var widget = this;
8892 if ( !this.isDisabled() ) {
8893 // Allow the stack to clear so the value will be updated
8894 setTimeout( function () {
8895 widget.setValue( widget.$input.val() );
8896 } );
8897 }
8898 };
8899
8900 /**
8901 * Get the value of the input.
8902 *
8903 * @return {string} Input value
8904 */
8905 OO.ui.InputWidget.prototype.getValue = function () {
8906 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
8907 // it, and we won't know unless they're kind enough to trigger a 'change' event.
8908 var value = this.$input.val();
8909 if ( this.value !== value ) {
8910 this.setValue( value );
8911 }
8912 return this.value;
8913 };
8914
8915 /**
8916 * Set the directionality of the input.
8917 *
8918 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
8919 * @chainable
8920 */
8921 OO.ui.InputWidget.prototype.setDir = function ( dir ) {
8922 this.$input.prop( 'dir', dir );
8923 return this;
8924 };
8925
8926 /**
8927 * Set the value of the input.
8928 *
8929 * @param {string} value New value
8930 * @fires change
8931 * @chainable
8932 */
8933 OO.ui.InputWidget.prototype.setValue = function ( value ) {
8934 value = this.cleanUpValue( value );
8935 // Update the DOM if it has changed. Note that with cleanUpValue, it
8936 // is possible for the DOM value to change without this.value changing.
8937 if ( this.$input.val() !== value ) {
8938 this.$input.val( value );
8939 }
8940 if ( this.value !== value ) {
8941 this.value = value;
8942 this.emit( 'change', this.value );
8943 }
8944 // The first time that the value is set (probably while constructing the widget),
8945 // remember it in defaultValue. This property can be later used to check whether
8946 // the value of the input has been changed since it was created.
8947 if ( this.defaultValue === undefined ) {
8948 this.defaultValue = this.value;
8949 this.$input[ 0 ].defaultValue = this.defaultValue;
8950 }
8951 return this;
8952 };
8953
8954 /**
8955 * Clean up incoming value.
8956 *
8957 * Ensures value is a string, and converts undefined and null to empty string.
8958 *
8959 * @private
8960 * @param {string} value Original value
8961 * @return {string} Cleaned up value
8962 */
8963 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
8964 if ( value === undefined || value === null ) {
8965 return '';
8966 } else if ( this.inputFilter ) {
8967 return this.inputFilter( String( value ) );
8968 } else {
8969 return String( value );
8970 }
8971 };
8972
8973 /**
8974 * @inheritdoc
8975 */
8976 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
8977 OO.ui.InputWidget.parent.prototype.setDisabled.call( this, state );
8978 if ( this.$input ) {
8979 this.$input.prop( 'disabled', this.isDisabled() );
8980 }
8981 return this;
8982 };
8983
8984 /**
8985 * Set the 'id' attribute of the `<input>` element.
8986 *
8987 * @param {string} id
8988 * @chainable
8989 */
8990 OO.ui.InputWidget.prototype.setInputId = function ( id ) {
8991 this.$input.attr( 'id', id );
8992 return this;
8993 };
8994
8995 /**
8996 * @inheritdoc
8997 */
8998 OO.ui.InputWidget.prototype.restorePreInfuseState = function ( state ) {
8999 OO.ui.InputWidget.parent.prototype.restorePreInfuseState.call( this, state );
9000 if ( state.value !== undefined && state.value !== this.getValue() ) {
9001 this.setValue( state.value );
9002 }
9003 if ( state.focus ) {
9004 this.focus();
9005 }
9006 };
9007
9008 /**
9009 * Data widget intended for creating 'hidden'-type inputs.
9010 *
9011 * @class
9012 * @extends OO.ui.Widget
9013 *
9014 * @constructor
9015 * @param {Object} [config] Configuration options
9016 * @cfg {string} [value=''] The value of the input.
9017 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
9018 */
9019 OO.ui.HiddenInputWidget = function OoUiHiddenInputWidget( config ) {
9020 // Configuration initialization
9021 config = $.extend( { value: '', name: '' }, config );
9022
9023 // Parent constructor
9024 OO.ui.HiddenInputWidget.parent.call( this, config );
9025
9026 // Initialization
9027 this.$element.attr( {
9028 type: 'hidden',
9029 value: config.value,
9030 name: config.name
9031 } );
9032 this.$element.removeAttr( 'aria-disabled' );
9033 };
9034
9035 /* Setup */
9036
9037 OO.inheritClass( OO.ui.HiddenInputWidget, OO.ui.Widget );
9038
9039 /* Static Properties */
9040
9041 /**
9042 * @static
9043 * @inheritdoc
9044 */
9045 OO.ui.HiddenInputWidget.static.tagName = 'input';
9046
9047 /**
9048 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
9049 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
9050 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
9051 * HTML `<button>` (the default) or an HTML `<input>` tags. See the
9052 * [OOUI documentation on MediaWiki] [1] for more information.
9053 *
9054 * @example
9055 * // A ButtonInputWidget rendered as an HTML button, the default.
9056 * var button = new OO.ui.ButtonInputWidget( {
9057 * label: 'Input button',
9058 * icon: 'check',
9059 * value: 'check'
9060 * } );
9061 * $( 'body' ).append( button.$element );
9062 *
9063 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#Button_inputs
9064 *
9065 * @class
9066 * @extends OO.ui.InputWidget
9067 * @mixins OO.ui.mixin.ButtonElement
9068 * @mixins OO.ui.mixin.IconElement
9069 * @mixins OO.ui.mixin.IndicatorElement
9070 * @mixins OO.ui.mixin.LabelElement
9071 * @mixins OO.ui.mixin.TitledElement
9072 *
9073 * @constructor
9074 * @param {Object} [config] Configuration options
9075 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
9076 * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
9077 * Widgets configured to be an `<input>` do not support {@link #icon icons} and {@link #indicator indicators},
9078 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
9079 * be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
9080 */
9081 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
9082 // Configuration initialization
9083 config = $.extend( { type: 'button', useInputTag: false }, config );
9084
9085 // See InputWidget#reusePreInfuseDOM about config.$input
9086 if ( config.$input ) {
9087 config.$input.empty();
9088 }
9089
9090 // Properties (must be set before parent constructor, which calls #setValue)
9091 this.useInputTag = config.useInputTag;
9092
9093 // Parent constructor
9094 OO.ui.ButtonInputWidget.parent.call( this, config );
9095
9096 // Mixin constructors
9097 OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
9098 OO.ui.mixin.IconElement.call( this, config );
9099 OO.ui.mixin.IndicatorElement.call( this, config );
9100 OO.ui.mixin.LabelElement.call( this, config );
9101 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
9102
9103 // Initialization
9104 if ( !config.useInputTag ) {
9105 this.$input.append( this.$icon, this.$label, this.$indicator );
9106 }
9107 this.$element.addClass( 'oo-ui-buttonInputWidget' );
9108 };
9109
9110 /* Setup */
9111
9112 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
9113 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.ButtonElement );
9114 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IconElement );
9115 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IndicatorElement );
9116 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.LabelElement );
9117 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.TitledElement );
9118
9119 /* Static Properties */
9120
9121 /**
9122 * @static
9123 * @inheritdoc
9124 */
9125 OO.ui.ButtonInputWidget.static.tagName = 'span';
9126
9127 /* Methods */
9128
9129 /**
9130 * @inheritdoc
9131 * @protected
9132 */
9133 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
9134 var type;
9135 type = [ 'button', 'submit', 'reset' ].indexOf( config.type ) !== -1 ? config.type : 'button';
9136 return $( '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + type + '">' );
9137 };
9138
9139 /**
9140 * Set label value.
9141 *
9142 * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
9143 *
9144 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
9145 * text, or `null` for no label
9146 * @chainable
9147 */
9148 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
9149 if ( typeof label === 'function' ) {
9150 label = OO.ui.resolveMsg( label );
9151 }
9152
9153 if ( this.useInputTag ) {
9154 // Discard non-plaintext labels
9155 if ( typeof label !== 'string' ) {
9156 label = '';
9157 }
9158
9159 this.$input.val( label );
9160 }
9161
9162 return OO.ui.mixin.LabelElement.prototype.setLabel.call( this, label );
9163 };
9164
9165 /**
9166 * Set the value of the input.
9167 *
9168 * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
9169 * they do not support {@link #value values}.
9170 *
9171 * @param {string} value New value
9172 * @chainable
9173 */
9174 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
9175 if ( !this.useInputTag ) {
9176 OO.ui.ButtonInputWidget.parent.prototype.setValue.call( this, value );
9177 }
9178 return this;
9179 };
9180
9181 /**
9182 * @inheritdoc
9183 */
9184 OO.ui.ButtonInputWidget.prototype.getInputId = function () {
9185 // Disable generating `<label>` elements for buttons. One would very rarely need additional label
9186 // for a button, and it's already a big clickable target, and it causes unexpected rendering.
9187 return null;
9188 };
9189
9190 /**
9191 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
9192 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
9193 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
9194 * alignment. For more information, please see the [OOUI documentation on MediaWiki][1].
9195 *
9196 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9197 *
9198 * @example
9199 * // An example of selected, unselected, and disabled checkbox inputs
9200 * var checkbox1=new OO.ui.CheckboxInputWidget( {
9201 * value: 'a',
9202 * selected: true
9203 * } );
9204 * var checkbox2=new OO.ui.CheckboxInputWidget( {
9205 * value: 'b'
9206 * } );
9207 * var checkbox3=new OO.ui.CheckboxInputWidget( {
9208 * value:'c',
9209 * disabled: true
9210 * } );
9211 * // Create a fieldset layout with fields for each checkbox.
9212 * var fieldset = new OO.ui.FieldsetLayout( {
9213 * label: 'Checkboxes'
9214 * } );
9215 * fieldset.addItems( [
9216 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
9217 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
9218 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
9219 * ] );
9220 * $( 'body' ).append( fieldset.$element );
9221 *
9222 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9223 *
9224 * @class
9225 * @extends OO.ui.InputWidget
9226 *
9227 * @constructor
9228 * @param {Object} [config] Configuration options
9229 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
9230 */
9231 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
9232 // Configuration initialization
9233 config = config || {};
9234
9235 // Parent constructor
9236 OO.ui.CheckboxInputWidget.parent.call( this, config );
9237
9238 // Properties
9239 this.checkIcon = new OO.ui.IconWidget( {
9240 icon: 'check',
9241 classes: [ 'oo-ui-checkboxInputWidget-checkIcon' ]
9242 } );
9243
9244 // Initialization
9245 this.$element
9246 .addClass( 'oo-ui-checkboxInputWidget' )
9247 // Required for pretty styling in WikimediaUI theme
9248 .append( this.checkIcon.$element );
9249 this.setSelected( config.selected !== undefined ? config.selected : false );
9250 };
9251
9252 /* Setup */
9253
9254 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
9255
9256 /* Static Properties */
9257
9258 /**
9259 * @static
9260 * @inheritdoc
9261 */
9262 OO.ui.CheckboxInputWidget.static.tagName = 'span';
9263
9264 /* Static Methods */
9265
9266 /**
9267 * @inheritdoc
9268 */
9269 OO.ui.CheckboxInputWidget.static.gatherPreInfuseState = function ( node, config ) {
9270 var state = OO.ui.CheckboxInputWidget.parent.static.gatherPreInfuseState( node, config );
9271 state.checked = config.$input.prop( 'checked' );
9272 return state;
9273 };
9274
9275 /* Methods */
9276
9277 /**
9278 * @inheritdoc
9279 * @protected
9280 */
9281 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
9282 return $( '<input>' ).attr( 'type', 'checkbox' );
9283 };
9284
9285 /**
9286 * @inheritdoc
9287 */
9288 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
9289 var widget = this;
9290 if ( !this.isDisabled() ) {
9291 // Allow the stack to clear so the value will be updated
9292 setTimeout( function () {
9293 widget.setSelected( widget.$input.prop( 'checked' ) );
9294 } );
9295 }
9296 };
9297
9298 /**
9299 * Set selection state of this checkbox.
9300 *
9301 * @param {boolean} state `true` for selected
9302 * @chainable
9303 */
9304 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
9305 state = !!state;
9306 if ( this.selected !== state ) {
9307 this.selected = state;
9308 this.$input.prop( 'checked', this.selected );
9309 this.emit( 'change', this.selected );
9310 }
9311 // The first time that the selection state is set (probably while constructing the widget),
9312 // remember it in defaultSelected. This property can be later used to check whether
9313 // the selection state of the input has been changed since it was created.
9314 if ( this.defaultSelected === undefined ) {
9315 this.defaultSelected = this.selected;
9316 this.$input[ 0 ].defaultChecked = this.defaultSelected;
9317 }
9318 return this;
9319 };
9320
9321 /**
9322 * Check if this checkbox is selected.
9323 *
9324 * @return {boolean} Checkbox is selected
9325 */
9326 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
9327 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
9328 // it, and we won't know unless they're kind enough to trigger a 'change' event.
9329 var selected = this.$input.prop( 'checked' );
9330 if ( this.selected !== selected ) {
9331 this.setSelected( selected );
9332 }
9333 return this.selected;
9334 };
9335
9336 /**
9337 * @inheritdoc
9338 */
9339 OO.ui.CheckboxInputWidget.prototype.simulateLabelClick = function () {
9340 if ( !this.isDisabled() ) {
9341 this.$input.click();
9342 }
9343 this.focus();
9344 };
9345
9346 /**
9347 * @inheritdoc
9348 */
9349 OO.ui.CheckboxInputWidget.prototype.restorePreInfuseState = function ( state ) {
9350 OO.ui.CheckboxInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
9351 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
9352 this.setSelected( state.checked );
9353 }
9354 };
9355
9356 /**
9357 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
9358 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
9359 * of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9360 * more information about input widgets.
9361 *
9362 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
9363 * are no options. If no `value` configuration option is provided, the first option is selected.
9364 * If you need a state representing no value (no option being selected), use a DropdownWidget.
9365 *
9366 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
9367 *
9368 * @example
9369 * // Example: A DropdownInputWidget with three options
9370 * var dropdownInput = new OO.ui.DropdownInputWidget( {
9371 * options: [
9372 * { data: 'a', label: 'First' },
9373 * { data: 'b', label: 'Second'},
9374 * { data: 'c', label: 'Third' }
9375 * ]
9376 * } );
9377 * $( 'body' ).append( dropdownInput.$element );
9378 *
9379 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9380 *
9381 * @class
9382 * @extends OO.ui.InputWidget
9383 *
9384 * @constructor
9385 * @param {Object} [config] Configuration options
9386 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9387 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
9388 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
9389 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
9390 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
9391 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
9392 */
9393 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
9394 // Configuration initialization
9395 config = config || {};
9396
9397 // Properties (must be done before parent constructor which calls #setDisabled)
9398 this.dropdownWidget = new OO.ui.DropdownWidget( $.extend(
9399 {
9400 $overlay: config.$overlay
9401 },
9402 config.dropdown
9403 ) );
9404 // Set up the options before parent constructor, which uses them to validate config.value.
9405 // Use this instead of setOptions() because this.$input is not set up yet.
9406 this.setOptionsData( config.options || [] );
9407
9408 // Parent constructor
9409 OO.ui.DropdownInputWidget.parent.call( this, config );
9410
9411 // Events
9412 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
9413
9414 // Initialization
9415 this.$element
9416 .addClass( 'oo-ui-dropdownInputWidget' )
9417 .append( this.dropdownWidget.$element );
9418 this.setTabIndexedElement( this.dropdownWidget.$tabIndexed );
9419 };
9420
9421 /* Setup */
9422
9423 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
9424
9425 /* Methods */
9426
9427 /**
9428 * @inheritdoc
9429 * @protected
9430 */
9431 OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
9432 return $( '<select>' );
9433 };
9434
9435 /**
9436 * Handles menu select events.
9437 *
9438 * @private
9439 * @param {OO.ui.MenuOptionWidget|null} item Selected menu item
9440 */
9441 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
9442 this.setValue( item ? item.getData() : '' );
9443 };
9444
9445 /**
9446 * @inheritdoc
9447 */
9448 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
9449 var selected;
9450 value = this.cleanUpValue( value );
9451 // Only allow setting values that are actually present in the dropdown
9452 selected = this.dropdownWidget.getMenu().findItemFromData( value ) ||
9453 this.dropdownWidget.getMenu().findFirstSelectableItem();
9454 this.dropdownWidget.getMenu().selectItem( selected );
9455 value = selected ? selected.getData() : '';
9456 OO.ui.DropdownInputWidget.parent.prototype.setValue.call( this, value );
9457 if ( this.optionsDirty ) {
9458 // We reached this from the constructor or from #setOptions.
9459 // We have to update the <select> element.
9460 this.updateOptionsInterface();
9461 }
9462 return this;
9463 };
9464
9465 /**
9466 * @inheritdoc
9467 */
9468 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
9469 this.dropdownWidget.setDisabled( state );
9470 OO.ui.DropdownInputWidget.parent.prototype.setDisabled.call( this, state );
9471 return this;
9472 };
9473
9474 /**
9475 * Set the options available for this input.
9476 *
9477 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9478 * @chainable
9479 */
9480 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
9481 var value = this.getValue();
9482
9483 this.setOptionsData( options );
9484
9485 // Re-set the value to update the visible interface (DropdownWidget and <select>).
9486 // In case the previous value is no longer an available option, select the first valid one.
9487 this.setValue( value );
9488
9489 return this;
9490 };
9491
9492 /**
9493 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
9494 *
9495 * This method may be called before the parent constructor, so various properties may not be
9496 * intialized yet.
9497 *
9498 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9499 * @private
9500 */
9501 OO.ui.DropdownInputWidget.prototype.setOptionsData = function ( options ) {
9502 var
9503 optionWidgets,
9504 widget = this;
9505
9506 this.optionsDirty = true;
9507
9508 optionWidgets = options.map( function ( opt ) {
9509 var optValue;
9510
9511 if ( opt.optgroup !== undefined ) {
9512 return widget.createMenuSectionOptionWidget( opt.optgroup );
9513 }
9514
9515 optValue = widget.cleanUpValue( opt.data );
9516 return widget.createMenuOptionWidget(
9517 optValue,
9518 opt.label !== undefined ? opt.label : optValue
9519 );
9520
9521 } );
9522
9523 this.dropdownWidget.getMenu().clearItems().addItems( optionWidgets );
9524 };
9525
9526 /**
9527 * Create a menu option widget.
9528 *
9529 * @protected
9530 * @param {string} data Item data
9531 * @param {string} label Item label
9532 * @return {OO.ui.MenuOptionWidget} Option widget
9533 */
9534 OO.ui.DropdownInputWidget.prototype.createMenuOptionWidget = function ( data, label ) {
9535 return new OO.ui.MenuOptionWidget( {
9536 data: data,
9537 label: label
9538 } );
9539 };
9540
9541 /**
9542 * Create a menu section option widget.
9543 *
9544 * @protected
9545 * @param {string} label Section item label
9546 * @return {OO.ui.MenuSectionOptionWidget} Menu section option widget
9547 */
9548 OO.ui.DropdownInputWidget.prototype.createMenuSectionOptionWidget = function ( label ) {
9549 return new OO.ui.MenuSectionOptionWidget( {
9550 label: label
9551 } );
9552 };
9553
9554 /**
9555 * Update the user-visible interface to match the internal list of options and value.
9556 *
9557 * This method must only be called after the parent constructor.
9558 *
9559 * @private
9560 */
9561 OO.ui.DropdownInputWidget.prototype.updateOptionsInterface = function () {
9562 var
9563 $optionsContainer = this.$input,
9564 defaultValue = this.defaultValue,
9565 widget = this;
9566
9567 this.$input.empty();
9568
9569 this.dropdownWidget.getMenu().getItems().forEach( function ( optionWidget ) {
9570 var $optionNode;
9571
9572 if ( !( optionWidget instanceof OO.ui.MenuSectionOptionWidget ) ) {
9573 $optionNode = $( '<option>' )
9574 .attr( 'value', optionWidget.getData() )
9575 .text( optionWidget.getLabel() );
9576
9577 // Remember original selection state. This property can be later used to check whether
9578 // the selection state of the input has been changed since it was created.
9579 $optionNode[ 0 ].defaultSelected = ( optionWidget.getData() === defaultValue );
9580
9581 $optionsContainer.append( $optionNode );
9582 } else {
9583 $optionNode = $( '<optgroup>' )
9584 .attr( 'label', optionWidget.getLabel() );
9585 widget.$input.append( $optionNode );
9586 $optionsContainer = $optionNode;
9587 }
9588 } );
9589
9590 this.optionsDirty = false;
9591 };
9592
9593 /**
9594 * @inheritdoc
9595 */
9596 OO.ui.DropdownInputWidget.prototype.focus = function () {
9597 this.dropdownWidget.focus();
9598 return this;
9599 };
9600
9601 /**
9602 * @inheritdoc
9603 */
9604 OO.ui.DropdownInputWidget.prototype.blur = function () {
9605 this.dropdownWidget.blur();
9606 return this;
9607 };
9608
9609 /**
9610 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
9611 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
9612 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
9613 * please see the [OOUI documentation on MediaWiki][1].
9614 *
9615 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9616 *
9617 * @example
9618 * // An example of selected, unselected, and disabled radio inputs
9619 * var radio1 = new OO.ui.RadioInputWidget( {
9620 * value: 'a',
9621 * selected: true
9622 * } );
9623 * var radio2 = new OO.ui.RadioInputWidget( {
9624 * value: 'b'
9625 * } );
9626 * var radio3 = new OO.ui.RadioInputWidget( {
9627 * value: 'c',
9628 * disabled: true
9629 * } );
9630 * // Create a fieldset layout with fields for each radio button.
9631 * var fieldset = new OO.ui.FieldsetLayout( {
9632 * label: 'Radio inputs'
9633 * } );
9634 * fieldset.addItems( [
9635 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
9636 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
9637 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
9638 * ] );
9639 * $( 'body' ).append( fieldset.$element );
9640 *
9641 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9642 *
9643 * @class
9644 * @extends OO.ui.InputWidget
9645 *
9646 * @constructor
9647 * @param {Object} [config] Configuration options
9648 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
9649 */
9650 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
9651 // Configuration initialization
9652 config = config || {};
9653
9654 // Parent constructor
9655 OO.ui.RadioInputWidget.parent.call( this, config );
9656
9657 // Initialization
9658 this.$element
9659 .addClass( 'oo-ui-radioInputWidget' )
9660 // Required for pretty styling in WikimediaUI theme
9661 .append( $( '<span>' ) );
9662 this.setSelected( config.selected !== undefined ? config.selected : false );
9663 };
9664
9665 /* Setup */
9666
9667 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
9668
9669 /* Static Properties */
9670
9671 /**
9672 * @static
9673 * @inheritdoc
9674 */
9675 OO.ui.RadioInputWidget.static.tagName = 'span';
9676
9677 /* Static Methods */
9678
9679 /**
9680 * @inheritdoc
9681 */
9682 OO.ui.RadioInputWidget.static.gatherPreInfuseState = function ( node, config ) {
9683 var state = OO.ui.RadioInputWidget.parent.static.gatherPreInfuseState( node, config );
9684 state.checked = config.$input.prop( 'checked' );
9685 return state;
9686 };
9687
9688 /* Methods */
9689
9690 /**
9691 * @inheritdoc
9692 * @protected
9693 */
9694 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
9695 return $( '<input>' ).attr( 'type', 'radio' );
9696 };
9697
9698 /**
9699 * @inheritdoc
9700 */
9701 OO.ui.RadioInputWidget.prototype.onEdit = function () {
9702 // RadioInputWidget doesn't track its state.
9703 };
9704
9705 /**
9706 * Set selection state of this radio button.
9707 *
9708 * @param {boolean} state `true` for selected
9709 * @chainable
9710 */
9711 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
9712 // RadioInputWidget doesn't track its state.
9713 this.$input.prop( 'checked', state );
9714 // The first time that the selection state is set (probably while constructing the widget),
9715 // remember it in defaultSelected. This property can be later used to check whether
9716 // the selection state of the input has been changed since it was created.
9717 if ( this.defaultSelected === undefined ) {
9718 this.defaultSelected = state;
9719 this.$input[ 0 ].defaultChecked = this.defaultSelected;
9720 }
9721 return this;
9722 };
9723
9724 /**
9725 * Check if this radio button is selected.
9726 *
9727 * @return {boolean} Radio is selected
9728 */
9729 OO.ui.RadioInputWidget.prototype.isSelected = function () {
9730 return this.$input.prop( 'checked' );
9731 };
9732
9733 /**
9734 * @inheritdoc
9735 */
9736 OO.ui.RadioInputWidget.prototype.simulateLabelClick = function () {
9737 if ( !this.isDisabled() ) {
9738 this.$input.click();
9739 }
9740 this.focus();
9741 };
9742
9743 /**
9744 * @inheritdoc
9745 */
9746 OO.ui.RadioInputWidget.prototype.restorePreInfuseState = function ( state ) {
9747 OO.ui.RadioInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
9748 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
9749 this.setSelected( state.checked );
9750 }
9751 };
9752
9753 /**
9754 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
9755 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
9756 * of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9757 * more information about input widgets.
9758 *
9759 * This and OO.ui.DropdownInputWidget support the same configuration options.
9760 *
9761 * @example
9762 * // Example: A RadioSelectInputWidget with three options
9763 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
9764 * options: [
9765 * { data: 'a', label: 'First' },
9766 * { data: 'b', label: 'Second'},
9767 * { data: 'c', label: 'Third' }
9768 * ]
9769 * } );
9770 * $( 'body' ).append( radioSelectInput.$element );
9771 *
9772 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9773 *
9774 * @class
9775 * @extends OO.ui.InputWidget
9776 *
9777 * @constructor
9778 * @param {Object} [config] Configuration options
9779 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9780 */
9781 OO.ui.RadioSelectInputWidget = function OoUiRadioSelectInputWidget( config ) {
9782 // Configuration initialization
9783 config = config || {};
9784
9785 // Properties (must be done before parent constructor which calls #setDisabled)
9786 this.radioSelectWidget = new OO.ui.RadioSelectWidget();
9787 // Set up the options before parent constructor, which uses them to validate config.value.
9788 // Use this instead of setOptions() because this.$input is not set up yet
9789 this.setOptionsData( config.options || [] );
9790
9791 // Parent constructor
9792 OO.ui.RadioSelectInputWidget.parent.call( this, config );
9793
9794 // Events
9795 this.radioSelectWidget.connect( this, { select: 'onMenuSelect' } );
9796
9797 // Initialization
9798 this.$element
9799 .addClass( 'oo-ui-radioSelectInputWidget' )
9800 .append( this.radioSelectWidget.$element );
9801 this.setTabIndexedElement( this.radioSelectWidget.$tabIndexed );
9802 };
9803
9804 /* Setup */
9805
9806 OO.inheritClass( OO.ui.RadioSelectInputWidget, OO.ui.InputWidget );
9807
9808 /* Static Methods */
9809
9810 /**
9811 * @inheritdoc
9812 */
9813 OO.ui.RadioSelectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
9814 var state = OO.ui.RadioSelectInputWidget.parent.static.gatherPreInfuseState( node, config );
9815 state.value = $( node ).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
9816 return state;
9817 };
9818
9819 /**
9820 * @inheritdoc
9821 */
9822 OO.ui.RadioSelectInputWidget.static.reusePreInfuseDOM = function ( node, config ) {
9823 config = OO.ui.RadioSelectInputWidget.parent.static.reusePreInfuseDOM( node, config );
9824 // Cannot reuse the `<input type=radio>` set
9825 delete config.$input;
9826 return config;
9827 };
9828
9829 /* Methods */
9830
9831 /**
9832 * @inheritdoc
9833 * @protected
9834 */
9835 OO.ui.RadioSelectInputWidget.prototype.getInputElement = function () {
9836 // Use this instead of <input type="hidden">, because hidden inputs do not have separate
9837 // 'value' and 'defaultValue' properties, and InputWidget wants to handle 'defaultValue'.
9838 return $( '<input>' ).addClass( 'oo-ui-element-hidden' );
9839 };
9840
9841 /**
9842 * Handles menu select events.
9843 *
9844 * @private
9845 * @param {OO.ui.RadioOptionWidget} item Selected menu item
9846 */
9847 OO.ui.RadioSelectInputWidget.prototype.onMenuSelect = function ( item ) {
9848 this.setValue( item.getData() );
9849 };
9850
9851 /**
9852 * @inheritdoc
9853 */
9854 OO.ui.RadioSelectInputWidget.prototype.setValue = function ( value ) {
9855 var selected;
9856 value = this.cleanUpValue( value );
9857 // Only allow setting values that are actually present in the dropdown
9858 selected = this.radioSelectWidget.findItemFromData( value ) ||
9859 this.radioSelectWidget.findFirstSelectableItem();
9860 this.radioSelectWidget.selectItem( selected );
9861 value = selected ? selected.getData() : '';
9862 OO.ui.RadioSelectInputWidget.parent.prototype.setValue.call( this, value );
9863 return this;
9864 };
9865
9866 /**
9867 * @inheritdoc
9868 */
9869 OO.ui.RadioSelectInputWidget.prototype.setDisabled = function ( state ) {
9870 this.radioSelectWidget.setDisabled( state );
9871 OO.ui.RadioSelectInputWidget.parent.prototype.setDisabled.call( this, state );
9872 return this;
9873 };
9874
9875 /**
9876 * Set the options available for this input.
9877 *
9878 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9879 * @chainable
9880 */
9881 OO.ui.RadioSelectInputWidget.prototype.setOptions = function ( options ) {
9882 var value = this.getValue();
9883
9884 this.setOptionsData( options );
9885
9886 // Re-set the value to update the visible interface (RadioSelectWidget).
9887 // In case the previous value is no longer an available option, select the first valid one.
9888 this.setValue( value );
9889
9890 return this;
9891 };
9892
9893 /**
9894 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
9895 *
9896 * This method may be called before the parent constructor, so various properties may not be
9897 * intialized yet.
9898 *
9899 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9900 * @private
9901 */
9902 OO.ui.RadioSelectInputWidget.prototype.setOptionsData = function ( options ) {
9903 var widget = this;
9904
9905 this.radioSelectWidget
9906 .clearItems()
9907 .addItems( options.map( function ( opt ) {
9908 var optValue = widget.cleanUpValue( opt.data );
9909 return new OO.ui.RadioOptionWidget( {
9910 data: optValue,
9911 label: opt.label !== undefined ? opt.label : optValue
9912 } );
9913 } ) );
9914 };
9915
9916 /**
9917 * @inheritdoc
9918 */
9919 OO.ui.RadioSelectInputWidget.prototype.focus = function () {
9920 this.radioSelectWidget.focus();
9921 return this;
9922 };
9923
9924 /**
9925 * @inheritdoc
9926 */
9927 OO.ui.RadioSelectInputWidget.prototype.blur = function () {
9928 this.radioSelectWidget.blur();
9929 return this;
9930 };
9931
9932 /**
9933 * CheckboxMultiselectInputWidget is a
9934 * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
9935 * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
9936 * HTML `<input type=checkbox>` tags. Please see the [OOUI documentation on MediaWiki][1] for
9937 * more information about input widgets.
9938 *
9939 * @example
9940 * // Example: A CheckboxMultiselectInputWidget with three options
9941 * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
9942 * options: [
9943 * { data: 'a', label: 'First' },
9944 * { data: 'b', label: 'Second'},
9945 * { data: 'c', label: 'Third' }
9946 * ]
9947 * } );
9948 * $( 'body' ).append( multiselectInput.$element );
9949 *
9950 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9951 *
9952 * @class
9953 * @extends OO.ui.InputWidget
9954 *
9955 * @constructor
9956 * @param {Object} [config] Configuration options
9957 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: …, disabled: … }`
9958 */
9959 OO.ui.CheckboxMultiselectInputWidget = function OoUiCheckboxMultiselectInputWidget( config ) {
9960 // Configuration initialization
9961 config = config || {};
9962
9963 // Properties (must be done before parent constructor which calls #setDisabled)
9964 this.checkboxMultiselectWidget = new OO.ui.CheckboxMultiselectWidget();
9965 // Must be set before the #setOptionsData call below
9966 this.inputName = config.name;
9967 // Set up the options before parent constructor, which uses them to validate config.value.
9968 // Use this instead of setOptions() because this.$input is not set up yet
9969 this.setOptionsData( config.options || [] );
9970
9971 // Parent constructor
9972 OO.ui.CheckboxMultiselectInputWidget.parent.call( this, config );
9973
9974 // Events
9975 this.checkboxMultiselectWidget.connect( this, { select: 'onCheckboxesSelect' } );
9976
9977 // Initialization
9978 this.$element
9979 .addClass( 'oo-ui-checkboxMultiselectInputWidget' )
9980 .append( this.checkboxMultiselectWidget.$element );
9981 // We don't use this.$input, but rather the CheckboxInputWidgets inside each option
9982 this.$input.detach();
9983 };
9984
9985 /* Setup */
9986
9987 OO.inheritClass( OO.ui.CheckboxMultiselectInputWidget, OO.ui.InputWidget );
9988
9989 /* Static Methods */
9990
9991 /**
9992 * @inheritdoc
9993 */
9994 OO.ui.CheckboxMultiselectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
9995 var state = OO.ui.CheckboxMultiselectInputWidget.parent.static.gatherPreInfuseState( node, config );
9996 state.value = $( node ).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
9997 .toArray().map( function ( el ) { return el.value; } );
9998 return state;
9999 };
10000
10001 /**
10002 * @inheritdoc
10003 */
10004 OO.ui.CheckboxMultiselectInputWidget.static.reusePreInfuseDOM = function ( node, config ) {
10005 config = OO.ui.CheckboxMultiselectInputWidget.parent.static.reusePreInfuseDOM( node, config );
10006 // Cannot reuse the `<input type=checkbox>` set
10007 delete config.$input;
10008 return config;
10009 };
10010
10011 /* Methods */
10012
10013 /**
10014 * @inheritdoc
10015 * @protected
10016 */
10017 OO.ui.CheckboxMultiselectInputWidget.prototype.getInputElement = function () {
10018 // Actually unused
10019 return $( '<unused>' );
10020 };
10021
10022 /**
10023 * Handles CheckboxMultiselectWidget select events.
10024 *
10025 * @private
10026 */
10027 OO.ui.CheckboxMultiselectInputWidget.prototype.onCheckboxesSelect = function () {
10028 this.setValue( this.checkboxMultiselectWidget.findSelectedItemsData() );
10029 };
10030
10031 /**
10032 * @inheritdoc
10033 */
10034 OO.ui.CheckboxMultiselectInputWidget.prototype.getValue = function () {
10035 var value = this.$element.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
10036 .toArray().map( function ( el ) { return el.value; } );
10037 if ( this.value !== value ) {
10038 this.setValue( value );
10039 }
10040 return this.value;
10041 };
10042
10043 /**
10044 * @inheritdoc
10045 */
10046 OO.ui.CheckboxMultiselectInputWidget.prototype.setValue = function ( value ) {
10047 value = this.cleanUpValue( value );
10048 this.checkboxMultiselectWidget.selectItemsByData( value );
10049 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.setValue.call( this, value );
10050 if ( this.optionsDirty ) {
10051 // We reached this from the constructor or from #setOptions.
10052 // We have to update the <select> element.
10053 this.updateOptionsInterface();
10054 }
10055 return this;
10056 };
10057
10058 /**
10059 * Clean up incoming value.
10060 *
10061 * @param {string[]} value Original value
10062 * @return {string[]} Cleaned up value
10063 */
10064 OO.ui.CheckboxMultiselectInputWidget.prototype.cleanUpValue = function ( value ) {
10065 var i, singleValue,
10066 cleanValue = [];
10067 if ( !Array.isArray( value ) ) {
10068 return cleanValue;
10069 }
10070 for ( i = 0; i < value.length; i++ ) {
10071 singleValue =
10072 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.cleanUpValue.call( this, value[ i ] );
10073 // Remove options that we don't have here
10074 if ( !this.checkboxMultiselectWidget.findItemFromData( singleValue ) ) {
10075 continue;
10076 }
10077 cleanValue.push( singleValue );
10078 }
10079 return cleanValue;
10080 };
10081
10082 /**
10083 * @inheritdoc
10084 */
10085 OO.ui.CheckboxMultiselectInputWidget.prototype.setDisabled = function ( state ) {
10086 this.checkboxMultiselectWidget.setDisabled( state );
10087 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.setDisabled.call( this, state );
10088 return this;
10089 };
10090
10091 /**
10092 * Set the options available for this input.
10093 *
10094 * @param {Object[]} options Array of menu options in the format `{ data: …, label: …, disabled: … }`
10095 * @chainable
10096 */
10097 OO.ui.CheckboxMultiselectInputWidget.prototype.setOptions = function ( options ) {
10098 var value = this.getValue();
10099
10100 this.setOptionsData( options );
10101
10102 // Re-set the value to update the visible interface (CheckboxMultiselectWidget).
10103 // This will also get rid of any stale options that we just removed.
10104 this.setValue( value );
10105
10106 return this;
10107 };
10108
10109 /**
10110 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
10111 *
10112 * This method may be called before the parent constructor, so various properties may not be
10113 * intialized yet.
10114 *
10115 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10116 * @private
10117 */
10118 OO.ui.CheckboxMultiselectInputWidget.prototype.setOptionsData = function ( options ) {
10119 var widget = this;
10120
10121 this.optionsDirty = true;
10122
10123 this.checkboxMultiselectWidget
10124 .clearItems()
10125 .addItems( options.map( function ( opt ) {
10126 var optValue, item, optDisabled;
10127 optValue =
10128 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.cleanUpValue.call( widget, opt.data );
10129 optDisabled = opt.disabled !== undefined ? opt.disabled : false;
10130 item = new OO.ui.CheckboxMultioptionWidget( {
10131 data: optValue,
10132 label: opt.label !== undefined ? opt.label : optValue,
10133 disabled: optDisabled
10134 } );
10135 // Set the 'name' and 'value' for form submission
10136 item.checkbox.$input.attr( 'name', widget.inputName );
10137 item.checkbox.setValue( optValue );
10138 return item;
10139 } ) );
10140 };
10141
10142 /**
10143 * Update the user-visible interface to match the internal list of options and value.
10144 *
10145 * This method must only be called after the parent constructor.
10146 *
10147 * @private
10148 */
10149 OO.ui.CheckboxMultiselectInputWidget.prototype.updateOptionsInterface = function () {
10150 var defaultValue = this.defaultValue;
10151
10152 this.checkboxMultiselectWidget.getItems().forEach( function ( item ) {
10153 // Remember original selection state. This property can be later used to check whether
10154 // the selection state of the input has been changed since it was created.
10155 var isDefault = defaultValue.indexOf( item.getData() ) !== -1;
10156 item.checkbox.defaultSelected = isDefault;
10157 item.checkbox.$input[ 0 ].defaultChecked = isDefault;
10158 } );
10159
10160 this.optionsDirty = false;
10161 };
10162
10163 /**
10164 * @inheritdoc
10165 */
10166 OO.ui.CheckboxMultiselectInputWidget.prototype.focus = function () {
10167 this.checkboxMultiselectWidget.focus();
10168 return this;
10169 };
10170
10171 /**
10172 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
10173 * size of the field as well as its presentation. In addition, these widgets can be configured
10174 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
10175 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
10176 * which modifies incoming values rather than validating them.
10177 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
10178 *
10179 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
10180 *
10181 * @example
10182 * // Example of a text input widget
10183 * var textInput = new OO.ui.TextInputWidget( {
10184 * value: 'Text input'
10185 * } )
10186 * $( 'body' ).append( textInput.$element );
10187 *
10188 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
10189 *
10190 * @class
10191 * @extends OO.ui.InputWidget
10192 * @mixins OO.ui.mixin.IconElement
10193 * @mixins OO.ui.mixin.IndicatorElement
10194 * @mixins OO.ui.mixin.PendingElement
10195 * @mixins OO.ui.mixin.LabelElement
10196 *
10197 * @constructor
10198 * @param {Object} [config] Configuration options
10199 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password'
10200 * 'email', 'url' or 'number'.
10201 * @cfg {string} [placeholder] Placeholder text
10202 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
10203 * instruct the browser to focus this widget.
10204 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
10205 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
10206 *
10207 * For unfortunate historical reasons, this counts the number of UTF-16 code units rather than
10208 * Unicode codepoints, which means that codepoints outside the Basic Multilingual Plane (e.g.
10209 * many emojis) count as 2 characters each.
10210 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
10211 * the value or placeholder text: `'before'` or `'after'`
10212 * @cfg {boolean} [required=false] Mark the field as required with `true`. Implies `indicator: 'required'`.
10213 * Note that `false` & setting `indicator: 'required' will result in no indicator shown.
10214 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
10215 * @cfg {boolean} [spellcheck] Should the browser support spellcheck for this field (`undefined` means
10216 * leaving it up to the browser).
10217 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
10218 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
10219 * (the value must contain only numbers); when RegExp, a regular expression that must match the
10220 * value for it to be considered valid; when Function, a function receiving the value as parameter
10221 * that must return true, or promise resolving to true, for it to be considered valid.
10222 */
10223 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
10224 // Configuration initialization
10225 config = $.extend( {
10226 type: 'text',
10227 labelPosition: 'after'
10228 }, config );
10229
10230 // Parent constructor
10231 OO.ui.TextInputWidget.parent.call( this, config );
10232
10233 // Mixin constructors
10234 OO.ui.mixin.IconElement.call( this, config );
10235 OO.ui.mixin.IndicatorElement.call( this, config );
10236 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$input } ) );
10237 OO.ui.mixin.LabelElement.call( this, config );
10238
10239 // Properties
10240 this.type = this.getSaneType( config );
10241 this.readOnly = false;
10242 this.required = false;
10243 this.validate = null;
10244 this.styleHeight = null;
10245 this.scrollWidth = null;
10246
10247 this.setValidation( config.validate );
10248 this.setLabelPosition( config.labelPosition );
10249
10250 // Events
10251 this.$input.on( {
10252 keypress: this.onKeyPress.bind( this ),
10253 blur: this.onBlur.bind( this ),
10254 focus: this.onFocus.bind( this )
10255 } );
10256 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
10257 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
10258 this.on( 'labelChange', this.updatePosition.bind( this ) );
10259 this.on( 'change', OO.ui.debounce( this.onDebouncedChange.bind( this ), 250 ) );
10260
10261 // Initialization
10262 this.$element
10263 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type )
10264 .append( this.$icon, this.$indicator );
10265 this.setReadOnly( !!config.readOnly );
10266 this.setRequired( !!config.required );
10267 if ( config.placeholder !== undefined ) {
10268 this.$input.attr( 'placeholder', config.placeholder );
10269 }
10270 if ( config.maxLength !== undefined ) {
10271 this.$input.attr( 'maxlength', config.maxLength );
10272 }
10273 if ( config.autofocus ) {
10274 this.$input.attr( 'autofocus', 'autofocus' );
10275 }
10276 if ( config.autocomplete === false ) {
10277 this.$input.attr( 'autocomplete', 'off' );
10278 // Turning off autocompletion also disables "form caching" when the user navigates to a
10279 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
10280 $( window ).on( {
10281 beforeunload: function () {
10282 this.$input.removeAttr( 'autocomplete' );
10283 }.bind( this ),
10284 pageshow: function () {
10285 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
10286 // whole page... it shouldn't hurt, though.
10287 this.$input.attr( 'autocomplete', 'off' );
10288 }.bind( this )
10289 } );
10290 }
10291 if ( config.spellcheck !== undefined ) {
10292 this.$input.attr( 'spellcheck', config.spellcheck ? 'true' : 'false' );
10293 }
10294 if ( this.label ) {
10295 this.isWaitingToBeAttached = true;
10296 this.installParentChangeDetector();
10297 }
10298 };
10299
10300 /* Setup */
10301
10302 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
10303 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IconElement );
10304 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IndicatorElement );
10305 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.PendingElement );
10306 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.LabelElement );
10307
10308 /* Static Properties */
10309
10310 OO.ui.TextInputWidget.static.validationPatterns = {
10311 'non-empty': /.+/,
10312 integer: /^\d+$/
10313 };
10314
10315 /* Events */
10316
10317 /**
10318 * An `enter` event is emitted when the user presses 'enter' inside the text box.
10319 *
10320 * @event enter
10321 */
10322
10323 /* Methods */
10324
10325 /**
10326 * Handle icon mouse down events.
10327 *
10328 * @private
10329 * @param {jQuery.Event} e Mouse down event
10330 */
10331 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
10332 if ( e.which === OO.ui.MouseButtons.LEFT ) {
10333 this.focus();
10334 return false;
10335 }
10336 };
10337
10338 /**
10339 * Handle indicator mouse down events.
10340 *
10341 * @private
10342 * @param {jQuery.Event} e Mouse down event
10343 */
10344 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
10345 if ( e.which === OO.ui.MouseButtons.LEFT ) {
10346 this.focus();
10347 return false;
10348 }
10349 };
10350
10351 /**
10352 * Handle key press events.
10353 *
10354 * @private
10355 * @param {jQuery.Event} e Key press event
10356 * @fires enter If enter key is pressed
10357 */
10358 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
10359 if ( e.which === OO.ui.Keys.ENTER ) {
10360 this.emit( 'enter', e );
10361 }
10362 };
10363
10364 /**
10365 * Handle blur events.
10366 *
10367 * @private
10368 * @param {jQuery.Event} e Blur event
10369 */
10370 OO.ui.TextInputWidget.prototype.onBlur = function () {
10371 this.setValidityFlag();
10372 };
10373
10374 /**
10375 * Handle focus events.
10376 *
10377 * @private
10378 * @param {jQuery.Event} e Focus event
10379 */
10380 OO.ui.TextInputWidget.prototype.onFocus = function () {
10381 if ( this.isWaitingToBeAttached ) {
10382 // If we've received focus, then we must be attached to the document, and if
10383 // isWaitingToBeAttached is still true, that means the handler never fired. Fire it now.
10384 this.onElementAttach();
10385 }
10386 this.setValidityFlag( true );
10387 };
10388
10389 /**
10390 * Handle element attach events.
10391 *
10392 * @private
10393 * @param {jQuery.Event} e Element attach event
10394 */
10395 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
10396 this.isWaitingToBeAttached = false;
10397 // Any previously calculated size is now probably invalid if we reattached elsewhere
10398 this.valCache = null;
10399 this.positionLabel();
10400 };
10401
10402 /**
10403 * Handle debounced change events.
10404 *
10405 * @param {string} value
10406 * @private
10407 */
10408 OO.ui.TextInputWidget.prototype.onDebouncedChange = function () {
10409 this.setValidityFlag();
10410 };
10411
10412 /**
10413 * Check if the input is {@link #readOnly read-only}.
10414 *
10415 * @return {boolean}
10416 */
10417 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
10418 return this.readOnly;
10419 };
10420
10421 /**
10422 * Set the {@link #readOnly read-only} state of the input.
10423 *
10424 * @param {boolean} state Make input read-only
10425 * @chainable
10426 */
10427 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
10428 this.readOnly = !!state;
10429 this.$input.prop( 'readOnly', this.readOnly );
10430 return this;
10431 };
10432
10433 /**
10434 * Check if the input is {@link #required required}.
10435 *
10436 * @return {boolean}
10437 */
10438 OO.ui.TextInputWidget.prototype.isRequired = function () {
10439 return this.required;
10440 };
10441
10442 /**
10443 * Set the {@link #required required} state of the input.
10444 *
10445 * @param {boolean} state Make input required
10446 * @chainable
10447 */
10448 OO.ui.TextInputWidget.prototype.setRequired = function ( state ) {
10449 this.required = !!state;
10450 if ( this.required ) {
10451 this.$input
10452 .prop( 'required', true )
10453 .attr( 'aria-required', 'true' );
10454 if ( this.getIndicator() === null ) {
10455 this.setIndicator( 'required' );
10456 }
10457 } else {
10458 this.$input
10459 .prop( 'required', false )
10460 .removeAttr( 'aria-required' );
10461 if ( this.getIndicator() === 'required' ) {
10462 this.setIndicator( null );
10463 }
10464 }
10465 return this;
10466 };
10467
10468 /**
10469 * Support function for making #onElementAttach work across browsers.
10470 *
10471 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
10472 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
10473 *
10474 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
10475 * first time that the element gets attached to the documented.
10476 */
10477 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
10478 var mutationObserver, onRemove, topmostNode, fakeParentNode,
10479 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
10480 widget = this;
10481
10482 if ( MutationObserver ) {
10483 // The new way. If only it wasn't so ugly.
10484
10485 if ( this.isElementAttached() ) {
10486 // Widget is attached already, do nothing. This breaks the functionality of this function when
10487 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
10488 // would require observation of the whole document, which would hurt performance of other,
10489 // more important code.
10490 return;
10491 }
10492
10493 // Find topmost node in the tree
10494 topmostNode = this.$element[ 0 ];
10495 while ( topmostNode.parentNode ) {
10496 topmostNode = topmostNode.parentNode;
10497 }
10498
10499 // We have no way to detect the $element being attached somewhere without observing the entire
10500 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
10501 // parent node of $element, and instead detect when $element is removed from it (and thus
10502 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
10503 // doesn't get attached, we end up back here and create the parent.
10504
10505 mutationObserver = new MutationObserver( function ( mutations ) {
10506 var i, j, removedNodes;
10507 for ( i = 0; i < mutations.length; i++ ) {
10508 removedNodes = mutations[ i ].removedNodes;
10509 for ( j = 0; j < removedNodes.length; j++ ) {
10510 if ( removedNodes[ j ] === topmostNode ) {
10511 setTimeout( onRemove, 0 );
10512 return;
10513 }
10514 }
10515 }
10516 } );
10517
10518 onRemove = function () {
10519 // If the node was attached somewhere else, report it
10520 if ( widget.isElementAttached() ) {
10521 widget.onElementAttach();
10522 }
10523 mutationObserver.disconnect();
10524 widget.installParentChangeDetector();
10525 };
10526
10527 // Create a fake parent and observe it
10528 fakeParentNode = $( '<div>' ).append( topmostNode )[ 0 ];
10529 mutationObserver.observe( fakeParentNode, { childList: true } );
10530 } else {
10531 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
10532 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
10533 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
10534 }
10535 };
10536
10537 /**
10538 * @inheritdoc
10539 * @protected
10540 */
10541 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
10542 if ( this.getSaneType( config ) === 'number' ) {
10543 return $( '<input>' )
10544 .attr( 'step', 'any' )
10545 .attr( 'type', 'number' );
10546 } else {
10547 return $( '<input>' ).attr( 'type', this.getSaneType( config ) );
10548 }
10549 };
10550
10551 /**
10552 * Get sanitized value for 'type' for given config.
10553 *
10554 * @param {Object} config Configuration options
10555 * @return {string|null}
10556 * @protected
10557 */
10558 OO.ui.TextInputWidget.prototype.getSaneType = function ( config ) {
10559 var allowedTypes = [
10560 'text',
10561 'password',
10562 'email',
10563 'url',
10564 'number'
10565 ];
10566 return allowedTypes.indexOf( config.type ) !== -1 ? config.type : 'text';
10567 };
10568
10569 /**
10570 * Focus the input and select a specified range within the text.
10571 *
10572 * @param {number} from Select from offset
10573 * @param {number} [to] Select to offset, defaults to from
10574 * @chainable
10575 */
10576 OO.ui.TextInputWidget.prototype.selectRange = function ( from, to ) {
10577 var isBackwards, start, end,
10578 input = this.$input[ 0 ];
10579
10580 to = to || from;
10581
10582 isBackwards = to < from;
10583 start = isBackwards ? to : from;
10584 end = isBackwards ? from : to;
10585
10586 this.focus();
10587
10588 try {
10589 input.setSelectionRange( start, end, isBackwards ? 'backward' : 'forward' );
10590 } catch ( e ) {
10591 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
10592 // Rather than expensively check if the input is attached every time, just check
10593 // if it was the cause of an error being thrown. If not, rethrow the error.
10594 if ( this.getElementDocument().body.contains( input ) ) {
10595 throw e;
10596 }
10597 }
10598 return this;
10599 };
10600
10601 /**
10602 * Get an object describing the current selection range in a directional manner
10603 *
10604 * @return {Object} Object containing 'from' and 'to' offsets
10605 */
10606 OO.ui.TextInputWidget.prototype.getRange = function () {
10607 var input = this.$input[ 0 ],
10608 start = input.selectionStart,
10609 end = input.selectionEnd,
10610 isBackwards = input.selectionDirection === 'backward';
10611
10612 return {
10613 from: isBackwards ? end : start,
10614 to: isBackwards ? start : end
10615 };
10616 };
10617
10618 /**
10619 * Get the length of the text input value.
10620 *
10621 * This could differ from the length of #getValue if the
10622 * value gets filtered
10623 *
10624 * @return {number} Input length
10625 */
10626 OO.ui.TextInputWidget.prototype.getInputLength = function () {
10627 return this.$input[ 0 ].value.length;
10628 };
10629
10630 /**
10631 * Focus the input and select the entire text.
10632 *
10633 * @chainable
10634 */
10635 OO.ui.TextInputWidget.prototype.select = function () {
10636 return this.selectRange( 0, this.getInputLength() );
10637 };
10638
10639 /**
10640 * Focus the input and move the cursor to the start.
10641 *
10642 * @chainable
10643 */
10644 OO.ui.TextInputWidget.prototype.moveCursorToStart = function () {
10645 return this.selectRange( 0 );
10646 };
10647
10648 /**
10649 * Focus the input and move the cursor to the end.
10650 *
10651 * @chainable
10652 */
10653 OO.ui.TextInputWidget.prototype.moveCursorToEnd = function () {
10654 return this.selectRange( this.getInputLength() );
10655 };
10656
10657 /**
10658 * Insert new content into the input.
10659 *
10660 * @param {string} content Content to be inserted
10661 * @chainable
10662 */
10663 OO.ui.TextInputWidget.prototype.insertContent = function ( content ) {
10664 var start, end,
10665 range = this.getRange(),
10666 value = this.getValue();
10667
10668 start = Math.min( range.from, range.to );
10669 end = Math.max( range.from, range.to );
10670
10671 this.setValue( value.slice( 0, start ) + content + value.slice( end ) );
10672 this.selectRange( start + content.length );
10673 return this;
10674 };
10675
10676 /**
10677 * Insert new content either side of a selection.
10678 *
10679 * @param {string} pre Content to be inserted before the selection
10680 * @param {string} post Content to be inserted after the selection
10681 * @chainable
10682 */
10683 OO.ui.TextInputWidget.prototype.encapsulateContent = function ( pre, post ) {
10684 var start, end,
10685 range = this.getRange(),
10686 offset = pre.length;
10687
10688 start = Math.min( range.from, range.to );
10689 end = Math.max( range.from, range.to );
10690
10691 this.selectRange( start ).insertContent( pre );
10692 this.selectRange( offset + end ).insertContent( post );
10693
10694 this.selectRange( offset + start, offset + end );
10695 return this;
10696 };
10697
10698 /**
10699 * Set the validation pattern.
10700 *
10701 * The validation pattern is either a regular expression, a function, or the symbolic name of a
10702 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
10703 * value must contain only numbers).
10704 *
10705 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
10706 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
10707 */
10708 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
10709 if ( validate instanceof RegExp || validate instanceof Function ) {
10710 this.validate = validate;
10711 } else {
10712 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
10713 }
10714 };
10715
10716 /**
10717 * Sets the 'invalid' flag appropriately.
10718 *
10719 * @param {boolean} [isValid] Optionally override validation result
10720 */
10721 OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) {
10722 var widget = this,
10723 setFlag = function ( valid ) {
10724 if ( !valid ) {
10725 widget.$input.attr( 'aria-invalid', 'true' );
10726 } else {
10727 widget.$input.removeAttr( 'aria-invalid' );
10728 }
10729 widget.setFlags( { invalid: !valid } );
10730 };
10731
10732 if ( isValid !== undefined ) {
10733 setFlag( isValid );
10734 } else {
10735 this.getValidity().then( function () {
10736 setFlag( true );
10737 }, function () {
10738 setFlag( false );
10739 } );
10740 }
10741 };
10742
10743 /**
10744 * Get the validity of current value.
10745 *
10746 * This method returns a promise that resolves if the value is valid and rejects if
10747 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
10748 *
10749 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
10750 */
10751 OO.ui.TextInputWidget.prototype.getValidity = function () {
10752 var result;
10753
10754 function rejectOrResolve( valid ) {
10755 if ( valid ) {
10756 return $.Deferred().resolve().promise();
10757 } else {
10758 return $.Deferred().reject().promise();
10759 }
10760 }
10761
10762 // Check browser validity and reject if it is invalid
10763 if (
10764 this.$input[ 0 ].checkValidity !== undefined &&
10765 this.$input[ 0 ].checkValidity() === false
10766 ) {
10767 return rejectOrResolve( false );
10768 }
10769
10770 // Run our checks if the browser thinks the field is valid
10771 if ( this.validate instanceof Function ) {
10772 result = this.validate( this.getValue() );
10773 if ( result && $.isFunction( result.promise ) ) {
10774 return result.promise().then( function ( valid ) {
10775 return rejectOrResolve( valid );
10776 } );
10777 } else {
10778 return rejectOrResolve( result );
10779 }
10780 } else {
10781 return rejectOrResolve( this.getValue().match( this.validate ) );
10782 }
10783 };
10784
10785 /**
10786 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
10787 *
10788 * @param {string} labelPosition Label position, 'before' or 'after'
10789 * @chainable
10790 */
10791 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
10792 this.labelPosition = labelPosition;
10793 if ( this.label ) {
10794 // If there is no label and we only change the position, #updatePosition is a no-op,
10795 // but it takes really a lot of work to do nothing.
10796 this.updatePosition();
10797 }
10798 return this;
10799 };
10800
10801 /**
10802 * Update the position of the inline label.
10803 *
10804 * This method is called by #setLabelPosition, and can also be called on its own if
10805 * something causes the label to be mispositioned.
10806 *
10807 * @chainable
10808 */
10809 OO.ui.TextInputWidget.prototype.updatePosition = function () {
10810 var after = this.labelPosition === 'after';
10811
10812 this.$element
10813 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
10814 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
10815
10816 this.valCache = null;
10817 this.scrollWidth = null;
10818 this.positionLabel();
10819
10820 return this;
10821 };
10822
10823 /**
10824 * Position the label by setting the correct padding on the input.
10825 *
10826 * @private
10827 * @chainable
10828 */
10829 OO.ui.TextInputWidget.prototype.positionLabel = function () {
10830 var after, rtl, property, newCss;
10831
10832 if ( this.isWaitingToBeAttached ) {
10833 // #onElementAttach will be called soon, which calls this method
10834 return this;
10835 }
10836
10837 newCss = {
10838 'padding-right': '',
10839 'padding-left': ''
10840 };
10841
10842 if ( this.label ) {
10843 this.$element.append( this.$label );
10844 } else {
10845 this.$label.detach();
10846 // Clear old values if present
10847 this.$input.css( newCss );
10848 return;
10849 }
10850
10851 after = this.labelPosition === 'after';
10852 rtl = this.$element.css( 'direction' ) === 'rtl';
10853 property = after === rtl ? 'padding-left' : 'padding-right';
10854
10855 newCss[ property ] = this.$label.outerWidth( true ) + ( after ? this.scrollWidth : 0 );
10856 // We have to clear the padding on the other side, in case the element direction changed
10857 this.$input.css( newCss );
10858
10859 return this;
10860 };
10861
10862 /**
10863 * @class
10864 * @extends OO.ui.TextInputWidget
10865 *
10866 * @constructor
10867 * @param {Object} [config] Configuration options
10868 */
10869 OO.ui.SearchInputWidget = function OoUiSearchInputWidget( config ) {
10870 config = $.extend( {
10871 icon: 'search'
10872 }, config );
10873
10874 // Parent constructor
10875 OO.ui.SearchInputWidget.parent.call( this, config );
10876
10877 // Events
10878 this.connect( this, {
10879 change: 'onChange'
10880 } );
10881
10882 // Initialization
10883 this.updateSearchIndicator();
10884 this.connect( this, {
10885 disable: 'onDisable'
10886 } );
10887 };
10888
10889 /* Setup */
10890
10891 OO.inheritClass( OO.ui.SearchInputWidget, OO.ui.TextInputWidget );
10892
10893 /* Methods */
10894
10895 /**
10896 * @inheritdoc
10897 * @protected
10898 */
10899 OO.ui.SearchInputWidget.prototype.getSaneType = function () {
10900 return 'search';
10901 };
10902
10903 /**
10904 * @inheritdoc
10905 */
10906 OO.ui.SearchInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
10907 if ( e.which === OO.ui.MouseButtons.LEFT ) {
10908 // Clear the text field
10909 this.setValue( '' );
10910 this.focus();
10911 return false;
10912 }
10913 };
10914
10915 /**
10916 * Update the 'clear' indicator displayed on type: 'search' text
10917 * fields, hiding it when the field is already empty or when it's not
10918 * editable.
10919 */
10920 OO.ui.SearchInputWidget.prototype.updateSearchIndicator = function () {
10921 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
10922 this.setIndicator( null );
10923 } else {
10924 this.setIndicator( 'clear' );
10925 }
10926 };
10927
10928 /**
10929 * Handle change events.
10930 *
10931 * @private
10932 */
10933 OO.ui.SearchInputWidget.prototype.onChange = function () {
10934 this.updateSearchIndicator();
10935 };
10936
10937 /**
10938 * Handle disable events.
10939 *
10940 * @param {boolean} disabled Element is disabled
10941 * @private
10942 */
10943 OO.ui.SearchInputWidget.prototype.onDisable = function () {
10944 this.updateSearchIndicator();
10945 };
10946
10947 /**
10948 * @inheritdoc
10949 */
10950 OO.ui.SearchInputWidget.prototype.setReadOnly = function ( state ) {
10951 OO.ui.SearchInputWidget.parent.prototype.setReadOnly.call( this, state );
10952 this.updateSearchIndicator();
10953 return this;
10954 };
10955
10956 /**
10957 * @class
10958 * @extends OO.ui.TextInputWidget
10959 *
10960 * @constructor
10961 * @param {Object} [config] Configuration options
10962 * @cfg {number} [rows] Number of visible lines in textarea. If used with `autosize`,
10963 * specifies minimum number of rows to display.
10964 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
10965 * Use the #maxRows config to specify a maximum number of displayed rows.
10966 * @cfg {number} [maxRows] Maximum number of rows to display when #autosize is set to true.
10967 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
10968 */
10969 OO.ui.MultilineTextInputWidget = function OoUiMultilineTextInputWidget( config ) {
10970 config = $.extend( {
10971 type: 'text'
10972 }, config );
10973 // Parent constructor
10974 OO.ui.MultilineTextInputWidget.parent.call( this, config );
10975
10976 // Properties
10977 this.autosize = !!config.autosize;
10978 this.minRows = config.rows !== undefined ? config.rows : '';
10979 this.maxRows = config.maxRows || Math.max( 2 * ( this.minRows || 0 ), 10 );
10980
10981 // Clone for resizing
10982 if ( this.autosize ) {
10983 this.$clone = this.$input
10984 .clone()
10985 .removeAttr( 'id' )
10986 .removeAttr( 'name' )
10987 .insertAfter( this.$input )
10988 .attr( 'aria-hidden', 'true' )
10989 .addClass( 'oo-ui-element-hidden' );
10990 }
10991
10992 // Events
10993 this.connect( this, {
10994 change: 'onChange'
10995 } );
10996
10997 // Initialization
10998 if ( config.rows ) {
10999 this.$input.attr( 'rows', config.rows );
11000 }
11001 if ( this.autosize ) {
11002 this.$input.addClass( 'oo-ui-textInputWidget-autosized' );
11003 this.isWaitingToBeAttached = true;
11004 this.installParentChangeDetector();
11005 }
11006 };
11007
11008 /* Setup */
11009
11010 OO.inheritClass( OO.ui.MultilineTextInputWidget, OO.ui.TextInputWidget );
11011
11012 /* Static Methods */
11013
11014 /**
11015 * @inheritdoc
11016 */
11017 OO.ui.MultilineTextInputWidget.static.gatherPreInfuseState = function ( node, config ) {
11018 var state = OO.ui.MultilineTextInputWidget.parent.static.gatherPreInfuseState( node, config );
11019 state.scrollTop = config.$input.scrollTop();
11020 return state;
11021 };
11022
11023 /* Methods */
11024
11025 /**
11026 * @inheritdoc
11027 */
11028 OO.ui.MultilineTextInputWidget.prototype.onElementAttach = function () {
11029 OO.ui.MultilineTextInputWidget.parent.prototype.onElementAttach.call( this );
11030 this.adjustSize();
11031 };
11032
11033 /**
11034 * Handle change events.
11035 *
11036 * @private
11037 */
11038 OO.ui.MultilineTextInputWidget.prototype.onChange = function () {
11039 this.adjustSize();
11040 };
11041
11042 /**
11043 * @inheritdoc
11044 */
11045 OO.ui.MultilineTextInputWidget.prototype.updatePosition = function () {
11046 OO.ui.MultilineTextInputWidget.parent.prototype.updatePosition.call( this );
11047 this.adjustSize();
11048 };
11049
11050 /**
11051 * @inheritdoc
11052 *
11053 * Modify to emit 'enter' on Ctrl/Meta+Enter, instead of plain Enter
11054 */
11055 OO.ui.MultilineTextInputWidget.prototype.onKeyPress = function ( e ) {
11056 if (
11057 ( e.which === OO.ui.Keys.ENTER && ( e.ctrlKey || e.metaKey ) ) ||
11058 // Some platforms emit keycode 10 for ctrl+enter in a textarea
11059 e.which === 10
11060 ) {
11061 this.emit( 'enter', e );
11062 }
11063 };
11064
11065 /**
11066 * Automatically adjust the size of the text input.
11067 *
11068 * This only affects multiline inputs that are {@link #autosize autosized}.
11069 *
11070 * @chainable
11071 * @fires resize
11072 */
11073 OO.ui.MultilineTextInputWidget.prototype.adjustSize = function () {
11074 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError,
11075 idealHeight, newHeight, scrollWidth, property;
11076
11077 if ( this.$input.val() !== this.valCache ) {
11078 if ( this.autosize ) {
11079 this.$clone
11080 .val( this.$input.val() )
11081 .attr( 'rows', this.minRows )
11082 // Set inline height property to 0 to measure scroll height
11083 .css( 'height', 0 );
11084
11085 this.$clone.removeClass( 'oo-ui-element-hidden' );
11086
11087 this.valCache = this.$input.val();
11088
11089 scrollHeight = this.$clone[ 0 ].scrollHeight;
11090
11091 // Remove inline height property to measure natural heights
11092 this.$clone.css( 'height', '' );
11093 innerHeight = this.$clone.innerHeight();
11094 outerHeight = this.$clone.outerHeight();
11095
11096 // Measure max rows height
11097 this.$clone
11098 .attr( 'rows', this.maxRows )
11099 .css( 'height', 'auto' )
11100 .val( '' );
11101 maxInnerHeight = this.$clone.innerHeight();
11102
11103 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
11104 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
11105 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
11106 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
11107
11108 this.$clone.addClass( 'oo-ui-element-hidden' );
11109
11110 // Only apply inline height when expansion beyond natural height is needed
11111 // Use the difference between the inner and outer height as a buffer
11112 newHeight = idealHeight > innerHeight ? idealHeight + ( outerHeight - innerHeight ) : '';
11113 if ( newHeight !== this.styleHeight ) {
11114 this.$input.css( 'height', newHeight );
11115 this.styleHeight = newHeight;
11116 this.emit( 'resize' );
11117 }
11118 }
11119 scrollWidth = this.$input[ 0 ].offsetWidth - this.$input[ 0 ].clientWidth;
11120 if ( scrollWidth !== this.scrollWidth ) {
11121 property = this.$element.css( 'direction' ) === 'rtl' ? 'left' : 'right';
11122 // Reset
11123 this.$label.css( { right: '', left: '' } );
11124 this.$indicator.css( { right: '', left: '' } );
11125
11126 if ( scrollWidth ) {
11127 this.$indicator.css( property, scrollWidth );
11128 if ( this.labelPosition === 'after' ) {
11129 this.$label.css( property, scrollWidth );
11130 }
11131 }
11132
11133 this.scrollWidth = scrollWidth;
11134 this.positionLabel();
11135 }
11136 }
11137 return this;
11138 };
11139
11140 /**
11141 * @inheritdoc
11142 * @protected
11143 */
11144 OO.ui.MultilineTextInputWidget.prototype.getInputElement = function () {
11145 return $( '<textarea>' );
11146 };
11147
11148 /**
11149 * Check if the input automatically adjusts its size.
11150 *
11151 * @return {boolean}
11152 */
11153 OO.ui.MultilineTextInputWidget.prototype.isAutosizing = function () {
11154 return !!this.autosize;
11155 };
11156
11157 /**
11158 * @inheritdoc
11159 */
11160 OO.ui.MultilineTextInputWidget.prototype.restorePreInfuseState = function ( state ) {
11161 OO.ui.MultilineTextInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
11162 if ( state.scrollTop !== undefined ) {
11163 this.$input.scrollTop( state.scrollTop );
11164 }
11165 };
11166
11167 /**
11168 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
11169 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
11170 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
11171 *
11172 * - by typing a value in the text input field. If the value exactly matches the value of a menu
11173 * option, that option will appear to be selected.
11174 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
11175 * input field.
11176 *
11177 * After the user chooses an option, its `data` will be used as a new value for the widget.
11178 * A `label` also can be specified for each option: if given, it will be shown instead of the
11179 * `data` in the dropdown menu.
11180 *
11181 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
11182 *
11183 * For more information about menus and options, please see the [OOUI documentation on MediaWiki][1].
11184 *
11185 * @example
11186 * // Example: A ComboBoxInputWidget.
11187 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11188 * value: 'Option 1',
11189 * options: [
11190 * { data: 'Option 1' },
11191 * { data: 'Option 2' },
11192 * { data: 'Option 3' }
11193 * ]
11194 * } );
11195 * $( 'body' ).append( comboBox.$element );
11196 *
11197 * @example
11198 * // Example: A ComboBoxInputWidget with additional option labels.
11199 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11200 * value: 'Option 1',
11201 * options: [
11202 * {
11203 * data: 'Option 1',
11204 * label: 'Option One'
11205 * },
11206 * {
11207 * data: 'Option 2',
11208 * label: 'Option Two'
11209 * },
11210 * {
11211 * data: 'Option 3',
11212 * label: 'Option Three'
11213 * }
11214 * ]
11215 * } );
11216 * $( 'body' ).append( comboBox.$element );
11217 *
11218 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
11219 *
11220 * @class
11221 * @extends OO.ui.TextInputWidget
11222 *
11223 * @constructor
11224 * @param {Object} [config] Configuration options
11225 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
11226 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
11227 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
11228 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
11229 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
11230 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11231 */
11232 OO.ui.ComboBoxInputWidget = function OoUiComboBoxInputWidget( config ) {
11233 // Configuration initialization
11234 config = $.extend( {
11235 autocomplete: false
11236 }, config );
11237
11238 // ComboBoxInputWidget shouldn't support `multiline`
11239 config.multiline = false;
11240
11241 // See InputWidget#reusePreInfuseDOM about `config.$input`
11242 if ( config.$input ) {
11243 config.$input.removeAttr( 'list' );
11244 }
11245
11246 // Parent constructor
11247 OO.ui.ComboBoxInputWidget.parent.call( this, config );
11248
11249 // Properties
11250 this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
11251 this.dropdownButton = new OO.ui.ButtonWidget( {
11252 classes: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ],
11253 indicator: 'down',
11254 disabled: this.disabled
11255 } );
11256 this.menu = new OO.ui.MenuSelectWidget( $.extend(
11257 {
11258 widget: this,
11259 input: this,
11260 $floatableContainer: this.$element,
11261 disabled: this.isDisabled()
11262 },
11263 config.menu
11264 ) );
11265
11266 // Events
11267 this.connect( this, {
11268 change: 'onInputChange',
11269 enter: 'onInputEnter'
11270 } );
11271 this.dropdownButton.connect( this, {
11272 click: 'onDropdownButtonClick'
11273 } );
11274 this.menu.connect( this, {
11275 choose: 'onMenuChoose',
11276 add: 'onMenuItemsChange',
11277 remove: 'onMenuItemsChange',
11278 toggle: 'onMenuToggle'
11279 } );
11280
11281 // Initialization
11282 this.$input.attr( {
11283 role: 'combobox',
11284 'aria-owns': this.menu.getElementId(),
11285 'aria-autocomplete': 'list'
11286 } );
11287 // Do not override options set via config.menu.items
11288 if ( config.options !== undefined ) {
11289 this.setOptions( config.options );
11290 }
11291 this.$field = $( '<div>' )
11292 .addClass( 'oo-ui-comboBoxInputWidget-field' )
11293 .append( this.$input, this.dropdownButton.$element );
11294 this.$element
11295 .addClass( 'oo-ui-comboBoxInputWidget' )
11296 .append( this.$field );
11297 this.$overlay.append( this.menu.$element );
11298 this.onMenuItemsChange();
11299 };
11300
11301 /* Setup */
11302
11303 OO.inheritClass( OO.ui.ComboBoxInputWidget, OO.ui.TextInputWidget );
11304
11305 /* Methods */
11306
11307 /**
11308 * Get the combobox's menu.
11309 *
11310 * @return {OO.ui.MenuSelectWidget} Menu widget
11311 */
11312 OO.ui.ComboBoxInputWidget.prototype.getMenu = function () {
11313 return this.menu;
11314 };
11315
11316 /**
11317 * Get the combobox's text input widget.
11318 *
11319 * @return {OO.ui.TextInputWidget} Text input widget
11320 */
11321 OO.ui.ComboBoxInputWidget.prototype.getInput = function () {
11322 return this;
11323 };
11324
11325 /**
11326 * Handle input change events.
11327 *
11328 * @private
11329 * @param {string} value New value
11330 */
11331 OO.ui.ComboBoxInputWidget.prototype.onInputChange = function ( value ) {
11332 var match = this.menu.findItemFromData( value );
11333
11334 this.menu.selectItem( match );
11335 if ( this.menu.findHighlightedItem() ) {
11336 this.menu.highlightItem( match );
11337 }
11338
11339 if ( !this.isDisabled() ) {
11340 this.menu.toggle( true );
11341 }
11342 };
11343
11344 /**
11345 * Handle input enter events.
11346 *
11347 * @private
11348 */
11349 OO.ui.ComboBoxInputWidget.prototype.onInputEnter = function () {
11350 if ( !this.isDisabled() ) {
11351 this.menu.toggle( false );
11352 }
11353 };
11354
11355 /**
11356 * Handle button click events.
11357 *
11358 * @private
11359 */
11360 OO.ui.ComboBoxInputWidget.prototype.onDropdownButtonClick = function () {
11361 this.menu.toggle();
11362 this.focus();
11363 };
11364
11365 /**
11366 * Handle menu choose events.
11367 *
11368 * @private
11369 * @param {OO.ui.OptionWidget} item Chosen item
11370 */
11371 OO.ui.ComboBoxInputWidget.prototype.onMenuChoose = function ( item ) {
11372 this.setValue( item.getData() );
11373 };
11374
11375 /**
11376 * Handle menu item change events.
11377 *
11378 * @private
11379 */
11380 OO.ui.ComboBoxInputWidget.prototype.onMenuItemsChange = function () {
11381 var match = this.menu.findItemFromData( this.getValue() );
11382 this.menu.selectItem( match );
11383 if ( this.menu.findHighlightedItem() ) {
11384 this.menu.highlightItem( match );
11385 }
11386 this.$element.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu.isEmpty() );
11387 };
11388
11389 /**
11390 * Handle menu toggle events.
11391 *
11392 * @private
11393 * @param {boolean} isVisible Open state of the menu
11394 */
11395 OO.ui.ComboBoxInputWidget.prototype.onMenuToggle = function ( isVisible ) {
11396 this.$element.toggleClass( 'oo-ui-comboBoxInputWidget-open', isVisible );
11397 };
11398
11399 /**
11400 * @inheritdoc
11401 */
11402 OO.ui.ComboBoxInputWidget.prototype.setDisabled = function ( disabled ) {
11403 // Parent method
11404 OO.ui.ComboBoxInputWidget.parent.prototype.setDisabled.call( this, disabled );
11405
11406 if ( this.dropdownButton ) {
11407 this.dropdownButton.setDisabled( this.isDisabled() );
11408 }
11409 if ( this.menu ) {
11410 this.menu.setDisabled( this.isDisabled() );
11411 }
11412
11413 return this;
11414 };
11415
11416 /**
11417 * Set the options available for this input.
11418 *
11419 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
11420 * @chainable
11421 */
11422 OO.ui.ComboBoxInputWidget.prototype.setOptions = function ( options ) {
11423 this.getMenu()
11424 .clearItems()
11425 .addItems( options.map( function ( opt ) {
11426 return new OO.ui.MenuOptionWidget( {
11427 data: opt.data,
11428 label: opt.label !== undefined ? opt.label : opt.data
11429 } );
11430 } ) );
11431
11432 return this;
11433 };
11434
11435 /**
11436 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
11437 * which is a widget that is specified by reference before any optional configuration settings.
11438 *
11439 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
11440 *
11441 * - **left**: The label is placed before the field-widget and aligned with the left margin.
11442 * A left-alignment is used for forms with many fields.
11443 * - **right**: The label is placed before the field-widget and aligned to the right margin.
11444 * A right-alignment is used for long but familiar forms which users tab through,
11445 * verifying the current field with a quick glance at the label.
11446 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
11447 * that users fill out from top to bottom.
11448 * - **inline**: The label is placed after the field-widget and aligned to the left.
11449 * An inline-alignment is best used with checkboxes or radio buttons.
11450 *
11451 * Help text can either be:
11452 *
11453 * - accessed via a help icon that appears in the upper right corner of the rendered field layout, or
11454 * - shown as a subtle explanation below the label.
11455 *
11456 * If the help text is brief, or is essential to always expose it, set `helpInline` to `true`. If it
11457 * is long or not essential, leave `helpInline` to its default, `false`.
11458 *
11459 * Please see the [OOUI documentation on MediaWiki] [1] for examples and more information.
11460 *
11461 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
11462 *
11463 * @class
11464 * @extends OO.ui.Layout
11465 * @mixins OO.ui.mixin.LabelElement
11466 * @mixins OO.ui.mixin.TitledElement
11467 *
11468 * @constructor
11469 * @param {OO.ui.Widget} fieldWidget Field widget
11470 * @param {Object} [config] Configuration options
11471 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top'
11472 * or 'inline'
11473 * @cfg {Array} [errors] Error messages about the widget, which will be
11474 * displayed below the widget.
11475 * The array may contain strings or OO.ui.HtmlSnippet instances.
11476 * @cfg {Array} [notices] Notices about the widget, which will be displayed
11477 * below the widget.
11478 * The array may contain strings or OO.ui.HtmlSnippet instances.
11479 * These are more visible than `help` messages when `helpInline` is set, and so
11480 * might be good for transient messages.
11481 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified
11482 * and `helpInline` is `false`, a "help" icon will appear in the upper-right
11483 * corner of the rendered field; clicking it will display the text in a popup.
11484 * If `helpInline` is `true`, then a subtle description will be shown after the
11485 * label.
11486 * @cfg {boolean} [helpInline=false] Whether or not the help should be inline,
11487 * or shown when the "help" icon is clicked.
11488 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if
11489 * `help` is given.
11490 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11491 *
11492 * @throws {Error} An error is thrown if no widget is specified
11493 */
11494 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
11495 // Allow passing positional parameters inside the config object
11496 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
11497 config = fieldWidget;
11498 fieldWidget = config.fieldWidget;
11499 }
11500
11501 // Make sure we have required constructor arguments
11502 if ( fieldWidget === undefined ) {
11503 throw new Error( 'Widget not found' );
11504 }
11505
11506 // Configuration initialization
11507 config = $.extend( { align: 'left', helpInline: false }, config );
11508
11509 // Parent constructor
11510 OO.ui.FieldLayout.parent.call( this, config );
11511
11512 // Mixin constructors
11513 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, {
11514 $label: $( '<label>' )
11515 } ) );
11516 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
11517
11518 // Properties
11519 this.fieldWidget = fieldWidget;
11520 this.errors = [];
11521 this.notices = [];
11522 this.$field = this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
11523 this.$messages = $( '<ul>' );
11524 this.$header = $( '<span>' );
11525 this.$body = $( '<div>' );
11526 this.align = null;
11527 this.helpInline = config.helpInline;
11528
11529 // Events
11530 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
11531
11532 // Initialization
11533 this.$help = config.help ?
11534 this.createHelpElement( config.help, config.$overlay ) :
11535 $( [] );
11536 if ( this.fieldWidget.getInputId() ) {
11537 this.$label.attr( 'for', this.fieldWidget.getInputId() );
11538 if ( this.helpInline ) {
11539 this.$help.attr( 'for', this.fieldWidget.getInputId() );
11540 }
11541 } else {
11542 this.$label.on( 'click', function () {
11543 this.fieldWidget.simulateLabelClick();
11544 }.bind( this ) );
11545 if ( this.helpInline ) {
11546 this.$help.on( 'click', function () {
11547 this.fieldWidget.simulateLabelClick();
11548 }.bind( this ) );
11549 }
11550 }
11551 this.$element
11552 .addClass( 'oo-ui-fieldLayout' )
11553 .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget.isDisabled() )
11554 .append( this.$body );
11555 this.$body.addClass( 'oo-ui-fieldLayout-body' );
11556 this.$header.addClass( 'oo-ui-fieldLayout-header' );
11557 this.$messages.addClass( 'oo-ui-fieldLayout-messages' );
11558 this.$field
11559 .addClass( 'oo-ui-fieldLayout-field' )
11560 .append( this.fieldWidget.$element );
11561
11562 this.setErrors( config.errors || [] );
11563 this.setNotices( config.notices || [] );
11564 this.setAlignment( config.align );
11565 // Call this again to take into account the widget's accessKey
11566 this.updateTitle();
11567 };
11568
11569 /* Setup */
11570
11571 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
11572 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.LabelElement );
11573 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.TitledElement );
11574
11575 /* Methods */
11576
11577 /**
11578 * Handle field disable events.
11579 *
11580 * @private
11581 * @param {boolean} value Field is disabled
11582 */
11583 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
11584 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
11585 };
11586
11587 /**
11588 * Get the widget contained by the field.
11589 *
11590 * @return {OO.ui.Widget} Field widget
11591 */
11592 OO.ui.FieldLayout.prototype.getField = function () {
11593 return this.fieldWidget;
11594 };
11595
11596 /**
11597 * Return `true` if the given field widget can be used with `'inline'` alignment (see
11598 * #setAlignment). Return `false` if it can't or if this can't be determined.
11599 *
11600 * @return {boolean}
11601 */
11602 OO.ui.FieldLayout.prototype.isFieldInline = function () {
11603 // This is very simplistic, but should be good enough.
11604 return this.getField().$element.prop( 'tagName' ).toLowerCase() === 'span';
11605 };
11606
11607 /**
11608 * @protected
11609 * @param {string} kind 'error' or 'notice'
11610 * @param {string|OO.ui.HtmlSnippet} text
11611 * @return {jQuery}
11612 */
11613 OO.ui.FieldLayout.prototype.makeMessage = function ( kind, text ) {
11614 var $listItem, $icon, message;
11615 $listItem = $( '<li>' );
11616 if ( kind === 'error' ) {
11617 $icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'warning' ] } ).$element;
11618 $listItem.attr( 'role', 'alert' );
11619 } else if ( kind === 'notice' ) {
11620 $icon = new OO.ui.IconWidget( { icon: 'notice' } ).$element;
11621 } else {
11622 $icon = '';
11623 }
11624 message = new OO.ui.LabelWidget( { label: text } );
11625 $listItem
11626 .append( $icon, message.$element )
11627 .addClass( 'oo-ui-fieldLayout-messages-' + kind );
11628 return $listItem;
11629 };
11630
11631 /**
11632 * Set the field alignment mode.
11633 *
11634 * @private
11635 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
11636 * @chainable
11637 */
11638 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
11639 if ( value !== this.align ) {
11640 // Default to 'left'
11641 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
11642 value = 'left';
11643 }
11644 // Validate
11645 if ( value === 'inline' && !this.isFieldInline() ) {
11646 value = 'top';
11647 }
11648 // Reorder elements
11649
11650 if ( this.helpInline ) {
11651 if ( value === 'top' ) {
11652 this.$header.append( this.$label );
11653 this.$body.append( this.$header, this.$field, this.$help );
11654 } else if ( value === 'inline' ) {
11655 this.$header.append( this.$label, this.$help );
11656 this.$body.append( this.$field, this.$header );
11657 } else {
11658 this.$header.append( this.$label, this.$help );
11659 this.$body.append( this.$header, this.$field );
11660 }
11661 } else {
11662 if ( value === 'top' ) {
11663 this.$header.append( this.$help, this.$label );
11664 this.$body.append( this.$header, this.$field );
11665 } else if ( value === 'inline' ) {
11666 this.$header.append( this.$help, this.$label );
11667 this.$body.append( this.$field, this.$header );
11668 } else {
11669 this.$header.append( this.$label );
11670 this.$body.append( this.$header, this.$help, this.$field );
11671 }
11672 }
11673 // Set classes. The following classes can be used here:
11674 // * oo-ui-fieldLayout-align-left
11675 // * oo-ui-fieldLayout-align-right
11676 // * oo-ui-fieldLayout-align-top
11677 // * oo-ui-fieldLayout-align-inline
11678 if ( this.align ) {
11679 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
11680 }
11681 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
11682 this.align = value;
11683 }
11684
11685 return this;
11686 };
11687
11688 /**
11689 * Set the list of error messages.
11690 *
11691 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
11692 * The array may contain strings or OO.ui.HtmlSnippet instances.
11693 * @chainable
11694 */
11695 OO.ui.FieldLayout.prototype.setErrors = function ( errors ) {
11696 this.errors = errors.slice();
11697 this.updateMessages();
11698 return this;
11699 };
11700
11701 /**
11702 * Set the list of notice messages.
11703 *
11704 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
11705 * The array may contain strings or OO.ui.HtmlSnippet instances.
11706 * @chainable
11707 */
11708 OO.ui.FieldLayout.prototype.setNotices = function ( notices ) {
11709 this.notices = notices.slice();
11710 this.updateMessages();
11711 return this;
11712 };
11713
11714 /**
11715 * Update the rendering of error and notice messages.
11716 *
11717 * @private
11718 */
11719 OO.ui.FieldLayout.prototype.updateMessages = function () {
11720 var i;
11721 this.$messages.empty();
11722
11723 if ( this.errors.length || this.notices.length ) {
11724 this.$body.after( this.$messages );
11725 } else {
11726 this.$messages.remove();
11727 return;
11728 }
11729
11730 for ( i = 0; i < this.notices.length; i++ ) {
11731 this.$messages.append( this.makeMessage( 'notice', this.notices[ i ] ) );
11732 }
11733 for ( i = 0; i < this.errors.length; i++ ) {
11734 this.$messages.append( this.makeMessage( 'error', this.errors[ i ] ) );
11735 }
11736 };
11737
11738 /**
11739 * Include information about the widget's accessKey in our title. TitledElement calls this method.
11740 * (This is a bit of a hack.)
11741 *
11742 * @protected
11743 * @param {string} title Tooltip label for 'title' attribute
11744 * @return {string}
11745 */
11746 OO.ui.FieldLayout.prototype.formatTitleWithAccessKey = function ( title ) {
11747 if ( this.fieldWidget && this.fieldWidget.formatTitleWithAccessKey ) {
11748 return this.fieldWidget.formatTitleWithAccessKey( title );
11749 }
11750 return title;
11751 };
11752
11753 /**
11754 * Creates and returns the help element. Also sets the `aria-describedby`
11755 * attribute on the main element of the `fieldWidget`.
11756 *
11757 * @private
11758 * @param {string|OO.ui.HtmlSnippet} [help] Help text.
11759 * @param {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup.
11760 * @return {jQuery} The element that should become `this.$help`.
11761 */
11762 OO.ui.FieldLayout.prototype.createHelpElement = function ( help, $overlay ) {
11763 var helpId, helpWidget;
11764
11765 if ( this.helpInline ) {
11766 helpWidget = new OO.ui.LabelWidget( {
11767 label: help,
11768 classes: [ 'oo-ui-inline-help' ]
11769 } );
11770
11771 helpId = helpWidget.getElementId();
11772 } else {
11773 helpWidget = new OO.ui.PopupButtonWidget( {
11774 $overlay: $overlay,
11775 popup: {
11776 padded: true
11777 },
11778 classes: [ 'oo-ui-fieldLayout-help' ],
11779 framed: false,
11780 icon: 'info',
11781 label: OO.ui.msg( 'ooui-field-help' ),
11782 invisibleLabel: true
11783 } );
11784 if ( help instanceof OO.ui.HtmlSnippet ) {
11785 helpWidget.getPopup().$body.html( help.toString() );
11786 } else {
11787 helpWidget.getPopup().$body.text( help );
11788 }
11789
11790 helpId = helpWidget.getPopup().getBodyId();
11791 }
11792
11793 // Set the 'aria-describedby' attribute on the fieldWidget
11794 // Preference given to an input or a button
11795 (
11796 this.fieldWidget.$input ||
11797 this.fieldWidget.$button ||
11798 this.fieldWidget.$element
11799 ).attr( 'aria-describedby', helpId );
11800
11801 return helpWidget.$element;
11802 };
11803
11804 /**
11805 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
11806 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
11807 * is required and is specified before any optional configuration settings.
11808 *
11809 * Labels can be aligned in one of four ways:
11810 *
11811 * - **left**: The label is placed before the field-widget and aligned with the left margin.
11812 * A left-alignment is used for forms with many fields.
11813 * - **right**: The label is placed before the field-widget and aligned to the right margin.
11814 * A right-alignment is used for long but familiar forms which users tab through,
11815 * verifying the current field with a quick glance at the label.
11816 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
11817 * that users fill out from top to bottom.
11818 * - **inline**: The label is placed after the field-widget and aligned to the left.
11819 * An inline-alignment is best used with checkboxes or radio buttons.
11820 *
11821 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
11822 * text is specified.
11823 *
11824 * @example
11825 * // Example of an ActionFieldLayout
11826 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
11827 * new OO.ui.TextInputWidget( {
11828 * placeholder: 'Field widget'
11829 * } ),
11830 * new OO.ui.ButtonWidget( {
11831 * label: 'Button'
11832 * } ),
11833 * {
11834 * label: 'An ActionFieldLayout. This label is aligned top',
11835 * align: 'top',
11836 * help: 'This is help text'
11837 * }
11838 * );
11839 *
11840 * $( 'body' ).append( actionFieldLayout.$element );
11841 *
11842 * @class
11843 * @extends OO.ui.FieldLayout
11844 *
11845 * @constructor
11846 * @param {OO.ui.Widget} fieldWidget Field widget
11847 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
11848 * @param {Object} config
11849 */
11850 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
11851 // Allow passing positional parameters inside the config object
11852 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
11853 config = fieldWidget;
11854 fieldWidget = config.fieldWidget;
11855 buttonWidget = config.buttonWidget;
11856 }
11857
11858 // Parent constructor
11859 OO.ui.ActionFieldLayout.parent.call( this, fieldWidget, config );
11860
11861 // Properties
11862 this.buttonWidget = buttonWidget;
11863 this.$button = $( '<span>' );
11864 this.$input = this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
11865
11866 // Initialization
11867 this.$element
11868 .addClass( 'oo-ui-actionFieldLayout' );
11869 this.$button
11870 .addClass( 'oo-ui-actionFieldLayout-button' )
11871 .append( this.buttonWidget.$element );
11872 this.$input
11873 .addClass( 'oo-ui-actionFieldLayout-input' )
11874 .append( this.fieldWidget.$element );
11875 this.$field
11876 .append( this.$input, this.$button );
11877 };
11878
11879 /* Setup */
11880
11881 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
11882
11883 /**
11884 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
11885 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
11886 * configured with a label as well. For more information and examples,
11887 * please see the [OOUI documentation on MediaWiki][1].
11888 *
11889 * @example
11890 * // Example of a fieldset layout
11891 * var input1 = new OO.ui.TextInputWidget( {
11892 * placeholder: 'A text input field'
11893 * } );
11894 *
11895 * var input2 = new OO.ui.TextInputWidget( {
11896 * placeholder: 'A text input field'
11897 * } );
11898 *
11899 * var fieldset = new OO.ui.FieldsetLayout( {
11900 * label: 'Example of a fieldset layout'
11901 * } );
11902 *
11903 * fieldset.addItems( [
11904 * new OO.ui.FieldLayout( input1, {
11905 * label: 'Field One'
11906 * } ),
11907 * new OO.ui.FieldLayout( input2, {
11908 * label: 'Field Two'
11909 * } )
11910 * ] );
11911 * $( 'body' ).append( fieldset.$element );
11912 *
11913 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
11914 *
11915 * @class
11916 * @extends OO.ui.Layout
11917 * @mixins OO.ui.mixin.IconElement
11918 * @mixins OO.ui.mixin.LabelElement
11919 * @mixins OO.ui.mixin.GroupElement
11920 *
11921 * @constructor
11922 * @param {Object} [config] Configuration options
11923 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
11924 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
11925 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
11926 * For important messages, you are advised to use `notices`, as they are always shown.
11927 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
11928 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11929 */
11930 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
11931 // Configuration initialization
11932 config = config || {};
11933
11934 // Parent constructor
11935 OO.ui.FieldsetLayout.parent.call( this, config );
11936
11937 // Mixin constructors
11938 OO.ui.mixin.IconElement.call( this, config );
11939 OO.ui.mixin.LabelElement.call( this, config );
11940 OO.ui.mixin.GroupElement.call( this, config );
11941
11942 // Properties
11943 this.$header = $( '<legend>' );
11944 if ( config.help ) {
11945 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
11946 $overlay: config.$overlay,
11947 popup: {
11948 padded: true
11949 },
11950 classes: [ 'oo-ui-fieldsetLayout-help' ],
11951 framed: false,
11952 icon: 'info',
11953 label: OO.ui.msg( 'ooui-field-help' ),
11954 invisibleLabel: true
11955 } );
11956 if ( config.help instanceof OO.ui.HtmlSnippet ) {
11957 this.popupButtonWidget.getPopup().$body.html( config.help.toString() );
11958 } else {
11959 this.popupButtonWidget.getPopup().$body.text( config.help );
11960 }
11961 this.$help = this.popupButtonWidget.$element;
11962 } else {
11963 this.$help = $( [] );
11964 }
11965
11966 // Initialization
11967 this.$header
11968 .addClass( 'oo-ui-fieldsetLayout-header' )
11969 .append( this.$icon, this.$label, this.$help );
11970 this.$group.addClass( 'oo-ui-fieldsetLayout-group' );
11971 this.$element
11972 .addClass( 'oo-ui-fieldsetLayout' )
11973 .prepend( this.$header, this.$group );
11974 if ( Array.isArray( config.items ) ) {
11975 this.addItems( config.items );
11976 }
11977 };
11978
11979 /* Setup */
11980
11981 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
11982 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.IconElement );
11983 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.LabelElement );
11984 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.GroupElement );
11985
11986 /* Static Properties */
11987
11988 /**
11989 * @static
11990 * @inheritdoc
11991 */
11992 OO.ui.FieldsetLayout.static.tagName = 'fieldset';
11993
11994 /**
11995 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
11996 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
11997 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
11998 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
11999 *
12000 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
12001 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
12002 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
12003 * some fancier controls. Some controls have both regular and InputWidget variants, for example
12004 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
12005 * often have simplified APIs to match the capabilities of HTML forms.
12006 * See the [OOUI documentation on MediaWiki] [2] for more information about InputWidgets.
12007 *
12008 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Forms
12009 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
12010 *
12011 * @example
12012 * // Example of a form layout that wraps a fieldset layout
12013 * var input1 = new OO.ui.TextInputWidget( {
12014 * placeholder: 'Username'
12015 * } );
12016 * var input2 = new OO.ui.TextInputWidget( {
12017 * placeholder: 'Password',
12018 * type: 'password'
12019 * } );
12020 * var submit = new OO.ui.ButtonInputWidget( {
12021 * label: 'Submit'
12022 * } );
12023 *
12024 * var fieldset = new OO.ui.FieldsetLayout( {
12025 * label: 'A form layout'
12026 * } );
12027 * fieldset.addItems( [
12028 * new OO.ui.FieldLayout( input1, {
12029 * label: 'Username',
12030 * align: 'top'
12031 * } ),
12032 * new OO.ui.FieldLayout( input2, {
12033 * label: 'Password',
12034 * align: 'top'
12035 * } ),
12036 * new OO.ui.FieldLayout( submit )
12037 * ] );
12038 * var form = new OO.ui.FormLayout( {
12039 * items: [ fieldset ],
12040 * action: '/api/formhandler',
12041 * method: 'get'
12042 * } )
12043 * $( 'body' ).append( form.$element );
12044 *
12045 * @class
12046 * @extends OO.ui.Layout
12047 * @mixins OO.ui.mixin.GroupElement
12048 *
12049 * @constructor
12050 * @param {Object} [config] Configuration options
12051 * @cfg {string} [method] HTML form `method` attribute
12052 * @cfg {string} [action] HTML form `action` attribute
12053 * @cfg {string} [enctype] HTML form `enctype` attribute
12054 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
12055 */
12056 OO.ui.FormLayout = function OoUiFormLayout( config ) {
12057 var action;
12058
12059 // Configuration initialization
12060 config = config || {};
12061
12062 // Parent constructor
12063 OO.ui.FormLayout.parent.call( this, config );
12064
12065 // Mixin constructors
12066 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
12067
12068 // Events
12069 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
12070
12071 // Make sure the action is safe
12072 action = config.action;
12073 if ( action !== undefined && !OO.ui.isSafeUrl( action ) ) {
12074 action = './' + action;
12075 }
12076
12077 // Initialization
12078 this.$element
12079 .addClass( 'oo-ui-formLayout' )
12080 .attr( {
12081 method: config.method,
12082 action: action,
12083 enctype: config.enctype
12084 } );
12085 if ( Array.isArray( config.items ) ) {
12086 this.addItems( config.items );
12087 }
12088 };
12089
12090 /* Setup */
12091
12092 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
12093 OO.mixinClass( OO.ui.FormLayout, OO.ui.mixin.GroupElement );
12094
12095 /* Events */
12096
12097 /**
12098 * A 'submit' event is emitted when the form is submitted.
12099 *
12100 * @event submit
12101 */
12102
12103 /* Static Properties */
12104
12105 /**
12106 * @static
12107 * @inheritdoc
12108 */
12109 OO.ui.FormLayout.static.tagName = 'form';
12110
12111 /* Methods */
12112
12113 /**
12114 * Handle form submit events.
12115 *
12116 * @private
12117 * @param {jQuery.Event} e Submit event
12118 * @fires submit
12119 */
12120 OO.ui.FormLayout.prototype.onFormSubmit = function () {
12121 if ( this.emit( 'submit' ) ) {
12122 return false;
12123 }
12124 };
12125
12126 /**
12127 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
12128 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
12129 *
12130 * @example
12131 * // Example of a panel layout
12132 * var panel = new OO.ui.PanelLayout( {
12133 * expanded: false,
12134 * framed: true,
12135 * padded: true,
12136 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
12137 * } );
12138 * $( 'body' ).append( panel.$element );
12139 *
12140 * @class
12141 * @extends OO.ui.Layout
12142 *
12143 * @constructor
12144 * @param {Object} [config] Configuration options
12145 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
12146 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
12147 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
12148 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
12149 */
12150 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
12151 // Configuration initialization
12152 config = $.extend( {
12153 scrollable: false,
12154 padded: false,
12155 expanded: true,
12156 framed: false
12157 }, config );
12158
12159 // Parent constructor
12160 OO.ui.PanelLayout.parent.call( this, config );
12161
12162 // Initialization
12163 this.$element.addClass( 'oo-ui-panelLayout' );
12164 if ( config.scrollable ) {
12165 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
12166 }
12167 if ( config.padded ) {
12168 this.$element.addClass( 'oo-ui-panelLayout-padded' );
12169 }
12170 if ( config.expanded ) {
12171 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
12172 }
12173 if ( config.framed ) {
12174 this.$element.addClass( 'oo-ui-panelLayout-framed' );
12175 }
12176 };
12177
12178 /* Setup */
12179
12180 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
12181
12182 /* Methods */
12183
12184 /**
12185 * Focus the panel layout
12186 *
12187 * The default implementation just focuses the first focusable element in the panel
12188 */
12189 OO.ui.PanelLayout.prototype.focus = function () {
12190 OO.ui.findFocusable( this.$element ).focus();
12191 };
12192
12193 /**
12194 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
12195 * items), with small margins between them. Convenient when you need to put a number of block-level
12196 * widgets on a single line next to each other.
12197 *
12198 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
12199 *
12200 * @example
12201 * // HorizontalLayout with a text input and a label
12202 * var layout = new OO.ui.HorizontalLayout( {
12203 * items: [
12204 * new OO.ui.LabelWidget( { label: 'Label' } ),
12205 * new OO.ui.TextInputWidget( { value: 'Text' } )
12206 * ]
12207 * } );
12208 * $( 'body' ).append( layout.$element );
12209 *
12210 * @class
12211 * @extends OO.ui.Layout
12212 * @mixins OO.ui.mixin.GroupElement
12213 *
12214 * @constructor
12215 * @param {Object} [config] Configuration options
12216 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
12217 */
12218 OO.ui.HorizontalLayout = function OoUiHorizontalLayout( config ) {
12219 // Configuration initialization
12220 config = config || {};
12221
12222 // Parent constructor
12223 OO.ui.HorizontalLayout.parent.call( this, config );
12224
12225 // Mixin constructors
12226 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
12227
12228 // Initialization
12229 this.$element.addClass( 'oo-ui-horizontalLayout' );
12230 if ( Array.isArray( config.items ) ) {
12231 this.addItems( config.items );
12232 }
12233 };
12234
12235 /* Setup */
12236
12237 OO.inheritClass( OO.ui.HorizontalLayout, OO.ui.Layout );
12238 OO.mixinClass( OO.ui.HorizontalLayout, OO.ui.mixin.GroupElement );
12239
12240 /**
12241 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
12242 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
12243 * (to adjust the value in increments) to allow the user to enter a number.
12244 *
12245 * @example
12246 * // Example: A NumberInputWidget.
12247 * var numberInput = new OO.ui.NumberInputWidget( {
12248 * label: 'NumberInputWidget',
12249 * input: { value: 5 },
12250 * min: 1,
12251 * max: 10
12252 * } );
12253 * $( 'body' ).append( numberInput.$element );
12254 *
12255 * @class
12256 * @extends OO.ui.TextInputWidget
12257 *
12258 * @constructor
12259 * @param {Object} [config] Configuration options
12260 * @cfg {Object} [minusButton] Configuration options to pass to the
12261 * {@link OO.ui.ButtonWidget decrementing button widget}.
12262 * @cfg {Object} [plusButton] Configuration options to pass to the
12263 * {@link OO.ui.ButtonWidget incrementing button widget}.
12264 * @cfg {number} [min=-Infinity] Minimum allowed value
12265 * @cfg {number} [max=Infinity] Maximum allowed value
12266 * @cfg {number|null} [step] If specified, the field only accepts values that are multiples of this.
12267 * @cfg {number} [buttonStep=step||1] Delta when using the buttons or up/down arrow keys.
12268 * Defaults to `step` if specified, otherwise `1`.
12269 * @cfg {number} [pageStep=10*buttonStep] Delta when using the page-up/page-down keys.
12270 * Defaults to 10 times `buttonStep`.
12271 * @cfg {boolean} [showButtons=true] Whether to show the plus and minus buttons.
12272 */
12273 OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
12274 var $field = $( '<div>' )
12275 .addClass( 'oo-ui-numberInputWidget-field' );
12276
12277 // Configuration initialization
12278 config = $.extend( {
12279 min: -Infinity,
12280 max: Infinity,
12281 showButtons: true
12282 }, config );
12283
12284 // For backward compatibility
12285 $.extend( config, config.input );
12286 this.input = this;
12287
12288 // Parent constructor
12289 OO.ui.NumberInputWidget.parent.call( this, $.extend( config, {
12290 type: 'number'
12291 } ) );
12292
12293 if ( config.showButtons ) {
12294 this.minusButton = new OO.ui.ButtonWidget( $.extend(
12295 {
12296 disabled: this.isDisabled(),
12297 tabIndex: -1,
12298 classes: [ 'oo-ui-numberInputWidget-minusButton' ],
12299 icon: 'subtract'
12300 },
12301 config.minusButton
12302 ) );
12303 this.minusButton.$element.attr( 'aria-hidden', 'true' );
12304 this.plusButton = new OO.ui.ButtonWidget( $.extend(
12305 {
12306 disabled: this.isDisabled(),
12307 tabIndex: -1,
12308 classes: [ 'oo-ui-numberInputWidget-plusButton' ],
12309 icon: 'add'
12310 },
12311 config.plusButton
12312 ) );
12313 this.plusButton.$element.attr( 'aria-hidden', 'true' );
12314 }
12315
12316 // Events
12317 this.$input.on( {
12318 keydown: this.onKeyDown.bind( this ),
12319 'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
12320 } );
12321 if ( config.showButtons ) {
12322 this.plusButton.connect( this, {
12323 click: [ 'onButtonClick', +1 ]
12324 } );
12325 this.minusButton.connect( this, {
12326 click: [ 'onButtonClick', -1 ]
12327 } );
12328 }
12329
12330 // Build the field
12331 $field.append( this.$input );
12332 if ( config.showButtons ) {
12333 $field
12334 .prepend( this.minusButton.$element )
12335 .append( this.plusButton.$element );
12336 }
12337
12338 // Initialization
12339 if ( config.allowInteger || config.isInteger ) {
12340 // Backward compatibility
12341 config.step = 1;
12342 }
12343 this.setRange( config.min, config.max );
12344 this.setStep( config.buttonStep, config.pageStep, config.step );
12345 // Set the validation method after we set step and range
12346 // so that it doesn't immediately call setValidityFlag
12347 this.setValidation( this.validateNumber.bind( this ) );
12348
12349 this.$element
12350 .addClass( 'oo-ui-numberInputWidget' )
12351 .toggleClass( 'oo-ui-numberInputWidget-buttoned', config.showButtons )
12352 .append( $field );
12353 };
12354
12355 /* Setup */
12356
12357 OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.TextInputWidget );
12358
12359 /* Methods */
12360
12361 // Backward compatibility
12362 OO.ui.NumberInputWidget.prototype.setAllowInteger = function ( flag ) {
12363 this.setStep( flag ? 1 : null );
12364 };
12365 // Backward compatibility
12366 OO.ui.NumberInputWidget.prototype.setIsInteger = OO.ui.NumberInputWidget.prototype.setAllowInteger;
12367
12368 // Backward compatibility
12369 OO.ui.NumberInputWidget.prototype.getAllowInteger = function () {
12370 return this.step === 1;
12371 };
12372 // Backward compatibility
12373 OO.ui.NumberInputWidget.prototype.getIsInteger = OO.ui.NumberInputWidget.prototype.getAllowInteger;
12374
12375 /**
12376 * Set the range of allowed values
12377 *
12378 * @param {number} min Minimum allowed value
12379 * @param {number} max Maximum allowed value
12380 */
12381 OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
12382 if ( min > max ) {
12383 throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
12384 }
12385 this.min = min;
12386 this.max = max;
12387 this.$input.attr( 'min', this.min );
12388 this.$input.attr( 'max', this.max );
12389 this.setValidityFlag();
12390 };
12391
12392 /**
12393 * Get the current range
12394 *
12395 * @return {number[]} Minimum and maximum values
12396 */
12397 OO.ui.NumberInputWidget.prototype.getRange = function () {
12398 return [ this.min, this.max ];
12399 };
12400
12401 /**
12402 * Set the stepping deltas
12403 *
12404 * @param {number} [buttonStep=step||1] Delta when using the buttons or up/down arrow keys.
12405 * Defaults to `step` if specified, otherwise `1`.
12406 * @param {number} [pageStep=10*buttonStep] Delta when using the page-up/page-down keys.
12407 * Defaults to 10 times `buttonStep`.
12408 * @param {number|null} [step] If specified, the field only accepts values that are multiples of this.
12409 */
12410 OO.ui.NumberInputWidget.prototype.setStep = function ( buttonStep, pageStep, step ) {
12411 if ( buttonStep === undefined ) {
12412 buttonStep = step || 1;
12413 }
12414 if ( pageStep === undefined ) {
12415 pageStep = 10 * buttonStep;
12416 }
12417 if ( step !== null && step <= 0 ) {
12418 throw new Error( 'Step value, if given, must be positive' );
12419 }
12420 if ( buttonStep <= 0 ) {
12421 throw new Error( 'Button step value must be positive' );
12422 }
12423 if ( pageStep <= 0 ) {
12424 throw new Error( 'Page step value must be positive' );
12425 }
12426 this.step = step;
12427 this.buttonStep = buttonStep;
12428 this.pageStep = pageStep;
12429 this.$input.attr( 'step', this.step || 'any' );
12430 this.setValidityFlag();
12431 };
12432
12433 /**
12434 * @inheritdoc
12435 */
12436 OO.ui.NumberInputWidget.prototype.setValue = function ( value ) {
12437 if ( value === '' ) {
12438 // Some browsers allow a value in the input even if there isn't one reported by $input.val()
12439 // so here we make sure an 'empty' value is actually displayed as such.
12440 this.$input.val( '' );
12441 }
12442 return OO.ui.NumberInputWidget.parent.prototype.setValue.call( this, value );
12443 };
12444
12445 /**
12446 * Get the current stepping values
12447 *
12448 * @return {number[]} Button step, page step, and validity step
12449 */
12450 OO.ui.NumberInputWidget.prototype.getStep = function () {
12451 return [ this.buttonStep, this.pageStep, this.step ];
12452 };
12453
12454 /**
12455 * Get the current value of the widget as a number
12456 *
12457 * @return {number} May be NaN, or an invalid number
12458 */
12459 OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
12460 return +this.getValue();
12461 };
12462
12463 /**
12464 * Adjust the value of the widget
12465 *
12466 * @param {number} delta Adjustment amount
12467 */
12468 OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
12469 var n, v = this.getNumericValue();
12470
12471 delta = +delta;
12472 if ( isNaN( delta ) || !isFinite( delta ) ) {
12473 throw new Error( 'Delta must be a finite number' );
12474 }
12475
12476 if ( isNaN( v ) ) {
12477 n = 0;
12478 } else {
12479 n = v + delta;
12480 n = Math.max( Math.min( n, this.max ), this.min );
12481 if ( this.step ) {
12482 n = Math.round( n / this.step ) * this.step;
12483 }
12484 }
12485
12486 if ( n !== v ) {
12487 this.setValue( n );
12488 }
12489 };
12490 /**
12491 * Validate input
12492 *
12493 * @private
12494 * @param {string} value Field value
12495 * @return {boolean}
12496 */
12497 OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
12498 var n = +value;
12499 if ( value === '' ) {
12500 return !this.isRequired();
12501 }
12502
12503 if ( isNaN( n ) || !isFinite( n ) ) {
12504 return false;
12505 }
12506
12507 if ( this.step && Math.floor( n / this.step ) !== n / this.step ) {
12508 return false;
12509 }
12510
12511 if ( n < this.min || n > this.max ) {
12512 return false;
12513 }
12514
12515 return true;
12516 };
12517
12518 /**
12519 * Handle mouse click events.
12520 *
12521 * @private
12522 * @param {number} dir +1 or -1
12523 */
12524 OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
12525 this.adjustValue( dir * this.buttonStep );
12526 };
12527
12528 /**
12529 * Handle mouse wheel events.
12530 *
12531 * @private
12532 * @param {jQuery.Event} event
12533 */
12534 OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
12535 var delta = 0;
12536
12537 if ( !this.isDisabled() && this.$input.is( ':focus' ) ) {
12538 // Standard 'wheel' event
12539 if ( event.originalEvent.deltaMode !== undefined ) {
12540 this.sawWheelEvent = true;
12541 }
12542 if ( event.originalEvent.deltaY ) {
12543 delta = -event.originalEvent.deltaY;
12544 } else if ( event.originalEvent.deltaX ) {
12545 delta = event.originalEvent.deltaX;
12546 }
12547
12548 // Non-standard events
12549 if ( !this.sawWheelEvent ) {
12550 if ( event.originalEvent.wheelDeltaX ) {
12551 delta = -event.originalEvent.wheelDeltaX;
12552 } else if ( event.originalEvent.wheelDeltaY ) {
12553 delta = event.originalEvent.wheelDeltaY;
12554 } else if ( event.originalEvent.wheelDelta ) {
12555 delta = event.originalEvent.wheelDelta;
12556 } else if ( event.originalEvent.detail ) {
12557 delta = -event.originalEvent.detail;
12558 }
12559 }
12560
12561 if ( delta ) {
12562 delta = delta < 0 ? -1 : 1;
12563 this.adjustValue( delta * this.buttonStep );
12564 }
12565
12566 return false;
12567 }
12568 };
12569
12570 /**
12571 * Handle key down events.
12572 *
12573 * @private
12574 * @param {jQuery.Event} e Key down event
12575 */
12576 OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
12577 if ( !this.isDisabled() ) {
12578 switch ( e.which ) {
12579 case OO.ui.Keys.UP:
12580 this.adjustValue( this.buttonStep );
12581 return false;
12582 case OO.ui.Keys.DOWN:
12583 this.adjustValue( -this.buttonStep );
12584 return false;
12585 case OO.ui.Keys.PAGEUP:
12586 this.adjustValue( this.pageStep );
12587 return false;
12588 case OO.ui.Keys.PAGEDOWN:
12589 this.adjustValue( -this.pageStep );
12590 return false;
12591 }
12592 }
12593 };
12594
12595 /**
12596 * @inheritdoc
12597 */
12598 OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
12599 // Parent method
12600 OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
12601
12602 if ( this.minusButton ) {
12603 this.minusButton.setDisabled( this.isDisabled() );
12604 }
12605 if ( this.plusButton ) {
12606 this.plusButton.setDisabled( this.isDisabled() );
12607 }
12608
12609 return this;
12610 };
12611
12612 }( OO ) );
12613
12614 //# sourceMappingURL=oojs-ui-core.js.map.json