Merge "Set migration stage for change tag to read new"
[lhc/web/wiklou.git] / resources / lib / ooui / oojs-ui-core.js
1 /*!
2 * OOUI v0.29.5
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-08T22:38:07Z
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 * @return {OO.ui.Element} The element, for chaining
1383 */
1384 OO.ui.Element.prototype.toggle = function ( show ) {
1385 show = show === undefined ? !this.visible : !!show;
1386
1387 if ( show !== this.isVisible() ) {
1388 this.visible = show;
1389 this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
1390 this.emit( 'toggle', show );
1391 }
1392
1393 return this;
1394 };
1395
1396 /**
1397 * Check if element is visible.
1398 *
1399 * @return {boolean} element is visible
1400 */
1401 OO.ui.Element.prototype.isVisible = function () {
1402 return this.visible;
1403 };
1404
1405 /**
1406 * Get element data.
1407 *
1408 * @return {Mixed} Element data
1409 */
1410 OO.ui.Element.prototype.getData = function () {
1411 return this.data;
1412 };
1413
1414 /**
1415 * Set element data.
1416 *
1417 * @param {Mixed} data Element data
1418 * @chainable
1419 * @return {OO.ui.Element} The element, for chaining
1420 */
1421 OO.ui.Element.prototype.setData = function ( data ) {
1422 this.data = data;
1423 return this;
1424 };
1425
1426 /**
1427 * Set the element has an 'id' attribute.
1428 *
1429 * @param {string} id
1430 * @chainable
1431 * @return {OO.ui.Element} The element, for chaining
1432 */
1433 OO.ui.Element.prototype.setElementId = function ( id ) {
1434 this.elementId = id;
1435 this.$element.attr( 'id', id );
1436 return this;
1437 };
1438
1439 /**
1440 * Ensure that the element has an 'id' attribute, setting it to an unique value if it's missing,
1441 * and return its value.
1442 *
1443 * @return {string}
1444 */
1445 OO.ui.Element.prototype.getElementId = function () {
1446 if ( this.elementId === null ) {
1447 this.setElementId( OO.ui.generateElementId() );
1448 }
1449 return this.elementId;
1450 };
1451
1452 /**
1453 * Check if element supports one or more methods.
1454 *
1455 * @param {string|string[]} methods Method or list of methods to check
1456 * @return {boolean} All methods are supported
1457 */
1458 OO.ui.Element.prototype.supports = function ( methods ) {
1459 var i, len,
1460 support = 0;
1461
1462 methods = Array.isArray( methods ) ? methods : [ methods ];
1463 for ( i = 0, len = methods.length; i < len; i++ ) {
1464 if ( $.isFunction( this[ methods[ i ] ] ) ) {
1465 support++;
1466 }
1467 }
1468
1469 return methods.length === support;
1470 };
1471
1472 /**
1473 * Update the theme-provided classes.
1474 *
1475 * @localdoc This is called in element mixins and widget classes any time state changes.
1476 * Updating is debounced, minimizing overhead of changing multiple attributes and
1477 * guaranteeing that theme updates do not occur within an element's constructor
1478 */
1479 OO.ui.Element.prototype.updateThemeClasses = function () {
1480 OO.ui.theme.queueUpdateElementClasses( this );
1481 };
1482
1483 /**
1484 * Get the HTML tag name.
1485 *
1486 * Override this method to base the result on instance information.
1487 *
1488 * @return {string} HTML tag name
1489 */
1490 OO.ui.Element.prototype.getTagName = function () {
1491 return this.constructor.static.tagName;
1492 };
1493
1494 /**
1495 * Check if the element is attached to the DOM
1496 *
1497 * @return {boolean} The element is attached to the DOM
1498 */
1499 OO.ui.Element.prototype.isElementAttached = function () {
1500 return $.contains( this.getElementDocument(), this.$element[ 0 ] );
1501 };
1502
1503 /**
1504 * Get the DOM document.
1505 *
1506 * @return {HTMLDocument} Document object
1507 */
1508 OO.ui.Element.prototype.getElementDocument = function () {
1509 // Don't cache this in other ways either because subclasses could can change this.$element
1510 return OO.ui.Element.static.getDocument( this.$element );
1511 };
1512
1513 /**
1514 * Get the DOM window.
1515 *
1516 * @return {Window} Window object
1517 */
1518 OO.ui.Element.prototype.getElementWindow = function () {
1519 return OO.ui.Element.static.getWindow( this.$element );
1520 };
1521
1522 /**
1523 * Get closest scrollable container.
1524 *
1525 * @return {HTMLElement} Closest scrollable container
1526 */
1527 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1528 return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
1529 };
1530
1531 /**
1532 * Get group element is in.
1533 *
1534 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1535 */
1536 OO.ui.Element.prototype.getElementGroup = function () {
1537 return this.elementGroup;
1538 };
1539
1540 /**
1541 * Set group element is in.
1542 *
1543 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1544 * @chainable
1545 * @return {OO.ui.Element} The element, for chaining
1546 */
1547 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1548 this.elementGroup = group;
1549 return this;
1550 };
1551
1552 /**
1553 * Scroll element into view.
1554 *
1555 * @param {Object} [config] Configuration options
1556 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1557 */
1558 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
1559 if (
1560 !this.isElementAttached() ||
1561 !this.isVisible() ||
1562 ( this.getElementGroup() && !this.getElementGroup().isVisible() )
1563 ) {
1564 return $.Deferred().resolve();
1565 }
1566 return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
1567 };
1568
1569 /**
1570 * Restore the pre-infusion dynamic state for this widget.
1571 *
1572 * This method is called after #$element has been inserted into DOM. The parameter is the return
1573 * value of #gatherPreInfuseState.
1574 *
1575 * @protected
1576 * @param {Object} state
1577 */
1578 OO.ui.Element.prototype.restorePreInfuseState = function () {
1579 };
1580
1581 /**
1582 * Wraps an HTML snippet for use with configuration values which default
1583 * to strings. This bypasses the default html-escaping done to string
1584 * values.
1585 *
1586 * @class
1587 *
1588 * @constructor
1589 * @param {string} [content] HTML content
1590 */
1591 OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
1592 // Properties
1593 this.content = content;
1594 };
1595
1596 /* Setup */
1597
1598 OO.initClass( OO.ui.HtmlSnippet );
1599
1600 /* Methods */
1601
1602 /**
1603 * Render into HTML.
1604 *
1605 * @return {string} Unchanged HTML snippet.
1606 */
1607 OO.ui.HtmlSnippet.prototype.toString = function () {
1608 return this.content;
1609 };
1610
1611 /**
1612 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1613 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1614 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1615 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1616 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1617 *
1618 * @abstract
1619 * @class
1620 * @extends OO.ui.Element
1621 * @mixins OO.EventEmitter
1622 *
1623 * @constructor
1624 * @param {Object} [config] Configuration options
1625 */
1626 OO.ui.Layout = function OoUiLayout( config ) {
1627 // Configuration initialization
1628 config = config || {};
1629
1630 // Parent constructor
1631 OO.ui.Layout.parent.call( this, config );
1632
1633 // Mixin constructors
1634 OO.EventEmitter.call( this );
1635
1636 // Initialization
1637 this.$element.addClass( 'oo-ui-layout' );
1638 };
1639
1640 /* Setup */
1641
1642 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1643 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1644
1645 /* Methods */
1646
1647 /**
1648 * Reset scroll offsets
1649 *
1650 * @chainable
1651 * @return {OO.ui.Layout} The layout, for chaining
1652 */
1653 OO.ui.Layout.prototype.resetScroll = function () {
1654 this.$element[ 0 ].scrollTop = 0;
1655 // TODO: Reset scrollLeft in an RTL-aware manner, see OO.ui.Element.static.getScrollLeft.
1656
1657 return this;
1658 };
1659
1660 /**
1661 * Widgets are compositions of one or more OOUI elements that users can both view
1662 * and interact with. All widgets can be configured and modified via a standard API,
1663 * and their state can change dynamically according to a model.
1664 *
1665 * @abstract
1666 * @class
1667 * @extends OO.ui.Element
1668 * @mixins OO.EventEmitter
1669 *
1670 * @constructor
1671 * @param {Object} [config] Configuration options
1672 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1673 * appearance reflects this state.
1674 */
1675 OO.ui.Widget = function OoUiWidget( config ) {
1676 // Initialize config
1677 config = $.extend( { disabled: false }, config );
1678
1679 // Parent constructor
1680 OO.ui.Widget.parent.call( this, config );
1681
1682 // Mixin constructors
1683 OO.EventEmitter.call( this );
1684
1685 // Properties
1686 this.disabled = null;
1687 this.wasDisabled = null;
1688
1689 // Initialization
1690 this.$element.addClass( 'oo-ui-widget' );
1691 this.setDisabled( !!config.disabled );
1692 };
1693
1694 /* Setup */
1695
1696 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
1697 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
1698
1699 /* Events */
1700
1701 /**
1702 * @event disable
1703 *
1704 * A 'disable' event is emitted when the disabled state of the widget changes
1705 * (i.e. on disable **and** enable).
1706 *
1707 * @param {boolean} disabled Widget is disabled
1708 */
1709
1710 /**
1711 * @event toggle
1712 *
1713 * A 'toggle' event is emitted when the visibility of the widget changes.
1714 *
1715 * @param {boolean} visible Widget is visible
1716 */
1717
1718 /* Methods */
1719
1720 /**
1721 * Check if the widget is disabled.
1722 *
1723 * @return {boolean} Widget is disabled
1724 */
1725 OO.ui.Widget.prototype.isDisabled = function () {
1726 return this.disabled;
1727 };
1728
1729 /**
1730 * Set the 'disabled' state of the widget.
1731 *
1732 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1733 *
1734 * @param {boolean} disabled Disable widget
1735 * @chainable
1736 * @return {OO.ui.Widget} The widget, for chaining
1737 */
1738 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
1739 var isDisabled;
1740
1741 this.disabled = !!disabled;
1742 isDisabled = this.isDisabled();
1743 if ( isDisabled !== this.wasDisabled ) {
1744 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
1745 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
1746 this.$element.attr( 'aria-disabled', isDisabled.toString() );
1747 this.emit( 'disable', isDisabled );
1748 this.updateThemeClasses();
1749 }
1750 this.wasDisabled = isDisabled;
1751
1752 return this;
1753 };
1754
1755 /**
1756 * Update the disabled state, in case of changes in parent widget.
1757 *
1758 * @chainable
1759 * @return {OO.ui.Widget} The widget, for chaining
1760 */
1761 OO.ui.Widget.prototype.updateDisabled = function () {
1762 this.setDisabled( this.disabled );
1763 return this;
1764 };
1765
1766 /**
1767 * Get an ID of a labelable node which is part of this widget, if any, to be used for `<label for>`
1768 * value.
1769 *
1770 * If this function returns null, the widget should have a meaningful #simulateLabelClick method
1771 * instead.
1772 *
1773 * @return {string|null} The ID of the labelable element
1774 */
1775 OO.ui.Widget.prototype.getInputId = function () {
1776 return null;
1777 };
1778
1779 /**
1780 * Simulate the behavior of clicking on a label (a HTML `<label>` element) bound to this input.
1781 * HTML only allows `<label>` to act on specific "labelable" elements; complex widgets might need to
1782 * override this method to provide intuitive, accessible behavior.
1783 *
1784 * By default, this does nothing. OO.ui.mixin.TabIndexedElement overrides it for focusable widgets.
1785 * Individual widgets may override it too.
1786 *
1787 * This method is called by OO.ui.LabelWidget and OO.ui.FieldLayout. It should not be called
1788 * directly.
1789 */
1790 OO.ui.Widget.prototype.simulateLabelClick = function () {
1791 };
1792
1793 /**
1794 * Theme logic.
1795 *
1796 * @abstract
1797 * @class
1798 *
1799 * @constructor
1800 */
1801 OO.ui.Theme = function OoUiTheme() {
1802 this.elementClassesQueue = [];
1803 this.debouncedUpdateQueuedElementClasses = OO.ui.debounce( this.updateQueuedElementClasses );
1804 };
1805
1806 /* Setup */
1807
1808 OO.initClass( OO.ui.Theme );
1809
1810 /* Methods */
1811
1812 /**
1813 * Get a list of classes to be applied to a widget.
1814 *
1815 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
1816 * otherwise state transitions will not work properly.
1817 *
1818 * @param {OO.ui.Element} element Element for which to get classes
1819 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1820 */
1821 OO.ui.Theme.prototype.getElementClasses = function () {
1822 return { on: [], off: [] };
1823 };
1824
1825 /**
1826 * Update CSS classes provided by the theme.
1827 *
1828 * For elements with theme logic hooks, this should be called any time there's a state change.
1829 *
1830 * @param {OO.ui.Element} element Element for which to update classes
1831 */
1832 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
1833 var $elements = $( [] ),
1834 classes = this.getElementClasses( element );
1835
1836 if ( element.$icon ) {
1837 $elements = $elements.add( element.$icon );
1838 }
1839 if ( element.$indicator ) {
1840 $elements = $elements.add( element.$indicator );
1841 }
1842
1843 $elements
1844 .removeClass( classes.off )
1845 .addClass( classes.on );
1846 };
1847
1848 /**
1849 * @private
1850 */
1851 OO.ui.Theme.prototype.updateQueuedElementClasses = function () {
1852 var i;
1853 for ( i = 0; i < this.elementClassesQueue.length; i++ ) {
1854 this.updateElementClasses( this.elementClassesQueue[ i ] );
1855 }
1856 // Clear the queue
1857 this.elementClassesQueue = [];
1858 };
1859
1860 /**
1861 * Queue #updateElementClasses to be called for this element.
1862 *
1863 * @localdoc QUnit tests override this method to directly call #queueUpdateElementClasses,
1864 * to make them synchronous.
1865 *
1866 * @param {OO.ui.Element} element Element for which to update classes
1867 */
1868 OO.ui.Theme.prototype.queueUpdateElementClasses = function ( element ) {
1869 // Keep items in the queue unique. Use lastIndexOf to start checking from the end because that's
1870 // the most common case (this method is often called repeatedly for the same element).
1871 if ( this.elementClassesQueue.lastIndexOf( element ) !== -1 ) {
1872 return;
1873 }
1874 this.elementClassesQueue.push( element );
1875 this.debouncedUpdateQueuedElementClasses();
1876 };
1877
1878 /**
1879 * Get the transition duration in milliseconds for dialogs opening/closing
1880 *
1881 * The dialog should be fully rendered this many milliseconds after the
1882 * ready process has executed.
1883 *
1884 * @return {number} Transition duration in milliseconds
1885 */
1886 OO.ui.Theme.prototype.getDialogTransitionDuration = function () {
1887 return 0;
1888 };
1889
1890 /**
1891 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
1892 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
1893 * order in which users will navigate through the focusable elements via the "tab" key.
1894 *
1895 * @example
1896 * // TabIndexedElement is mixed into the ButtonWidget class
1897 * // to provide a tabIndex property.
1898 * var button1 = new OO.ui.ButtonWidget( {
1899 * label: 'fourth',
1900 * tabIndex: 4
1901 * } );
1902 * var button2 = new OO.ui.ButtonWidget( {
1903 * label: 'second',
1904 * tabIndex: 2
1905 * } );
1906 * var button3 = new OO.ui.ButtonWidget( {
1907 * label: 'third',
1908 * tabIndex: 3
1909 * } );
1910 * var button4 = new OO.ui.ButtonWidget( {
1911 * label: 'first',
1912 * tabIndex: 1
1913 * } );
1914 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
1915 *
1916 * @abstract
1917 * @class
1918 *
1919 * @constructor
1920 * @param {Object} [config] Configuration options
1921 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
1922 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
1923 * functionality will be applied to it instead.
1924 * @cfg {string|number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
1925 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
1926 * to remove the element from the tab-navigation flow.
1927 */
1928 OO.ui.mixin.TabIndexedElement = function OoUiMixinTabIndexedElement( config ) {
1929 // Configuration initialization
1930 config = $.extend( { tabIndex: 0 }, config );
1931
1932 // Properties
1933 this.$tabIndexed = null;
1934 this.tabIndex = null;
1935
1936 // Events
1937 this.connect( this, { disable: 'onTabIndexedElementDisable' } );
1938
1939 // Initialization
1940 this.setTabIndex( config.tabIndex );
1941 this.setTabIndexedElement( config.$tabIndexed || this.$element );
1942 };
1943
1944 /* Setup */
1945
1946 OO.initClass( OO.ui.mixin.TabIndexedElement );
1947
1948 /* Methods */
1949
1950 /**
1951 * Set the element that should use the tabindex functionality.
1952 *
1953 * This method is used to retarget a tabindex mixin so that its functionality applies
1954 * to the specified element. If an element is currently using the functionality, the mixin’s
1955 * effect on that element is removed before the new element is set up.
1956 *
1957 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
1958 * @chainable
1959 * @return {OO.ui.Element} The element, for chaining
1960 */
1961 OO.ui.mixin.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
1962 var tabIndex = this.tabIndex;
1963 // Remove attributes from old $tabIndexed
1964 this.setTabIndex( null );
1965 // Force update of new $tabIndexed
1966 this.$tabIndexed = $tabIndexed;
1967 this.tabIndex = tabIndex;
1968 return this.updateTabIndex();
1969 };
1970
1971 /**
1972 * Set the value of the tabindex.
1973 *
1974 * @param {string|number|null} tabIndex Tabindex value, or `null` for no tabindex
1975 * @chainable
1976 * @return {OO.ui.Element} The element, for chaining
1977 */
1978 OO.ui.mixin.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
1979 tabIndex = /^-?\d+$/.test( tabIndex ) ? Number( tabIndex ) : null;
1980
1981 if ( this.tabIndex !== tabIndex ) {
1982 this.tabIndex = tabIndex;
1983 this.updateTabIndex();
1984 }
1985
1986 return this;
1987 };
1988
1989 /**
1990 * Update the `tabindex` attribute, in case of changes to tab index or
1991 * disabled state.
1992 *
1993 * @private
1994 * @chainable
1995 * @return {OO.ui.Element} The element, for chaining
1996 */
1997 OO.ui.mixin.TabIndexedElement.prototype.updateTabIndex = function () {
1998 if ( this.$tabIndexed ) {
1999 if ( this.tabIndex !== null ) {
2000 // Do not index over disabled elements
2001 this.$tabIndexed.attr( {
2002 tabindex: this.isDisabled() ? -1 : this.tabIndex,
2003 // Support: ChromeVox and NVDA
2004 // These do not seem to inherit aria-disabled from parent elements
2005 'aria-disabled': this.isDisabled().toString()
2006 } );
2007 } else {
2008 this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
2009 }
2010 }
2011 return this;
2012 };
2013
2014 /**
2015 * Handle disable events.
2016 *
2017 * @private
2018 * @param {boolean} disabled Element is disabled
2019 */
2020 OO.ui.mixin.TabIndexedElement.prototype.onTabIndexedElementDisable = function () {
2021 this.updateTabIndex();
2022 };
2023
2024 /**
2025 * Get the value of the tabindex.
2026 *
2027 * @return {number|null} Tabindex value
2028 */
2029 OO.ui.mixin.TabIndexedElement.prototype.getTabIndex = function () {
2030 return this.tabIndex;
2031 };
2032
2033 /**
2034 * Get an ID of a focusable element of this widget, if any, to be used for `<label for>` value.
2035 *
2036 * If the element already has an ID then that is returned, otherwise unique ID is
2037 * generated, set on the element, and returned.
2038 *
2039 * @return {string|null} The ID of the focusable element
2040 */
2041 OO.ui.mixin.TabIndexedElement.prototype.getInputId = function () {
2042 var id;
2043
2044 if ( !this.$tabIndexed ) {
2045 return null;
2046 }
2047 if ( !this.isLabelableNode( this.$tabIndexed ) ) {
2048 return null;
2049 }
2050
2051 id = this.$tabIndexed.attr( 'id' );
2052 if ( id === undefined ) {
2053 id = OO.ui.generateElementId();
2054 this.$tabIndexed.attr( 'id', id );
2055 }
2056
2057 return id;
2058 };
2059
2060 /**
2061 * Whether the node is 'labelable' according to the HTML spec
2062 * (i.e., whether it can be interacted with through a `<label for="…">`).
2063 * See: <https://html.spec.whatwg.org/multipage/forms.html#category-label>.
2064 *
2065 * @private
2066 * @param {jQuery} $node
2067 * @return {boolean}
2068 */
2069 OO.ui.mixin.TabIndexedElement.prototype.isLabelableNode = function ( $node ) {
2070 var
2071 labelableTags = [ 'button', 'meter', 'output', 'progress', 'select', 'textarea' ],
2072 tagName = $node.prop( 'tagName' ).toLowerCase();
2073
2074 if ( tagName === 'input' && $node.attr( 'type' ) !== 'hidden' ) {
2075 return true;
2076 }
2077 if ( labelableTags.indexOf( tagName ) !== -1 ) {
2078 return true;
2079 }
2080 return false;
2081 };
2082
2083 /**
2084 * Focus this element.
2085 *
2086 * @chainable
2087 * @return {OO.ui.Element} The element, for chaining
2088 */
2089 OO.ui.mixin.TabIndexedElement.prototype.focus = function () {
2090 if ( !this.isDisabled() ) {
2091 this.$tabIndexed.focus();
2092 }
2093 return this;
2094 };
2095
2096 /**
2097 * Blur this element.
2098 *
2099 * @chainable
2100 * @return {OO.ui.Element} The element, for chaining
2101 */
2102 OO.ui.mixin.TabIndexedElement.prototype.blur = function () {
2103 this.$tabIndexed.blur();
2104 return this;
2105 };
2106
2107 /**
2108 * @inheritdoc OO.ui.Widget
2109 */
2110 OO.ui.mixin.TabIndexedElement.prototype.simulateLabelClick = function () {
2111 this.focus();
2112 };
2113
2114 /**
2115 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
2116 * interface element that can be configured with access keys for accessibility.
2117 * See the [OOUI documentation on MediaWiki] [1] for examples.
2118 *
2119 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches#Buttons
2120 *
2121 * @abstract
2122 * @class
2123 *
2124 * @constructor
2125 * @param {Object} [config] Configuration options
2126 * @cfg {jQuery} [$button] The button element created by the class.
2127 * If this configuration is omitted, the button element will use a generated `<a>`.
2128 * @cfg {boolean} [framed=true] Render the button with a frame
2129 */
2130 OO.ui.mixin.ButtonElement = function OoUiMixinButtonElement( config ) {
2131 // Configuration initialization
2132 config = config || {};
2133
2134 // Properties
2135 this.$button = null;
2136 this.framed = null;
2137 this.active = config.active !== undefined && config.active;
2138 this.onDocumentMouseUpHandler = this.onDocumentMouseUp.bind( this );
2139 this.onMouseDownHandler = this.onMouseDown.bind( this );
2140 this.onDocumentKeyUpHandler = this.onDocumentKeyUp.bind( this );
2141 this.onKeyDownHandler = this.onKeyDown.bind( this );
2142 this.onClickHandler = this.onClick.bind( this );
2143 this.onKeyPressHandler = this.onKeyPress.bind( this );
2144
2145 // Initialization
2146 this.$element.addClass( 'oo-ui-buttonElement' );
2147 this.toggleFramed( config.framed === undefined || config.framed );
2148 this.setButtonElement( config.$button || $( '<a>' ) );
2149 };
2150
2151 /* Setup */
2152
2153 OO.initClass( OO.ui.mixin.ButtonElement );
2154
2155 /* Static Properties */
2156
2157 /**
2158 * Cancel mouse down events.
2159 *
2160 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
2161 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
2162 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
2163 * parent widget.
2164 *
2165 * @static
2166 * @inheritable
2167 * @property {boolean}
2168 */
2169 OO.ui.mixin.ButtonElement.static.cancelButtonMouseDownEvents = true;
2170
2171 /* Events */
2172
2173 /**
2174 * A 'click' event is emitted when the button element is clicked.
2175 *
2176 * @event click
2177 */
2178
2179 /* Methods */
2180
2181 /**
2182 * Set the button element.
2183 *
2184 * This method is used to retarget a button mixin so that its functionality applies to
2185 * the specified button element instead of the one created by the class. If a button element
2186 * is already set, the method will remove the mixin’s effect on that element.
2187 *
2188 * @param {jQuery} $button Element to use as button
2189 */
2190 OO.ui.mixin.ButtonElement.prototype.setButtonElement = function ( $button ) {
2191 if ( this.$button ) {
2192 this.$button
2193 .removeClass( 'oo-ui-buttonElement-button' )
2194 .removeAttr( 'role accesskey' )
2195 .off( {
2196 mousedown: this.onMouseDownHandler,
2197 keydown: this.onKeyDownHandler,
2198 click: this.onClickHandler,
2199 keypress: this.onKeyPressHandler
2200 } );
2201 }
2202
2203 this.$button = $button
2204 .addClass( 'oo-ui-buttonElement-button' )
2205 .on( {
2206 mousedown: this.onMouseDownHandler,
2207 keydown: this.onKeyDownHandler,
2208 click: this.onClickHandler,
2209 keypress: this.onKeyPressHandler
2210 } );
2211
2212 // Add `role="button"` on `<a>` elements, where it's needed
2213 // `toUpperCase()` is added for XHTML documents
2214 if ( this.$button.prop( 'tagName' ).toUpperCase() === 'A' ) {
2215 this.$button.attr( 'role', 'button' );
2216 }
2217 };
2218
2219 /**
2220 * Handles mouse down events.
2221 *
2222 * @protected
2223 * @param {jQuery.Event} e Mouse down event
2224 * @return {undefined/boolean} False to prevent default if event is handled
2225 */
2226 OO.ui.mixin.ButtonElement.prototype.onMouseDown = function ( e ) {
2227 if ( this.isDisabled() || e.which !== OO.ui.MouseButtons.LEFT ) {
2228 return;
2229 }
2230 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
2231 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
2232 // reliably remove the pressed class
2233 this.getElementDocument().addEventListener( 'mouseup', this.onDocumentMouseUpHandler, true );
2234 // Prevent change of focus unless specifically configured otherwise
2235 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
2236 return false;
2237 }
2238 };
2239
2240 /**
2241 * Handles document mouse up events.
2242 *
2243 * @protected
2244 * @param {MouseEvent} e Mouse up event
2245 */
2246 OO.ui.mixin.ButtonElement.prototype.onDocumentMouseUp = function ( e ) {
2247 if ( this.isDisabled() || e.which !== OO.ui.MouseButtons.LEFT ) {
2248 return;
2249 }
2250 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
2251 // Stop listening for mouseup, since we only needed this once
2252 this.getElementDocument().removeEventListener( 'mouseup', this.onDocumentMouseUpHandler, true );
2253 };
2254
2255 // Deprecated alias since 0.28.3
2256 OO.ui.mixin.ButtonElement.prototype.onMouseUp = function () {
2257 OO.ui.warnDeprecation( 'onMouseUp is deprecated, use onDocumentMouseUp instead' );
2258 this.onDocumentMouseUp.apply( this, arguments );
2259 };
2260
2261 /**
2262 * Handles mouse click events.
2263 *
2264 * @protected
2265 * @param {jQuery.Event} e Mouse click event
2266 * @fires click
2267 * @return {undefined/boolean} False to prevent default if event is handled
2268 */
2269 OO.ui.mixin.ButtonElement.prototype.onClick = function ( e ) {
2270 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
2271 if ( this.emit( 'click' ) ) {
2272 return false;
2273 }
2274 }
2275 };
2276
2277 /**
2278 * Handles key down events.
2279 *
2280 * @protected
2281 * @param {jQuery.Event} e Key down event
2282 */
2283 OO.ui.mixin.ButtonElement.prototype.onKeyDown = function ( e ) {
2284 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
2285 return;
2286 }
2287 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
2288 // Run the keyup handler no matter where the key is when the button is let go, so we can
2289 // reliably remove the pressed class
2290 this.getElementDocument().addEventListener( 'keyup', this.onDocumentKeyUpHandler, true );
2291 };
2292
2293 /**
2294 * Handles document key up events.
2295 *
2296 * @protected
2297 * @param {KeyboardEvent} e Key up event
2298 */
2299 OO.ui.mixin.ButtonElement.prototype.onDocumentKeyUp = function ( e ) {
2300 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
2301 return;
2302 }
2303 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
2304 // Stop listening for keyup, since we only needed this once
2305 this.getElementDocument().removeEventListener( 'keyup', this.onDocumentKeyUpHandler, true );
2306 };
2307
2308 // Deprecated alias since 0.28.3
2309 OO.ui.mixin.ButtonElement.prototype.onKeyUp = function () {
2310 OO.ui.warnDeprecation( 'onKeyUp is deprecated, use onDocumentKeyUp instead' );
2311 this.onDocumentKeyUp.apply( this, arguments );
2312 };
2313
2314 /**
2315 * Handles key press events.
2316 *
2317 * @protected
2318 * @param {jQuery.Event} e Key press event
2319 * @fires click
2320 * @return {undefined/boolean} False to prevent default if event is handled
2321 */
2322 OO.ui.mixin.ButtonElement.prototype.onKeyPress = function ( e ) {
2323 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
2324 if ( this.emit( 'click' ) ) {
2325 return false;
2326 }
2327 }
2328 };
2329
2330 /**
2331 * Check if button has a frame.
2332 *
2333 * @return {boolean} Button is framed
2334 */
2335 OO.ui.mixin.ButtonElement.prototype.isFramed = function () {
2336 return this.framed;
2337 };
2338
2339 /**
2340 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
2341 *
2342 * @param {boolean} [framed] Make button framed, omit to toggle
2343 * @chainable
2344 * @return {OO.ui.Element} The element, for chaining
2345 */
2346 OO.ui.mixin.ButtonElement.prototype.toggleFramed = function ( framed ) {
2347 framed = framed === undefined ? !this.framed : !!framed;
2348 if ( framed !== this.framed ) {
2349 this.framed = framed;
2350 this.$element
2351 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
2352 .toggleClass( 'oo-ui-buttonElement-framed', framed );
2353 this.updateThemeClasses();
2354 }
2355
2356 return this;
2357 };
2358
2359 /**
2360 * Set the button's active state.
2361 *
2362 * The active state can be set on:
2363 *
2364 * - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected
2365 * - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on
2366 * - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page
2367 *
2368 * @protected
2369 * @param {boolean} value Make button active
2370 * @chainable
2371 * @return {OO.ui.Element} The element, for chaining
2372 */
2373 OO.ui.mixin.ButtonElement.prototype.setActive = function ( value ) {
2374 this.active = !!value;
2375 this.$element.toggleClass( 'oo-ui-buttonElement-active', this.active );
2376 this.updateThemeClasses();
2377 return this;
2378 };
2379
2380 /**
2381 * Check if the button is active
2382 *
2383 * @protected
2384 * @return {boolean} The button is active
2385 */
2386 OO.ui.mixin.ButtonElement.prototype.isActive = function () {
2387 return this.active;
2388 };
2389
2390 /**
2391 * Any OOUI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
2392 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
2393 * items from the group is done through the interface the class provides.
2394 * For more information, please see the [OOUI documentation on MediaWiki] [1].
2395 *
2396 * [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Groups
2397 *
2398 * @abstract
2399 * @mixins OO.EmitterList
2400 * @class
2401 *
2402 * @constructor
2403 * @param {Object} [config] Configuration options
2404 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
2405 * is omitted, the group element will use a generated `<div>`.
2406 */
2407 OO.ui.mixin.GroupElement = function OoUiMixinGroupElement( config ) {
2408 // Configuration initialization
2409 config = config || {};
2410
2411 // Mixin constructors
2412 OO.EmitterList.call( this, config );
2413
2414 // Properties
2415 this.$group = null;
2416
2417 // Initialization
2418 this.setGroupElement( config.$group || $( '<div>' ) );
2419 };
2420
2421 /* Setup */
2422
2423 OO.mixinClass( OO.ui.mixin.GroupElement, OO.EmitterList );
2424
2425 /* Events */
2426
2427 /**
2428 * @event change
2429 *
2430 * A change event is emitted when the set of selected items changes.
2431 *
2432 * @param {OO.ui.Element[]} items Items currently in the group
2433 */
2434
2435 /* Methods */
2436
2437 /**
2438 * Set the group element.
2439 *
2440 * If an element is already set, items will be moved to the new element.
2441 *
2442 * @param {jQuery} $group Element to use as group
2443 */
2444 OO.ui.mixin.GroupElement.prototype.setGroupElement = function ( $group ) {
2445 var i, len;
2446
2447 this.$group = $group;
2448 for ( i = 0, len = this.items.length; i < len; i++ ) {
2449 this.$group.append( this.items[ i ].$element );
2450 }
2451 };
2452
2453 /**
2454 * Find an item by its data.
2455 *
2456 * Only the first item with matching data will be returned. To return all matching items,
2457 * use the #findItemsFromData method.
2458 *
2459 * @param {Object} data Item data to search for
2460 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2461 */
2462 OO.ui.mixin.GroupElement.prototype.findItemFromData = function ( data ) {
2463 var i, len, item,
2464 hash = OO.getHash( data );
2465
2466 for ( i = 0, len = this.items.length; i < len; i++ ) {
2467 item = this.items[ i ];
2468 if ( hash === OO.getHash( item.getData() ) ) {
2469 return item;
2470 }
2471 }
2472
2473 return null;
2474 };
2475
2476 /**
2477 * Find items by their data.
2478 *
2479 * All items with matching data will be returned. To return only the first match, use the #findItemFromData method instead.
2480 *
2481 * @param {Object} data Item data to search for
2482 * @return {OO.ui.Element[]} Items with equivalent data
2483 */
2484 OO.ui.mixin.GroupElement.prototype.findItemsFromData = function ( data ) {
2485 var i, len, item,
2486 hash = OO.getHash( data ),
2487 items = [];
2488
2489 for ( i = 0, len = this.items.length; i < len; i++ ) {
2490 item = this.items[ i ];
2491 if ( hash === OO.getHash( item.getData() ) ) {
2492 items.push( item );
2493 }
2494 }
2495
2496 return items;
2497 };
2498
2499 /**
2500 * Add items to the group.
2501 *
2502 * Items will be added to the end of the group array unless the optional `index` parameter specifies
2503 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
2504 *
2505 * @param {OO.ui.Element[]} items An array of items to add to the group
2506 * @param {number} [index] Index of the insertion point
2507 * @chainable
2508 * @return {OO.ui.Element} The element, for chaining
2509 */
2510 OO.ui.mixin.GroupElement.prototype.addItems = function ( items, index ) {
2511 // Mixin method
2512 OO.EmitterList.prototype.addItems.call( this, items, index );
2513
2514 this.emit( 'change', this.getItems() );
2515 return this;
2516 };
2517
2518 /**
2519 * @inheritdoc
2520 */
2521 OO.ui.mixin.GroupElement.prototype.moveItem = function ( items, newIndex ) {
2522 // insertItemElements expects this.items to not have been modified yet, so call before the mixin
2523 this.insertItemElements( items, newIndex );
2524
2525 // Mixin method
2526 newIndex = OO.EmitterList.prototype.moveItem.call( this, items, newIndex );
2527
2528 return newIndex;
2529 };
2530
2531 /**
2532 * @inheritdoc
2533 */
2534 OO.ui.mixin.GroupElement.prototype.insertItem = function ( item, index ) {
2535 item.setElementGroup( this );
2536 this.insertItemElements( item, index );
2537
2538 // Mixin method
2539 index = OO.EmitterList.prototype.insertItem.call( this, item, index );
2540
2541 return index;
2542 };
2543
2544 /**
2545 * Insert elements into the group
2546 *
2547 * @private
2548 * @param {OO.ui.Element} itemWidget Item to insert
2549 * @param {number} index Insertion index
2550 */
2551 OO.ui.mixin.GroupElement.prototype.insertItemElements = function ( itemWidget, index ) {
2552 if ( index === undefined || index < 0 || index >= this.items.length ) {
2553 this.$group.append( itemWidget.$element );
2554 } else if ( index === 0 ) {
2555 this.$group.prepend( itemWidget.$element );
2556 } else {
2557 this.items[ index ].$element.before( itemWidget.$element );
2558 }
2559 };
2560
2561 /**
2562 * Remove the specified items from a group.
2563 *
2564 * Removed items are detached (not removed) from the DOM so that they may be reused.
2565 * To remove all items from a group, you may wish to use the #clearItems method instead.
2566 *
2567 * @param {OO.ui.Element[]} items An array of items to remove
2568 * @chainable
2569 * @return {OO.ui.Element} The element, for chaining
2570 */
2571 OO.ui.mixin.GroupElement.prototype.removeItems = function ( items ) {
2572 var i, len, item, index;
2573
2574 // Remove specific items elements
2575 for ( i = 0, len = items.length; i < len; i++ ) {
2576 item = items[ i ];
2577 index = this.items.indexOf( item );
2578 if ( index !== -1 ) {
2579 item.setElementGroup( null );
2580 item.$element.detach();
2581 }
2582 }
2583
2584 // Mixin method
2585 OO.EmitterList.prototype.removeItems.call( this, items );
2586
2587 this.emit( 'change', this.getItems() );
2588 return this;
2589 };
2590
2591 /**
2592 * Clear all items from the group.
2593 *
2594 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2595 * To remove only a subset of items from a group, use the #removeItems method.
2596 *
2597 * @chainable
2598 * @return {OO.ui.Element} The element, for chaining
2599 */
2600 OO.ui.mixin.GroupElement.prototype.clearItems = function () {
2601 var i, len;
2602
2603 // Remove all item elements
2604 for ( i = 0, len = this.items.length; i < len; i++ ) {
2605 this.items[ i ].setElementGroup( null );
2606 this.items[ i ].$element.detach();
2607 }
2608
2609 // Mixin method
2610 OO.EmitterList.prototype.clearItems.call( this );
2611
2612 this.emit( 'change', this.getItems() );
2613 return this;
2614 };
2615
2616 /**
2617 * LabelElement is often mixed into other classes to generate a label, which
2618 * helps identify the function of an interface element.
2619 * See the [OOUI documentation on MediaWiki] [1] for more information.
2620 *
2621 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
2622 *
2623 * @abstract
2624 * @class
2625 *
2626 * @constructor
2627 * @param {Object} [config] Configuration options
2628 * @cfg {jQuery} [$label] The label element created by the class. If this
2629 * configuration is omitted, the label element will use a generated `<span>`.
2630 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
2631 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
2632 * in the future. See the [OOUI documentation on MediaWiki] [2] for examples.
2633 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
2634 * @cfg {boolean} [invisibleLabel] Whether the label should be visually hidden (but still accessible
2635 * to screen-readers).
2636 */
2637 OO.ui.mixin.LabelElement = function OoUiMixinLabelElement( config ) {
2638 // Configuration initialization
2639 config = config || {};
2640
2641 // Properties
2642 this.$label = null;
2643 this.label = null;
2644 this.invisibleLabel = null;
2645
2646 // Initialization
2647 this.setLabel( config.label || this.constructor.static.label );
2648 this.setLabelElement( config.$label || $( '<span>' ) );
2649 this.setInvisibleLabel( config.invisibleLabel );
2650 };
2651
2652 /* Setup */
2653
2654 OO.initClass( OO.ui.mixin.LabelElement );
2655
2656 /* Events */
2657
2658 /**
2659 * @event labelChange
2660 * @param {string} value
2661 */
2662
2663 /* Static Properties */
2664
2665 /**
2666 * The label text. The label can be specified as a plaintext string, a function that will
2667 * produce a string in the future, or `null` for no label. The static value will
2668 * be overridden if a label is specified with the #label config option.
2669 *
2670 * @static
2671 * @inheritable
2672 * @property {string|Function|null}
2673 */
2674 OO.ui.mixin.LabelElement.static.label = null;
2675
2676 /* Static methods */
2677
2678 /**
2679 * Highlight the first occurrence of the query in the given text
2680 *
2681 * @param {string} text Text
2682 * @param {string} query Query to find
2683 * @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
2684 * @return {jQuery} Text with the first match of the query
2685 * sub-string wrapped in highlighted span
2686 */
2687 OO.ui.mixin.LabelElement.static.highlightQuery = function ( text, query, compare ) {
2688 var i, tLen, qLen,
2689 offset = -1,
2690 $result = $( '<span>' );
2691
2692 if ( compare ) {
2693 tLen = text.length;
2694 qLen = query.length;
2695 for ( i = 0; offset === -1 && i <= tLen - qLen; i++ ) {
2696 if ( compare( query, text.slice( i, i + qLen ) ) === 0 ) {
2697 offset = i;
2698 }
2699 }
2700 } else {
2701 offset = text.toLowerCase().indexOf( query.toLowerCase() );
2702 }
2703
2704 if ( !query.length || offset === -1 ) {
2705 $result.text( text );
2706 } else {
2707 $result.append(
2708 document.createTextNode( text.slice( 0, offset ) ),
2709 $( '<span>' )
2710 .addClass( 'oo-ui-labelElement-label-highlight' )
2711 .text( text.slice( offset, offset + query.length ) ),
2712 document.createTextNode( text.slice( offset + query.length ) )
2713 );
2714 }
2715 return $result.contents();
2716 };
2717
2718 /* Methods */
2719
2720 /**
2721 * Set the label element.
2722 *
2723 * If an element is already set, it will be cleaned up before setting up the new element.
2724 *
2725 * @param {jQuery} $label Element to use as label
2726 */
2727 OO.ui.mixin.LabelElement.prototype.setLabelElement = function ( $label ) {
2728 if ( this.$label ) {
2729 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
2730 }
2731
2732 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
2733 this.setLabelContent( this.label );
2734 };
2735
2736 /**
2737 * Set the label.
2738 *
2739 * An empty string will result in the label being hidden. A string containing only whitespace will
2740 * be converted to a single `&nbsp;`.
2741 *
2742 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
2743 * text; or null for no label
2744 * @chainable
2745 * @return {OO.ui.Element} The element, for chaining
2746 */
2747 OO.ui.mixin.LabelElement.prototype.setLabel = function ( label ) {
2748 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
2749 label = ( ( typeof label === 'string' || label instanceof jQuery ) && label.length ) || ( label instanceof OO.ui.HtmlSnippet && label.toString().length ) ? label : null;
2750
2751 if ( this.label !== label ) {
2752 if ( this.$label ) {
2753 this.setLabelContent( label );
2754 }
2755 this.label = label;
2756 this.emit( 'labelChange' );
2757 }
2758
2759 this.$element.toggleClass( 'oo-ui-labelElement', !!this.label && !this.invisibleLabel );
2760
2761 return this;
2762 };
2763
2764 /**
2765 * Set whether the label should be visually hidden (but still accessible to screen-readers).
2766 *
2767 * @param {boolean} invisibleLabel
2768 * @chainable
2769 * @return {OO.ui.Element} The element, for chaining
2770 */
2771 OO.ui.mixin.LabelElement.prototype.setInvisibleLabel = function ( invisibleLabel ) {
2772 invisibleLabel = !!invisibleLabel;
2773
2774 if ( this.invisibleLabel !== invisibleLabel ) {
2775 this.invisibleLabel = invisibleLabel;
2776 this.emit( 'labelChange' );
2777 }
2778
2779 this.$label.toggleClass( 'oo-ui-labelElement-invisible', this.invisibleLabel );
2780 // Pretend that there is no label, a lot of CSS has been written with this assumption
2781 this.$element.toggleClass( 'oo-ui-labelElement', !!this.label && !this.invisibleLabel );
2782
2783 return this;
2784 };
2785
2786 /**
2787 * Set the label as plain text with a highlighted query
2788 *
2789 * @param {string} text Text label to set
2790 * @param {string} query Substring of text to highlight
2791 * @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
2792 * @chainable
2793 * @return {OO.ui.Element} The element, for chaining
2794 */
2795 OO.ui.mixin.LabelElement.prototype.setHighlightedQuery = function ( text, query, compare ) {
2796 return this.setLabel( this.constructor.static.highlightQuery( text, query, compare ) );
2797 };
2798
2799 /**
2800 * Get the label.
2801 *
2802 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
2803 * text; or null for no label
2804 */
2805 OO.ui.mixin.LabelElement.prototype.getLabel = function () {
2806 return this.label;
2807 };
2808
2809 /**
2810 * Set the content of the label.
2811 *
2812 * Do not call this method until after the label element has been set by #setLabelElement.
2813 *
2814 * @private
2815 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
2816 * text; or null for no label
2817 */
2818 OO.ui.mixin.LabelElement.prototype.setLabelContent = function ( label ) {
2819 if ( typeof label === 'string' ) {
2820 if ( label.match( /^\s*$/ ) ) {
2821 // Convert whitespace only string to a single non-breaking space
2822 this.$label.html( '&nbsp;' );
2823 } else {
2824 this.$label.text( label );
2825 }
2826 } else if ( label instanceof OO.ui.HtmlSnippet ) {
2827 this.$label.html( label.toString() );
2828 } else if ( label instanceof jQuery ) {
2829 this.$label.empty().append( label );
2830 } else {
2831 this.$label.empty();
2832 }
2833 };
2834
2835 /**
2836 * IconElement is often mixed into other classes to generate an icon.
2837 * Icons are graphics, about the size of normal text. They are used to aid the user
2838 * in locating a control or to convey information in a space-efficient way. See the
2839 * [OOUI documentation on MediaWiki] [1] for a list of icons
2840 * included in the library.
2841 *
2842 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
2843 *
2844 * @abstract
2845 * @class
2846 *
2847 * @constructor
2848 * @param {Object} [config] Configuration options
2849 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2850 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2851 * the icon element be set to an existing icon instead of the one generated by this class, set a
2852 * value using a jQuery selection. For example:
2853 *
2854 * // Use a <div> tag instead of a <span>
2855 * $icon: $("<div>")
2856 * // Use an existing icon element instead of the one generated by the class
2857 * $icon: this.$element
2858 * // Use an icon element from a child widget
2859 * $icon: this.childwidget.$element
2860 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
2861 * symbolic names. A map is used for i18n purposes and contains a `default` icon
2862 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
2863 * by the user's language.
2864 *
2865 * Example of an i18n map:
2866 *
2867 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2868 * See the [OOUI documentation on MediaWiki] [2] for a list of icons included in the library.
2869 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
2870 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
2871 * text. The icon title is displayed when users move the mouse over the icon.
2872 */
2873 OO.ui.mixin.IconElement = function OoUiMixinIconElement( config ) {
2874 // Configuration initialization
2875 config = config || {};
2876
2877 // Properties
2878 this.$icon = null;
2879 this.icon = null;
2880 this.iconTitle = null;
2881
2882 // Initialization
2883 this.setIcon( config.icon || this.constructor.static.icon );
2884 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
2885 this.setIconElement( config.$icon || $( '<span>' ) );
2886 };
2887
2888 /* Setup */
2889
2890 OO.initClass( OO.ui.mixin.IconElement );
2891
2892 /* Static Properties */
2893
2894 /**
2895 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
2896 * for i18n purposes and contains a `default` icon name and additional names keyed by
2897 * language code. The `default` name is used when no icon is keyed by the user's language.
2898 *
2899 * Example of an i18n map:
2900 *
2901 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2902 *
2903 * Note: the static property will be overridden if the #icon configuration is used.
2904 *
2905 * @static
2906 * @inheritable
2907 * @property {Object|string}
2908 */
2909 OO.ui.mixin.IconElement.static.icon = null;
2910
2911 /**
2912 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2913 * function that returns title text, or `null` for no title.
2914 *
2915 * The static property will be overridden if the #iconTitle configuration is used.
2916 *
2917 * @static
2918 * @inheritable
2919 * @property {string|Function|null}
2920 */
2921 OO.ui.mixin.IconElement.static.iconTitle = null;
2922
2923 /* Methods */
2924
2925 /**
2926 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2927 * applies to the specified icon element instead of the one created by the class. If an icon
2928 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2929 * and mixin methods will no longer affect the element.
2930 *
2931 * @param {jQuery} $icon Element to use as icon
2932 */
2933 OO.ui.mixin.IconElement.prototype.setIconElement = function ( $icon ) {
2934 if ( this.$icon ) {
2935 this.$icon
2936 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
2937 .removeAttr( 'title' );
2938 }
2939
2940 this.$icon = $icon
2941 .addClass( 'oo-ui-iconElement-icon' )
2942 .toggleClass( 'oo-ui-iconElement-noIcon', !this.icon )
2943 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
2944 if ( this.iconTitle !== null ) {
2945 this.$icon.attr( 'title', this.iconTitle );
2946 }
2947
2948 this.updateThemeClasses();
2949 };
2950
2951 /**
2952 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
2953 * The icon parameter can also be set to a map of icon names. See the #icon config setting
2954 * for an example.
2955 *
2956 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
2957 * by language code, or `null` to remove the icon.
2958 * @chainable
2959 * @return {OO.ui.Element} The element, for chaining
2960 */
2961 OO.ui.mixin.IconElement.prototype.setIcon = function ( icon ) {
2962 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
2963 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
2964
2965 if ( this.icon !== icon ) {
2966 if ( this.$icon ) {
2967 if ( this.icon !== null ) {
2968 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
2969 }
2970 if ( icon !== null ) {
2971 this.$icon.addClass( 'oo-ui-icon-' + icon );
2972 }
2973 }
2974 this.icon = icon;
2975 }
2976
2977 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
2978 if ( this.$icon ) {
2979 this.$icon.toggleClass( 'oo-ui-iconElement-noIcon', !this.icon );
2980 }
2981 this.updateThemeClasses();
2982
2983 return this;
2984 };
2985
2986 /**
2987 * Set the icon title. Use `null` to remove the title.
2988 *
2989 * @param {string|Function|null} iconTitle A text string used as the icon title,
2990 * a function that returns title text, or `null` for no title.
2991 * @chainable
2992 * @return {OO.ui.Element} The element, for chaining
2993 */
2994 OO.ui.mixin.IconElement.prototype.setIconTitle = function ( iconTitle ) {
2995 iconTitle =
2996 ( typeof iconTitle === 'function' || ( typeof iconTitle === 'string' && iconTitle.length ) ) ?
2997 OO.ui.resolveMsg( iconTitle ) : null;
2998
2999 if ( this.iconTitle !== iconTitle ) {
3000 this.iconTitle = iconTitle;
3001 if ( this.$icon ) {
3002 if ( this.iconTitle !== null ) {
3003 this.$icon.attr( 'title', iconTitle );
3004 } else {
3005 this.$icon.removeAttr( 'title' );
3006 }
3007 }
3008 }
3009
3010 return this;
3011 };
3012
3013 /**
3014 * Get the symbolic name of the icon.
3015 *
3016 * @return {string} Icon name
3017 */
3018 OO.ui.mixin.IconElement.prototype.getIcon = function () {
3019 return this.icon;
3020 };
3021
3022 /**
3023 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
3024 *
3025 * @return {string} Icon title text
3026 */
3027 OO.ui.mixin.IconElement.prototype.getIconTitle = function () {
3028 return this.iconTitle;
3029 };
3030
3031 /**
3032 * IndicatorElement is often mixed into other classes to generate an indicator.
3033 * Indicators are small graphics that are generally used in two ways:
3034 *
3035 * - To draw attention to the status of an item. For example, an indicator might be
3036 * used to show that an item in a list has errors that need to be resolved.
3037 * - To clarify the function of a control that acts in an exceptional way (a button
3038 * that opens a menu instead of performing an action directly, for example).
3039 *
3040 * For a list of indicators included in the library, please see the
3041 * [OOUI documentation on MediaWiki] [1].
3042 *
3043 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3044 *
3045 * @abstract
3046 * @class
3047 *
3048 * @constructor
3049 * @param {Object} [config] Configuration options
3050 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
3051 * configuration is omitted, the indicator element will use a generated `<span>`.
3052 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3053 * See the [OOUI documentation on MediaWiki][2] for a list of indicators included
3054 * in the library.
3055 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3056 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
3057 * or a function that returns title text. The indicator title is displayed when users move
3058 * the mouse over the indicator.
3059 */
3060 OO.ui.mixin.IndicatorElement = function OoUiMixinIndicatorElement( config ) {
3061 // Configuration initialization
3062 config = config || {};
3063
3064 // Properties
3065 this.$indicator = null;
3066 this.indicator = null;
3067 this.indicatorTitle = null;
3068
3069 // Initialization
3070 this.setIndicator( config.indicator || this.constructor.static.indicator );
3071 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
3072 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
3073 };
3074
3075 /* Setup */
3076
3077 OO.initClass( OO.ui.mixin.IndicatorElement );
3078
3079 /* Static Properties */
3080
3081 /**
3082 * Symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3083 * The static property will be overridden if the #indicator configuration is used.
3084 *
3085 * @static
3086 * @inheritable
3087 * @property {string|null}
3088 */
3089 OO.ui.mixin.IndicatorElement.static.indicator = null;
3090
3091 /**
3092 * A text string used as the indicator title, a function that returns title text, or `null`
3093 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
3094 *
3095 * @static
3096 * @inheritable
3097 * @property {string|Function|null}
3098 */
3099 OO.ui.mixin.IndicatorElement.static.indicatorTitle = null;
3100
3101 /* Methods */
3102
3103 /**
3104 * Set the indicator element.
3105 *
3106 * If an element is already set, it will be cleaned up before setting up the new element.
3107 *
3108 * @param {jQuery} $indicator Element to use as indicator
3109 */
3110 OO.ui.mixin.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
3111 if ( this.$indicator ) {
3112 this.$indicator
3113 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
3114 .removeAttr( 'title' );
3115 }
3116
3117 this.$indicator = $indicator
3118 .addClass( 'oo-ui-indicatorElement-indicator' )
3119 .toggleClass( 'oo-ui-indicatorElement-noIndicator', !this.indicator )
3120 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
3121 if ( this.indicatorTitle !== null ) {
3122 this.$indicator.attr( 'title', this.indicatorTitle );
3123 }
3124
3125 this.updateThemeClasses();
3126 };
3127
3128 /**
3129 * Set the indicator by its symbolic name: ‘clear’, ‘down’, ‘required’, ‘search’, ‘up’. Use `null` to remove the indicator.
3130 *
3131 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
3132 * @chainable
3133 * @return {OO.ui.Element} The element, for chaining
3134 */
3135 OO.ui.mixin.IndicatorElement.prototype.setIndicator = function ( indicator ) {
3136 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
3137
3138 if ( this.indicator !== indicator ) {
3139 if ( this.$indicator ) {
3140 if ( this.indicator !== null ) {
3141 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
3142 }
3143 if ( indicator !== null ) {
3144 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
3145 }
3146 }
3147 this.indicator = indicator;
3148 }
3149
3150 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
3151 if ( this.$indicator ) {
3152 this.$indicator.toggleClass( 'oo-ui-indicatorElement-noIndicator', !this.indicator );
3153 }
3154 this.updateThemeClasses();
3155
3156 return this;
3157 };
3158
3159 /**
3160 * Set the indicator title.
3161 *
3162 * The title is displayed when a user moves the mouse over the indicator.
3163 *
3164 * @param {string|Function|null} indicatorTitle Indicator title text, a function that returns text, or
3165 * `null` for no indicator title
3166 * @chainable
3167 * @return {OO.ui.Element} The element, for chaining
3168 */
3169 OO.ui.mixin.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
3170 indicatorTitle =
3171 ( typeof indicatorTitle === 'function' || ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ) ?
3172 OO.ui.resolveMsg( indicatorTitle ) : null;
3173
3174 if ( this.indicatorTitle !== indicatorTitle ) {
3175 this.indicatorTitle = indicatorTitle;
3176 if ( this.$indicator ) {
3177 if ( this.indicatorTitle !== null ) {
3178 this.$indicator.attr( 'title', indicatorTitle );
3179 } else {
3180 this.$indicator.removeAttr( 'title' );
3181 }
3182 }
3183 }
3184
3185 return this;
3186 };
3187
3188 /**
3189 * Get the symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3190 *
3191 * @return {string} Symbolic name of indicator
3192 */
3193 OO.ui.mixin.IndicatorElement.prototype.getIndicator = function () {
3194 return this.indicator;
3195 };
3196
3197 /**
3198 * Get the indicator title.
3199 *
3200 * The title is displayed when a user moves the mouse over the indicator.
3201 *
3202 * @return {string} Indicator title text
3203 */
3204 OO.ui.mixin.IndicatorElement.prototype.getIndicatorTitle = function () {
3205 return this.indicatorTitle;
3206 };
3207
3208 /**
3209 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
3210 * additional functionality to an element created by another class. The class provides
3211 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
3212 * which are used to customize the look and feel of a widget to better describe its
3213 * importance and functionality.
3214 *
3215 * The library currently contains the following styling flags for general use:
3216 *
3217 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
3218 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
3219 *
3220 * The flags affect the appearance of the buttons:
3221 *
3222 * @example
3223 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
3224 * var button1 = new OO.ui.ButtonWidget( {
3225 * label: 'Progressive',
3226 * flags: 'progressive'
3227 * } );
3228 * var button2 = new OO.ui.ButtonWidget( {
3229 * label: 'Destructive',
3230 * flags: 'destructive'
3231 * } );
3232 * $( 'body' ).append( button1.$element, button2.$element );
3233 *
3234 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
3235 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
3236 *
3237 * [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
3238 *
3239 * @abstract
3240 * @class
3241 *
3242 * @constructor
3243 * @param {Object} [config] Configuration options
3244 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'progressive' or 'primary') to apply.
3245 * Please see the [OOUI documentation on MediaWiki] [2] for more information about available flags.
3246 * [2]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
3247 * @cfg {jQuery} [$flagged] The flagged element. By default,
3248 * the flagged functionality is applied to the element created by the class ($element).
3249 * If a different element is specified, the flagged functionality will be applied to it instead.
3250 */
3251 OO.ui.mixin.FlaggedElement = function OoUiMixinFlaggedElement( config ) {
3252 // Configuration initialization
3253 config = config || {};
3254
3255 // Properties
3256 this.flags = {};
3257 this.$flagged = null;
3258
3259 // Initialization
3260 this.setFlags( config.flags );
3261 this.setFlaggedElement( config.$flagged || this.$element );
3262 };
3263
3264 /* Events */
3265
3266 /**
3267 * @event flag
3268 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
3269 * parameter contains the name of each modified flag and indicates whether it was
3270 * added or removed.
3271 *
3272 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
3273 * that the flag was added, `false` that the flag was removed.
3274 */
3275
3276 /* Methods */
3277
3278 /**
3279 * Set the flagged element.
3280 *
3281 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
3282 * If an element is already set, the method will remove the mixin’s effect on that element.
3283 *
3284 * @param {jQuery} $flagged Element that should be flagged
3285 */
3286 OO.ui.mixin.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
3287 var classNames = Object.keys( this.flags ).map( function ( flag ) {
3288 return 'oo-ui-flaggedElement-' + flag;
3289 } );
3290
3291 if ( this.$flagged ) {
3292 this.$flagged.removeClass( classNames );
3293 }
3294
3295 this.$flagged = $flagged.addClass( classNames );
3296 };
3297
3298 /**
3299 * Check if the specified flag is set.
3300 *
3301 * @param {string} flag Name of flag
3302 * @return {boolean} The flag is set
3303 */
3304 OO.ui.mixin.FlaggedElement.prototype.hasFlag = function ( flag ) {
3305 // This may be called before the constructor, thus before this.flags is set
3306 return this.flags && ( flag in this.flags );
3307 };
3308
3309 /**
3310 * Get the names of all flags set.
3311 *
3312 * @return {string[]} Flag names
3313 */
3314 OO.ui.mixin.FlaggedElement.prototype.getFlags = function () {
3315 // This may be called before the constructor, thus before this.flags is set
3316 return Object.keys( this.flags || {} );
3317 };
3318
3319 /**
3320 * Clear all flags.
3321 *
3322 * @chainable
3323 * @return {OO.ui.Element} The element, for chaining
3324 * @fires flag
3325 */
3326 OO.ui.mixin.FlaggedElement.prototype.clearFlags = function () {
3327 var flag, className,
3328 changes = {},
3329 remove = [],
3330 classPrefix = 'oo-ui-flaggedElement-';
3331
3332 for ( flag in this.flags ) {
3333 className = classPrefix + flag;
3334 changes[ flag ] = false;
3335 delete this.flags[ flag ];
3336 remove.push( className );
3337 }
3338
3339 if ( this.$flagged ) {
3340 this.$flagged.removeClass( remove );
3341 }
3342
3343 this.updateThemeClasses();
3344 this.emit( 'flag', changes );
3345
3346 return this;
3347 };
3348
3349 /**
3350 * Add one or more flags.
3351 *
3352 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
3353 * or an object keyed by flag name with a boolean value that indicates whether the flag should
3354 * be added (`true`) or removed (`false`).
3355 * @chainable
3356 * @return {OO.ui.Element} The element, for chaining
3357 * @fires flag
3358 */
3359 OO.ui.mixin.FlaggedElement.prototype.setFlags = function ( flags ) {
3360 var i, len, flag, className,
3361 changes = {},
3362 add = [],
3363 remove = [],
3364 classPrefix = 'oo-ui-flaggedElement-';
3365
3366 if ( typeof flags === 'string' ) {
3367 className = classPrefix + flags;
3368 // Set
3369 if ( !this.flags[ flags ] ) {
3370 this.flags[ flags ] = true;
3371 add.push( className );
3372 }
3373 } else if ( Array.isArray( flags ) ) {
3374 for ( i = 0, len = flags.length; i < len; i++ ) {
3375 flag = flags[ i ];
3376 className = classPrefix + flag;
3377 // Set
3378 if ( !this.flags[ flag ] ) {
3379 changes[ flag ] = true;
3380 this.flags[ flag ] = true;
3381 add.push( className );
3382 }
3383 }
3384 } else if ( OO.isPlainObject( flags ) ) {
3385 for ( flag in flags ) {
3386 className = classPrefix + flag;
3387 if ( flags[ flag ] ) {
3388 // Set
3389 if ( !this.flags[ flag ] ) {
3390 changes[ flag ] = true;
3391 this.flags[ flag ] = true;
3392 add.push( className );
3393 }
3394 } else {
3395 // Remove
3396 if ( this.flags[ flag ] ) {
3397 changes[ flag ] = false;
3398 delete this.flags[ flag ];
3399 remove.push( className );
3400 }
3401 }
3402 }
3403 }
3404
3405 if ( this.$flagged ) {
3406 this.$flagged
3407 .addClass( add )
3408 .removeClass( remove );
3409 }
3410
3411 this.updateThemeClasses();
3412 this.emit( 'flag', changes );
3413
3414 return this;
3415 };
3416
3417 /**
3418 * TitledElement is mixed into other classes to provide a `title` attribute.
3419 * Titles are rendered by the browser and are made visible when the user moves
3420 * the mouse over the element. Titles are not visible on touch devices.
3421 *
3422 * @example
3423 * // TitledElement provides a 'title' attribute to the
3424 * // ButtonWidget class
3425 * var button = new OO.ui.ButtonWidget( {
3426 * label: 'Button with Title',
3427 * title: 'I am a button'
3428 * } );
3429 * $( 'body' ).append( button.$element );
3430 *
3431 * @abstract
3432 * @class
3433 *
3434 * @constructor
3435 * @param {Object} [config] Configuration options
3436 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
3437 * If this config is omitted, the title functionality is applied to $element, the
3438 * element created by the class.
3439 * @cfg {string|Function} [title] The title text or a function that returns text. If
3440 * this config is omitted, the value of the {@link #static-title static title} property is used.
3441 */
3442 OO.ui.mixin.TitledElement = function OoUiMixinTitledElement( config ) {
3443 // Configuration initialization
3444 config = config || {};
3445
3446 // Properties
3447 this.$titled = null;
3448 this.title = null;
3449
3450 // Initialization
3451 this.setTitle( config.title !== undefined ? config.title : this.constructor.static.title );
3452 this.setTitledElement( config.$titled || this.$element );
3453 };
3454
3455 /* Setup */
3456
3457 OO.initClass( OO.ui.mixin.TitledElement );
3458
3459 /* Static Properties */
3460
3461 /**
3462 * The title text, a function that returns text, or `null` for no title. The value of the static property
3463 * is overridden if the #title config option is used.
3464 *
3465 * @static
3466 * @inheritable
3467 * @property {string|Function|null}
3468 */
3469 OO.ui.mixin.TitledElement.static.title = null;
3470
3471 /* Methods */
3472
3473 /**
3474 * Set the titled element.
3475 *
3476 * This method is used to retarget a TitledElement mixin so that its functionality applies to the specified element.
3477 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
3478 *
3479 * @param {jQuery} $titled Element that should use the 'titled' functionality
3480 */
3481 OO.ui.mixin.TitledElement.prototype.setTitledElement = function ( $titled ) {
3482 if ( this.$titled ) {
3483 this.$titled.removeAttr( 'title' );
3484 }
3485
3486 this.$titled = $titled;
3487 if ( this.title ) {
3488 this.updateTitle();
3489 }
3490 };
3491
3492 /**
3493 * Set title.
3494 *
3495 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
3496 * @chainable
3497 * @return {OO.ui.Element} The element, for chaining
3498 */
3499 OO.ui.mixin.TitledElement.prototype.setTitle = function ( title ) {
3500 title = typeof title === 'function' ? OO.ui.resolveMsg( title ) : title;
3501 title = ( typeof title === 'string' && title.length ) ? title : null;
3502
3503 if ( this.title !== title ) {
3504 this.title = title;
3505 this.updateTitle();
3506 }
3507
3508 return this;
3509 };
3510
3511 /**
3512 * Update the title attribute, in case of changes to title or accessKey.
3513 *
3514 * @protected
3515 * @chainable
3516 * @return {OO.ui.Element} The element, for chaining
3517 */
3518 OO.ui.mixin.TitledElement.prototype.updateTitle = function () {
3519 var title = this.getTitle();
3520 if ( this.$titled ) {
3521 if ( title !== null ) {
3522 // Only if this is an AccessKeyedElement
3523 if ( this.formatTitleWithAccessKey ) {
3524 title = this.formatTitleWithAccessKey( title );
3525 }
3526 this.$titled.attr( 'title', title );
3527 } else {
3528 this.$titled.removeAttr( 'title' );
3529 }
3530 }
3531 return this;
3532 };
3533
3534 /**
3535 * Get title.
3536 *
3537 * @return {string} Title string
3538 */
3539 OO.ui.mixin.TitledElement.prototype.getTitle = function () {
3540 return this.title;
3541 };
3542
3543 /**
3544 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
3545 * Accesskeys allow an user to go to a specific element by using
3546 * a shortcut combination of a browser specific keys + the key
3547 * set to the field.
3548 *
3549 * @example
3550 * // AccessKeyedElement provides an 'accesskey' attribute to the
3551 * // ButtonWidget class
3552 * var button = new OO.ui.ButtonWidget( {
3553 * label: 'Button with Accesskey',
3554 * accessKey: 'k'
3555 * } );
3556 * $( 'body' ).append( button.$element );
3557 *
3558 * @abstract
3559 * @class
3560 *
3561 * @constructor
3562 * @param {Object} [config] Configuration options
3563 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3564 * If this config is omitted, the accesskey functionality is applied to $element, the
3565 * element created by the class.
3566 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3567 * this config is omitted, no accesskey will be added.
3568 */
3569 OO.ui.mixin.AccessKeyedElement = function OoUiMixinAccessKeyedElement( config ) {
3570 // Configuration initialization
3571 config = config || {};
3572
3573 // Properties
3574 this.$accessKeyed = null;
3575 this.accessKey = null;
3576
3577 // Initialization
3578 this.setAccessKey( config.accessKey || null );
3579 this.setAccessKeyedElement( config.$accessKeyed || this.$element );
3580
3581 // If this is also a TitledElement and it initialized before we did, we may have
3582 // to update the title with the access key
3583 if ( this.updateTitle ) {
3584 this.updateTitle();
3585 }
3586 };
3587
3588 /* Setup */
3589
3590 OO.initClass( OO.ui.mixin.AccessKeyedElement );
3591
3592 /* Static Properties */
3593
3594 /**
3595 * The access key, a function that returns a key, or `null` for no accesskey.
3596 *
3597 * @static
3598 * @inheritable
3599 * @property {string|Function|null}
3600 */
3601 OO.ui.mixin.AccessKeyedElement.static.accessKey = null;
3602
3603 /* Methods */
3604
3605 /**
3606 * Set the accesskeyed element.
3607 *
3608 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
3609 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
3610 *
3611 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyed' functionality
3612 */
3613 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKeyedElement = function ( $accessKeyed ) {
3614 if ( this.$accessKeyed ) {
3615 this.$accessKeyed.removeAttr( 'accesskey' );
3616 }
3617
3618 this.$accessKeyed = $accessKeyed;
3619 if ( this.accessKey ) {
3620 this.$accessKeyed.attr( 'accesskey', this.accessKey );
3621 }
3622 };
3623
3624 /**
3625 * Set accesskey.
3626 *
3627 * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no accesskey
3628 * @chainable
3629 * @return {OO.ui.Element} The element, for chaining
3630 */
3631 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKey = function ( accessKey ) {
3632 accessKey = typeof accessKey === 'string' ? OO.ui.resolveMsg( accessKey ) : null;
3633
3634 if ( this.accessKey !== accessKey ) {
3635 if ( this.$accessKeyed ) {
3636 if ( accessKey !== null ) {
3637 this.$accessKeyed.attr( 'accesskey', accessKey );
3638 } else {
3639 this.$accessKeyed.removeAttr( 'accesskey' );
3640 }
3641 }
3642 this.accessKey = accessKey;
3643
3644 // Only if this is a TitledElement
3645 if ( this.updateTitle ) {
3646 this.updateTitle();
3647 }
3648 }
3649
3650 return this;
3651 };
3652
3653 /**
3654 * Get accesskey.
3655 *
3656 * @return {string} accessKey string
3657 */
3658 OO.ui.mixin.AccessKeyedElement.prototype.getAccessKey = function () {
3659 return this.accessKey;
3660 };
3661
3662 /**
3663 * Add information about the access key to the element's tooltip label.
3664 * (This is only public for hacky usage in FieldLayout.)
3665 *
3666 * @param {string} title Tooltip label for `title` attribute
3667 * @return {string}
3668 */
3669 OO.ui.mixin.AccessKeyedElement.prototype.formatTitleWithAccessKey = function ( title ) {
3670 var accessKey;
3671
3672 if ( !this.$accessKeyed ) {
3673 // Not initialized yet; the constructor will call updateTitle() which will rerun this function
3674 return title;
3675 }
3676 // Use jquery.accessKeyLabel if available to show modifiers, otherwise just display the single key
3677 if ( $.fn.updateTooltipAccessKeys && $.fn.updateTooltipAccessKeys.getAccessKeyLabel ) {
3678 accessKey = $.fn.updateTooltipAccessKeys.getAccessKeyLabel( this.$accessKeyed[ 0 ] );
3679 } else {
3680 accessKey = this.getAccessKey();
3681 }
3682 if ( accessKey ) {
3683 title += ' [' + accessKey + ']';
3684 }
3685 return title;
3686 };
3687
3688 /**
3689 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3690 * feels, and functionality can be customized via the class’s configuration options
3691 * and methods. Please see the [OOUI documentation on MediaWiki] [1] for more information
3692 * and examples.
3693 *
3694 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches
3695 *
3696 * @example
3697 * // A button widget
3698 * var button = new OO.ui.ButtonWidget( {
3699 * label: 'Button with Icon',
3700 * icon: 'trash',
3701 * title: 'Remove'
3702 * } );
3703 * $( 'body' ).append( button.$element );
3704 *
3705 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3706 *
3707 * @class
3708 * @extends OO.ui.Widget
3709 * @mixins OO.ui.mixin.ButtonElement
3710 * @mixins OO.ui.mixin.IconElement
3711 * @mixins OO.ui.mixin.IndicatorElement
3712 * @mixins OO.ui.mixin.LabelElement
3713 * @mixins OO.ui.mixin.TitledElement
3714 * @mixins OO.ui.mixin.FlaggedElement
3715 * @mixins OO.ui.mixin.TabIndexedElement
3716 * @mixins OO.ui.mixin.AccessKeyedElement
3717 *
3718 * @constructor
3719 * @param {Object} [config] Configuration options
3720 * @cfg {boolean} [active=false] Whether button should be shown as active
3721 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3722 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3723 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3724 */
3725 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
3726 // Configuration initialization
3727 config = config || {};
3728
3729 // Parent constructor
3730 OO.ui.ButtonWidget.parent.call( this, config );
3731
3732 // Mixin constructors
3733 OO.ui.mixin.ButtonElement.call( this, config );
3734 OO.ui.mixin.IconElement.call( this, config );
3735 OO.ui.mixin.IndicatorElement.call( this, config );
3736 OO.ui.mixin.LabelElement.call( this, config );
3737 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
3738 OO.ui.mixin.FlaggedElement.call( this, config );
3739 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
3740 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$button } ) );
3741
3742 // Properties
3743 this.href = null;
3744 this.target = null;
3745 this.noFollow = false;
3746
3747 // Events
3748 this.connect( this, { disable: 'onDisable' } );
3749
3750 // Initialization
3751 this.$button.append( this.$icon, this.$label, this.$indicator );
3752 this.$element
3753 .addClass( 'oo-ui-buttonWidget' )
3754 .append( this.$button );
3755 this.setActive( config.active );
3756 this.setHref( config.href );
3757 this.setTarget( config.target );
3758 this.setNoFollow( config.noFollow );
3759 };
3760
3761 /* Setup */
3762
3763 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
3764 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.ButtonElement );
3765 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IconElement );
3766 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IndicatorElement );
3767 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.LabelElement );
3768 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TitledElement );
3769 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.FlaggedElement );
3770 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TabIndexedElement );
3771 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.AccessKeyedElement );
3772
3773 /* Static Properties */
3774
3775 /**
3776 * @static
3777 * @inheritdoc
3778 */
3779 OO.ui.ButtonWidget.static.cancelButtonMouseDownEvents = false;
3780
3781 /**
3782 * @static
3783 * @inheritdoc
3784 */
3785 OO.ui.ButtonWidget.static.tagName = 'span';
3786
3787 /* Methods */
3788
3789 /**
3790 * Get hyperlink location.
3791 *
3792 * @return {string} Hyperlink location
3793 */
3794 OO.ui.ButtonWidget.prototype.getHref = function () {
3795 return this.href;
3796 };
3797
3798 /**
3799 * Get hyperlink target.
3800 *
3801 * @return {string} Hyperlink target
3802 */
3803 OO.ui.ButtonWidget.prototype.getTarget = function () {
3804 return this.target;
3805 };
3806
3807 /**
3808 * Get search engine traversal hint.
3809 *
3810 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3811 */
3812 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
3813 return this.noFollow;
3814 };
3815
3816 /**
3817 * Set hyperlink location.
3818 *
3819 * @param {string|null} href Hyperlink location, null to remove
3820 * @chainable
3821 * @return {OO.ui.Widget} The widget, for chaining
3822 */
3823 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
3824 href = typeof href === 'string' ? href : null;
3825 if ( href !== null && !OO.ui.isSafeUrl( href ) ) {
3826 href = './' + href;
3827 }
3828
3829 if ( href !== this.href ) {
3830 this.href = href;
3831 this.updateHref();
3832 }
3833
3834 return this;
3835 };
3836
3837 /**
3838 * Update the `href` attribute, in case of changes to href or
3839 * disabled state.
3840 *
3841 * @private
3842 * @chainable
3843 * @return {OO.ui.Widget} The widget, for chaining
3844 */
3845 OO.ui.ButtonWidget.prototype.updateHref = function () {
3846 if ( this.href !== null && !this.isDisabled() ) {
3847 this.$button.attr( 'href', this.href );
3848 } else {
3849 this.$button.removeAttr( 'href' );
3850 }
3851
3852 return this;
3853 };
3854
3855 /**
3856 * Handle disable events.
3857 *
3858 * @private
3859 * @param {boolean} disabled Element is disabled
3860 */
3861 OO.ui.ButtonWidget.prototype.onDisable = function () {
3862 this.updateHref();
3863 };
3864
3865 /**
3866 * Set hyperlink target.
3867 *
3868 * @param {string|null} target Hyperlink target, null to remove
3869 * @return {OO.ui.Widget} The widget, for chaining
3870 */
3871 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
3872 target = typeof target === 'string' ? target : null;
3873
3874 if ( target !== this.target ) {
3875 this.target = target;
3876 if ( target !== null ) {
3877 this.$button.attr( 'target', target );
3878 } else {
3879 this.$button.removeAttr( 'target' );
3880 }
3881 }
3882
3883 return this;
3884 };
3885
3886 /**
3887 * Set search engine traversal hint.
3888 *
3889 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3890 * @return {OO.ui.Widget} The widget, for chaining
3891 */
3892 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
3893 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
3894
3895 if ( noFollow !== this.noFollow ) {
3896 this.noFollow = noFollow;
3897 if ( noFollow ) {
3898 this.$button.attr( 'rel', 'nofollow' );
3899 } else {
3900 this.$button.removeAttr( 'rel' );
3901 }
3902 }
3903
3904 return this;
3905 };
3906
3907 // Override method visibility hints from ButtonElement
3908 /**
3909 * @method setActive
3910 * @inheritdoc
3911 */
3912 /**
3913 * @method isActive
3914 * @inheritdoc
3915 */
3916
3917 /**
3918 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3919 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3920 * removed, and cleared from the group.
3921 *
3922 * @example
3923 * // Example: A ButtonGroupWidget with two buttons
3924 * var button1 = new OO.ui.PopupButtonWidget( {
3925 * label: 'Select a category',
3926 * icon: 'menu',
3927 * popup: {
3928 * $content: $( '<p>List of categories...</p>' ),
3929 * padded: true,
3930 * align: 'left'
3931 * }
3932 * } );
3933 * var button2 = new OO.ui.ButtonWidget( {
3934 * label: 'Add item'
3935 * });
3936 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
3937 * items: [button1, button2]
3938 * } );
3939 * $( 'body' ).append( buttonGroup.$element );
3940 *
3941 * @class
3942 * @extends OO.ui.Widget
3943 * @mixins OO.ui.mixin.GroupElement
3944 *
3945 * @constructor
3946 * @param {Object} [config] Configuration options
3947 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
3948 */
3949 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
3950 // Configuration initialization
3951 config = config || {};
3952
3953 // Parent constructor
3954 OO.ui.ButtonGroupWidget.parent.call( this, config );
3955
3956 // Mixin constructors
3957 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
3958
3959 // Initialization
3960 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
3961 if ( Array.isArray( config.items ) ) {
3962 this.addItems( config.items );
3963 }
3964 };
3965
3966 /* Setup */
3967
3968 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
3969 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.GroupElement );
3970
3971 /* Static Properties */
3972
3973 /**
3974 * @static
3975 * @inheritdoc
3976 */
3977 OO.ui.ButtonGroupWidget.static.tagName = 'span';
3978
3979 /* Methods */
3980
3981 /**
3982 * Focus the widget
3983 *
3984 * @chainable
3985 * @return {OO.ui.Widget} The widget, for chaining
3986 */
3987 OO.ui.ButtonGroupWidget.prototype.focus = function () {
3988 if ( !this.isDisabled() ) {
3989 if ( this.items[ 0 ] ) {
3990 this.items[ 0 ].focus();
3991 }
3992 }
3993 return this;
3994 };
3995
3996 /**
3997 * @inheritdoc
3998 */
3999 OO.ui.ButtonGroupWidget.prototype.simulateLabelClick = function () {
4000 this.focus();
4001 };
4002
4003 /**
4004 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
4005 * which creates a label that identifies the icon’s function. See the [OOUI documentation on MediaWiki] [1]
4006 * for a list of icons included in the library.
4007 *
4008 * @example
4009 * // An icon widget with a label
4010 * var myIcon = new OO.ui.IconWidget( {
4011 * icon: 'help',
4012 * title: 'Help'
4013 * } );
4014 * // Create a label.
4015 * var iconLabel = new OO.ui.LabelWidget( {
4016 * label: 'Help'
4017 * } );
4018 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
4019 *
4020 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
4021 *
4022 * @class
4023 * @extends OO.ui.Widget
4024 * @mixins OO.ui.mixin.IconElement
4025 * @mixins OO.ui.mixin.TitledElement
4026 * @mixins OO.ui.mixin.LabelElement
4027 * @mixins OO.ui.mixin.FlaggedElement
4028 *
4029 * @constructor
4030 * @param {Object} [config] Configuration options
4031 */
4032 OO.ui.IconWidget = function OoUiIconWidget( config ) {
4033 // Configuration initialization
4034 config = config || {};
4035
4036 // Parent constructor
4037 OO.ui.IconWidget.parent.call( this, config );
4038
4039 // Mixin constructors
4040 OO.ui.mixin.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
4041 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
4042 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element, invisibleLabel: true } ) );
4043 OO.ui.mixin.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) );
4044
4045 // Initialization
4046 this.$element.addClass( 'oo-ui-iconWidget' );
4047 // Remove class added by LabelElement initialization. It causes unexpected CSS to apply when
4048 // nested in other widgets, because this widget used to not mix in LabelElement.
4049 this.$element.removeClass( 'oo-ui-labelElement-label' );
4050 };
4051
4052 /* Setup */
4053
4054 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
4055 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.IconElement );
4056 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.TitledElement );
4057 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.LabelElement );
4058 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.FlaggedElement );
4059
4060 /* Static Properties */
4061
4062 /**
4063 * @static
4064 * @inheritdoc
4065 */
4066 OO.ui.IconWidget.static.tagName = 'span';
4067
4068 /**
4069 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
4070 * attention to the status of an item or to clarify the function within a control. For a list of
4071 * indicators included in the library, please see the [OOUI documentation on MediaWiki][1].
4072 *
4073 * @example
4074 * // Example of an indicator widget
4075 * var indicator1 = new OO.ui.IndicatorWidget( {
4076 * indicator: 'required'
4077 * } );
4078 *
4079 * // Create a fieldset layout to add a label
4080 * var fieldset = new OO.ui.FieldsetLayout();
4081 * fieldset.addItems( [
4082 * new OO.ui.FieldLayout( indicator1, { label: 'A required indicator:' } )
4083 * ] );
4084 * $( 'body' ).append( fieldset.$element );
4085 *
4086 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
4087 *
4088 * @class
4089 * @extends OO.ui.Widget
4090 * @mixins OO.ui.mixin.IndicatorElement
4091 * @mixins OO.ui.mixin.TitledElement
4092 * @mixins OO.ui.mixin.LabelElement
4093 *
4094 * @constructor
4095 * @param {Object} [config] Configuration options
4096 */
4097 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
4098 // Configuration initialization
4099 config = config || {};
4100
4101 // Parent constructor
4102 OO.ui.IndicatorWidget.parent.call( this, config );
4103
4104 // Mixin constructors
4105 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
4106 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
4107 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element, invisibleLabel: true } ) );
4108
4109 // Initialization
4110 this.$element.addClass( 'oo-ui-indicatorWidget' );
4111 // Remove class added by LabelElement initialization. It causes unexpected CSS to apply when
4112 // nested in other widgets, because this widget used to not mix in LabelElement.
4113 this.$element.removeClass( 'oo-ui-labelElement-label' );
4114 };
4115
4116 /* Setup */
4117
4118 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
4119 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.IndicatorElement );
4120 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.TitledElement );
4121 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.LabelElement );
4122
4123 /* Static Properties */
4124
4125 /**
4126 * @static
4127 * @inheritdoc
4128 */
4129 OO.ui.IndicatorWidget.static.tagName = 'span';
4130
4131 /**
4132 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
4133 * be configured with a `label` option that is set to a string, a label node, or a function:
4134 *
4135 * - String: a plaintext string
4136 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
4137 * label that includes a link or special styling, such as a gray color or additional graphical elements.
4138 * - Function: a function that will produce a string in the future. Functions are used
4139 * in cases where the value of the label is not currently defined.
4140 *
4141 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
4142 * will come into focus when the label is clicked.
4143 *
4144 * @example
4145 * // Examples of LabelWidgets
4146 * var label1 = new OO.ui.LabelWidget( {
4147 * label: 'plaintext label'
4148 * } );
4149 * var label2 = new OO.ui.LabelWidget( {
4150 * label: $( '<a href="default.html">jQuery label</a>' )
4151 * } );
4152 * // Create a fieldset layout with fields for each example
4153 * var fieldset = new OO.ui.FieldsetLayout();
4154 * fieldset.addItems( [
4155 * new OO.ui.FieldLayout( label1 ),
4156 * new OO.ui.FieldLayout( label2 )
4157 * ] );
4158 * $( 'body' ).append( fieldset.$element );
4159 *
4160 * @class
4161 * @extends OO.ui.Widget
4162 * @mixins OO.ui.mixin.LabelElement
4163 * @mixins OO.ui.mixin.TitledElement
4164 *
4165 * @constructor
4166 * @param {Object} [config] Configuration options
4167 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
4168 * Clicking the label will focus the specified input field.
4169 */
4170 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
4171 // Configuration initialization
4172 config = config || {};
4173
4174 // Parent constructor
4175 OO.ui.LabelWidget.parent.call( this, config );
4176
4177 // Mixin constructors
4178 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
4179 OO.ui.mixin.TitledElement.call( this, config );
4180
4181 // Properties
4182 this.input = config.input;
4183
4184 // Initialization
4185 if ( this.input ) {
4186 if ( this.input.getInputId() ) {
4187 this.$element.attr( 'for', this.input.getInputId() );
4188 } else {
4189 this.$label.on( 'click', function () {
4190 this.input.simulateLabelClick();
4191 }.bind( this ) );
4192 }
4193 }
4194 this.$element.addClass( 'oo-ui-labelWidget' );
4195 };
4196
4197 /* Setup */
4198
4199 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
4200 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.LabelElement );
4201 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.TitledElement );
4202
4203 /* Static Properties */
4204
4205 /**
4206 * @static
4207 * @inheritdoc
4208 */
4209 OO.ui.LabelWidget.static.tagName = 'label';
4210
4211 /**
4212 * PendingElement is a mixin that is used to create elements that notify users that something is happening
4213 * and that they should wait before proceeding. The pending state is visually represented with a pending
4214 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
4215 * field of a {@link OO.ui.TextInputWidget text input widget}.
4216 *
4217 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
4218 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
4219 * in process dialogs.
4220 *
4221 * @example
4222 * function MessageDialog( config ) {
4223 * MessageDialog.parent.call( this, config );
4224 * }
4225 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
4226 *
4227 * MessageDialog.static.name = 'myMessageDialog';
4228 * MessageDialog.static.actions = [
4229 * { action: 'save', label: 'Done', flags: 'primary' },
4230 * { label: 'Cancel', flags: 'safe' }
4231 * ];
4232 *
4233 * MessageDialog.prototype.initialize = function () {
4234 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
4235 * this.content = new OO.ui.PanelLayout( { padded: true } );
4236 * 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>' );
4237 * this.$body.append( this.content.$element );
4238 * };
4239 * MessageDialog.prototype.getBodyHeight = function () {
4240 * return 100;
4241 * }
4242 * MessageDialog.prototype.getActionProcess = function ( action ) {
4243 * var dialog = this;
4244 * if ( action === 'save' ) {
4245 * dialog.getActions().get({actions: 'save'})[0].pushPending();
4246 * return new OO.ui.Process()
4247 * .next( 1000 )
4248 * .next( function () {
4249 * dialog.getActions().get({actions: 'save'})[0].popPending();
4250 * } );
4251 * }
4252 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
4253 * };
4254 *
4255 * var windowManager = new OO.ui.WindowManager();
4256 * $( 'body' ).append( windowManager.$element );
4257 *
4258 * var dialog = new MessageDialog();
4259 * windowManager.addWindows( [ dialog ] );
4260 * windowManager.openWindow( dialog );
4261 *
4262 * @abstract
4263 * @class
4264 *
4265 * @constructor
4266 * @param {Object} [config] Configuration options
4267 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
4268 */
4269 OO.ui.mixin.PendingElement = function OoUiMixinPendingElement( config ) {
4270 // Configuration initialization
4271 config = config || {};
4272
4273 // Properties
4274 this.pending = 0;
4275 this.$pending = null;
4276
4277 // Initialisation
4278 this.setPendingElement( config.$pending || this.$element );
4279 };
4280
4281 /* Setup */
4282
4283 OO.initClass( OO.ui.mixin.PendingElement );
4284
4285 /* Methods */
4286
4287 /**
4288 * Set the pending element (and clean up any existing one).
4289 *
4290 * @param {jQuery} $pending The element to set to pending.
4291 */
4292 OO.ui.mixin.PendingElement.prototype.setPendingElement = function ( $pending ) {
4293 if ( this.$pending ) {
4294 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
4295 }
4296
4297 this.$pending = $pending;
4298 if ( this.pending > 0 ) {
4299 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
4300 }
4301 };
4302
4303 /**
4304 * Check if an element is pending.
4305 *
4306 * @return {boolean} Element is pending
4307 */
4308 OO.ui.mixin.PendingElement.prototype.isPending = function () {
4309 return !!this.pending;
4310 };
4311
4312 /**
4313 * Increase the pending counter. The pending state will remain active until the counter is zero
4314 * (i.e., the number of calls to #pushPending and #popPending is the same).
4315 *
4316 * @chainable
4317 * @return {OO.ui.Element} The element, for chaining
4318 */
4319 OO.ui.mixin.PendingElement.prototype.pushPending = function () {
4320 if ( this.pending === 0 ) {
4321 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
4322 this.updateThemeClasses();
4323 }
4324 this.pending++;
4325
4326 return this;
4327 };
4328
4329 /**
4330 * Decrease the pending counter. The pending state will remain active until the counter is zero
4331 * (i.e., the number of calls to #pushPending and #popPending is the same).
4332 *
4333 * @chainable
4334 * @return {OO.ui.Element} The element, for chaining
4335 */
4336 OO.ui.mixin.PendingElement.prototype.popPending = function () {
4337 if ( this.pending === 1 ) {
4338 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
4339 this.updateThemeClasses();
4340 }
4341 this.pending = Math.max( 0, this.pending - 1 );
4342
4343 return this;
4344 };
4345
4346 /**
4347 * Element that will stick adjacent to a specified container, even when it is inserted elsewhere
4348 * in the document (for example, in an OO.ui.Window's $overlay).
4349 *
4350 * The elements's position is automatically calculated and maintained when window is resized or the
4351 * page is scrolled. If you reposition the container manually, you have to call #position to make
4352 * sure the element is still placed correctly.
4353 *
4354 * As positioning is only possible when both the element and the container are attached to the DOM
4355 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
4356 * the #toggle method to display a floating popup, for example.
4357 *
4358 * @abstract
4359 * @class
4360 *
4361 * @constructor
4362 * @param {Object} [config] Configuration options
4363 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
4364 * @cfg {jQuery} [$floatableContainer] Node to position adjacent to
4365 * @cfg {string} [verticalPosition='below'] Where to position $floatable vertically:
4366 * 'below': Directly below $floatableContainer, aligning f's top edge with fC's bottom edge
4367 * 'above': Directly above $floatableContainer, aligning f's bottom edge with fC's top edge
4368 * 'top': Align the top edge with $floatableContainer's top edge
4369 * 'bottom': Align the bottom edge with $floatableContainer's bottom edge
4370 * 'center': Vertically align the center with $floatableContainer's center
4371 * @cfg {string} [horizontalPosition='start'] Where to position $floatable horizontally:
4372 * 'before': Directly before $floatableContainer, aligning f's end edge with fC's start edge
4373 * 'after': Directly after $floatableContainer, aligning f's start edge with fC's end edge
4374 * 'start': Align the start (left in LTR, right in RTL) edge with $floatableContainer's start edge
4375 * 'end': Align the end (right in LTR, left in RTL) edge with $floatableContainer's end edge
4376 * 'center': Horizontally align the center with $floatableContainer's center
4377 * @cfg {boolean} [hideWhenOutOfView=true] Whether to hide the floatable element if the container
4378 * is out of view
4379 */
4380 OO.ui.mixin.FloatableElement = function OoUiMixinFloatableElement( config ) {
4381 // Configuration initialization
4382 config = config || {};
4383
4384 // Properties
4385 this.$floatable = null;
4386 this.$floatableContainer = null;
4387 this.$floatableWindow = null;
4388 this.$floatableClosestScrollable = null;
4389 this.floatableOutOfView = false;
4390 this.onFloatableScrollHandler = this.position.bind( this );
4391 this.onFloatableWindowResizeHandler = this.position.bind( this );
4392
4393 // Initialization
4394 this.setFloatableContainer( config.$floatableContainer );
4395 this.setFloatableElement( config.$floatable || this.$element );
4396 this.setVerticalPosition( config.verticalPosition || 'below' );
4397 this.setHorizontalPosition( config.horizontalPosition || 'start' );
4398 this.hideWhenOutOfView = config.hideWhenOutOfView === undefined ? true : !!config.hideWhenOutOfView;
4399 };
4400
4401 /* Methods */
4402
4403 /**
4404 * Set floatable element.
4405 *
4406 * If an element is already set, it will be cleaned up before setting up the new element.
4407 *
4408 * @param {jQuery} $floatable Element to make floatable
4409 */
4410 OO.ui.mixin.FloatableElement.prototype.setFloatableElement = function ( $floatable ) {
4411 if ( this.$floatable ) {
4412 this.$floatable.removeClass( 'oo-ui-floatableElement-floatable' );
4413 this.$floatable.css( { left: '', top: '' } );
4414 }
4415
4416 this.$floatable = $floatable.addClass( 'oo-ui-floatableElement-floatable' );
4417 this.position();
4418 };
4419
4420 /**
4421 * Set floatable container.
4422 *
4423 * The element will be positioned relative to the specified container.
4424 *
4425 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
4426 */
4427 OO.ui.mixin.FloatableElement.prototype.setFloatableContainer = function ( $floatableContainer ) {
4428 this.$floatableContainer = $floatableContainer;
4429 if ( this.$floatable ) {
4430 this.position();
4431 }
4432 };
4433
4434 /**
4435 * Change how the element is positioned vertically.
4436 *
4437 * @param {string} position 'below', 'above', 'top', 'bottom' or 'center'
4438 */
4439 OO.ui.mixin.FloatableElement.prototype.setVerticalPosition = function ( position ) {
4440 if ( [ 'below', 'above', 'top', 'bottom', 'center' ].indexOf( position ) === -1 ) {
4441 throw new Error( 'Invalid value for vertical position: ' + position );
4442 }
4443 if ( this.verticalPosition !== position ) {
4444 this.verticalPosition = position;
4445 if ( this.$floatable ) {
4446 this.position();
4447 }
4448 }
4449 };
4450
4451 /**
4452 * Change how the element is positioned horizontally.
4453 *
4454 * @param {string} position 'before', 'after', 'start', 'end' or 'center'
4455 */
4456 OO.ui.mixin.FloatableElement.prototype.setHorizontalPosition = function ( position ) {
4457 if ( [ 'before', 'after', 'start', 'end', 'center' ].indexOf( position ) === -1 ) {
4458 throw new Error( 'Invalid value for horizontal position: ' + position );
4459 }
4460 if ( this.horizontalPosition !== position ) {
4461 this.horizontalPosition = position;
4462 if ( this.$floatable ) {
4463 this.position();
4464 }
4465 }
4466 };
4467
4468 /**
4469 * Toggle positioning.
4470 *
4471 * Do not turn positioning on until after the element is attached to the DOM and visible.
4472 *
4473 * @param {boolean} [positioning] Enable positioning, omit to toggle
4474 * @chainable
4475 * @return {OO.ui.Element} The element, for chaining
4476 */
4477 OO.ui.mixin.FloatableElement.prototype.togglePositioning = function ( positioning ) {
4478 var closestScrollableOfContainer;
4479
4480 if ( !this.$floatable || !this.$floatableContainer ) {
4481 return this;
4482 }
4483
4484 positioning = positioning === undefined ? !this.positioning : !!positioning;
4485
4486 if ( positioning && !this.warnedUnattached && !this.isElementAttached() ) {
4487 OO.ui.warnDeprecation( 'FloatableElement#togglePositioning: Before calling this method, the element must be attached to the DOM.' );
4488 this.warnedUnattached = true;
4489 }
4490
4491 if ( this.positioning !== positioning ) {
4492 this.positioning = positioning;
4493
4494 closestScrollableOfContainer = OO.ui.Element.static.getClosestScrollableContainer( this.$floatableContainer[ 0 ] );
4495 // If the scrollable is the root, we have to listen to scroll events
4496 // on the window because of browser inconsistencies.
4497 if ( $( closestScrollableOfContainer ).is( 'html, body' ) ) {
4498 closestScrollableOfContainer = OO.ui.Element.static.getWindow( closestScrollableOfContainer );
4499 }
4500
4501 if ( positioning ) {
4502 this.$floatableWindow = $( this.getElementWindow() );
4503 this.$floatableWindow.on( 'resize', this.onFloatableWindowResizeHandler );
4504
4505 this.$floatableClosestScrollable = $( closestScrollableOfContainer );
4506 this.$floatableClosestScrollable.on( 'scroll', this.onFloatableScrollHandler );
4507
4508 // Initial position after visible
4509 this.position();
4510 } else {
4511 if ( this.$floatableWindow ) {
4512 this.$floatableWindow.off( 'resize', this.onFloatableWindowResizeHandler );
4513 this.$floatableWindow = null;
4514 }
4515
4516 if ( this.$floatableClosestScrollable ) {
4517 this.$floatableClosestScrollable.off( 'scroll', this.onFloatableScrollHandler );
4518 this.$floatableClosestScrollable = null;
4519 }
4520
4521 this.$floatable.css( { left: '', right: '', top: '' } );
4522 }
4523 }
4524
4525 return this;
4526 };
4527
4528 /**
4529 * Check whether the bottom edge of the given element is within the viewport of the given container.
4530 *
4531 * @private
4532 * @param {jQuery} $element
4533 * @param {jQuery} $container
4534 * @return {boolean}
4535 */
4536 OO.ui.mixin.FloatableElement.prototype.isElementInViewport = function ( $element, $container ) {
4537 var elemRect, contRect, topEdgeInBounds, bottomEdgeInBounds, leftEdgeInBounds, rightEdgeInBounds,
4538 startEdgeInBounds, endEdgeInBounds, viewportSpacing,
4539 direction = $element.css( 'direction' );
4540
4541 elemRect = $element[ 0 ].getBoundingClientRect();
4542 if ( $container[ 0 ] === window ) {
4543 viewportSpacing = OO.ui.getViewportSpacing();
4544 contRect = {
4545 top: 0,
4546 left: 0,
4547 right: document.documentElement.clientWidth,
4548 bottom: document.documentElement.clientHeight
4549 };
4550 contRect.top += viewportSpacing.top;
4551 contRect.left += viewportSpacing.left;
4552 contRect.right -= viewportSpacing.right;
4553 contRect.bottom -= viewportSpacing.bottom;
4554 } else {
4555 contRect = $container[ 0 ].getBoundingClientRect();
4556 }
4557
4558 topEdgeInBounds = elemRect.top >= contRect.top && elemRect.top <= contRect.bottom;
4559 bottomEdgeInBounds = elemRect.bottom >= contRect.top && elemRect.bottom <= contRect.bottom;
4560 leftEdgeInBounds = elemRect.left >= contRect.left && elemRect.left <= contRect.right;
4561 rightEdgeInBounds = elemRect.right >= contRect.left && elemRect.right <= contRect.right;
4562 if ( direction === 'rtl' ) {
4563 startEdgeInBounds = rightEdgeInBounds;
4564 endEdgeInBounds = leftEdgeInBounds;
4565 } else {
4566 startEdgeInBounds = leftEdgeInBounds;
4567 endEdgeInBounds = rightEdgeInBounds;
4568 }
4569
4570 if ( this.verticalPosition === 'below' && !bottomEdgeInBounds ) {
4571 return false;
4572 }
4573 if ( this.verticalPosition === 'above' && !topEdgeInBounds ) {
4574 return false;
4575 }
4576 if ( this.horizontalPosition === 'before' && !startEdgeInBounds ) {
4577 return false;
4578 }
4579 if ( this.horizontalPosition === 'after' && !endEdgeInBounds ) {
4580 return false;
4581 }
4582
4583 // The other positioning values are all about being inside the container,
4584 // so in those cases all we care about is that any part of the container is visible.
4585 return elemRect.top <= contRect.bottom && elemRect.bottom >= contRect.top &&
4586 elemRect.left <= contRect.right && elemRect.right >= contRect.left;
4587 };
4588
4589 /**
4590 * Check if the floatable is hidden to the user because it was offscreen.
4591 *
4592 * @return {boolean} Floatable is out of view
4593 */
4594 OO.ui.mixin.FloatableElement.prototype.isFloatableOutOfView = function () {
4595 return this.floatableOutOfView;
4596 };
4597
4598 /**
4599 * Position the floatable below its container.
4600 *
4601 * This should only be done when both of them are attached to the DOM and visible.
4602 *
4603 * @chainable
4604 * @return {OO.ui.Element} The element, for chaining
4605 */
4606 OO.ui.mixin.FloatableElement.prototype.position = function () {
4607 if ( !this.positioning ) {
4608 return this;
4609 }
4610
4611 if ( !(
4612 // To continue, some things need to be true:
4613 // The element must actually be in the DOM
4614 this.isElementAttached() && (
4615 // The closest scrollable is the current window
4616 this.$floatableClosestScrollable[ 0 ] === this.getElementWindow() ||
4617 // OR is an element in the element's DOM
4618 $.contains( this.getElementDocument(), this.$floatableClosestScrollable[ 0 ] )
4619 )
4620 ) ) {
4621 // Abort early if important parts of the widget are no longer attached to the DOM
4622 return this;
4623 }
4624
4625 this.floatableOutOfView = this.hideWhenOutOfView && !this.isElementInViewport( this.$floatableContainer, this.$floatableClosestScrollable );
4626 if ( this.floatableOutOfView ) {
4627 this.$floatable.addClass( 'oo-ui-element-hidden' );
4628 return this;
4629 } else {
4630 this.$floatable.removeClass( 'oo-ui-element-hidden' );
4631 }
4632
4633 this.$floatable.css( this.computePosition() );
4634
4635 // We updated the position, so re-evaluate the clipping state.
4636 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
4637 // will not notice the need to update itself.)
4638 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
4639 // it not listen to the right events in the right places?
4640 if ( this.clip ) {
4641 this.clip();
4642 }
4643
4644 return this;
4645 };
4646
4647 /**
4648 * Compute how #$floatable should be positioned based on the position of #$floatableContainer
4649 * and the positioning settings. This is a helper for #position that shouldn't be called directly,
4650 * but may be overridden by subclasses if they want to change or add to the positioning logic.
4651 *
4652 * @return {Object} New position to apply with .css(). Keys are 'top', 'left', 'bottom' and 'right'.
4653 */
4654 OO.ui.mixin.FloatableElement.prototype.computePosition = function () {
4655 var isBody, scrollableX, scrollableY, containerPos,
4656 horizScrollbarHeight, vertScrollbarWidth, scrollTop, scrollLeft,
4657 newPos = { top: '', left: '', bottom: '', right: '' },
4658 direction = this.$floatableContainer.css( 'direction' ),
4659 $offsetParent = this.$floatable.offsetParent();
4660
4661 if ( $offsetParent.is( 'html' ) ) {
4662 // The innerHeight/Width and clientHeight/Width calculations don't work well on the
4663 // <html> element, but they do work on the <body>
4664 $offsetParent = $( $offsetParent[ 0 ].ownerDocument.body );
4665 }
4666 isBody = $offsetParent.is( 'body' );
4667 scrollableX = $offsetParent.css( 'overflow-x' ) === 'scroll' || $offsetParent.css( 'overflow-x' ) === 'auto';
4668 scrollableY = $offsetParent.css( 'overflow-y' ) === 'scroll' || $offsetParent.css( 'overflow-y' ) === 'auto';
4669
4670 vertScrollbarWidth = $offsetParent.innerWidth() - $offsetParent.prop( 'clientWidth' );
4671 horizScrollbarHeight = $offsetParent.innerHeight() - $offsetParent.prop( 'clientHeight' );
4672 // We don't need to compute and add scrollTop and scrollLeft if the scrollable container is the body,
4673 // or if it isn't scrollable
4674 scrollTop = scrollableY && !isBody ? $offsetParent.scrollTop() : 0;
4675 scrollLeft = scrollableX && !isBody ? OO.ui.Element.static.getScrollLeft( $offsetParent[ 0 ] ) : 0;
4676
4677 // Avoid passing the <body> to getRelativePosition(), because it won't return what we expect
4678 // if the <body> has a margin
4679 containerPos = isBody ?
4680 this.$floatableContainer.offset() :
4681 OO.ui.Element.static.getRelativePosition( this.$floatableContainer, $offsetParent );
4682 containerPos.bottom = containerPos.top + this.$floatableContainer.outerHeight();
4683 containerPos.right = containerPos.left + this.$floatableContainer.outerWidth();
4684 containerPos.start = direction === 'rtl' ? containerPos.right : containerPos.left;
4685 containerPos.end = direction === 'rtl' ? containerPos.left : containerPos.right;
4686
4687 if ( this.verticalPosition === 'below' ) {
4688 newPos.top = containerPos.bottom;
4689 } else if ( this.verticalPosition === 'above' ) {
4690 newPos.bottom = $offsetParent.outerHeight() - containerPos.top;
4691 } else if ( this.verticalPosition === 'top' ) {
4692 newPos.top = containerPos.top;
4693 } else if ( this.verticalPosition === 'bottom' ) {
4694 newPos.bottom = $offsetParent.outerHeight() - containerPos.bottom;
4695 } else if ( this.verticalPosition === 'center' ) {
4696 newPos.top = containerPos.top +
4697 ( this.$floatableContainer.height() - this.$floatable.height() ) / 2;
4698 }
4699
4700 if ( this.horizontalPosition === 'before' ) {
4701 newPos.end = containerPos.start;
4702 } else if ( this.horizontalPosition === 'after' ) {
4703 newPos.start = containerPos.end;
4704 } else if ( this.horizontalPosition === 'start' ) {
4705 newPos.start = containerPos.start;
4706 } else if ( this.horizontalPosition === 'end' ) {
4707 newPos.end = containerPos.end;
4708 } else if ( this.horizontalPosition === 'center' ) {
4709 newPos.left = containerPos.left +
4710 ( this.$floatableContainer.width() - this.$floatable.width() ) / 2;
4711 }
4712
4713 if ( newPos.start !== undefined ) {
4714 if ( direction === 'rtl' ) {
4715 newPos.right = ( isBody ? $( $offsetParent[ 0 ].ownerDocument.documentElement ) : $offsetParent ).outerWidth() - newPos.start;
4716 } else {
4717 newPos.left = newPos.start;
4718 }
4719 delete newPos.start;
4720 }
4721 if ( newPos.end !== undefined ) {
4722 if ( direction === 'rtl' ) {
4723 newPos.left = newPos.end;
4724 } else {
4725 newPos.right = ( isBody ? $( $offsetParent[ 0 ].ownerDocument.documentElement ) : $offsetParent ).outerWidth() - newPos.end;
4726 }
4727 delete newPos.end;
4728 }
4729
4730 // Account for scroll position
4731 if ( newPos.top !== '' ) {
4732 newPos.top += scrollTop;
4733 }
4734 if ( newPos.bottom !== '' ) {
4735 newPos.bottom -= scrollTop;
4736 }
4737 if ( newPos.left !== '' ) {
4738 newPos.left += scrollLeft;
4739 }
4740 if ( newPos.right !== '' ) {
4741 newPos.right -= scrollLeft;
4742 }
4743
4744 // Account for scrollbar gutter
4745 if ( newPos.bottom !== '' ) {
4746 newPos.bottom -= horizScrollbarHeight;
4747 }
4748 if ( direction === 'rtl' ) {
4749 if ( newPos.left !== '' ) {
4750 newPos.left -= vertScrollbarWidth;
4751 }
4752 } else {
4753 if ( newPos.right !== '' ) {
4754 newPos.right -= vertScrollbarWidth;
4755 }
4756 }
4757
4758 return newPos;
4759 };
4760
4761 /**
4762 * Element that can be automatically clipped to visible boundaries.
4763 *
4764 * Whenever the element's natural height changes, you have to call
4765 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
4766 * clipping correctly.
4767 *
4768 * The dimensions of #$clippableContainer will be compared to the boundaries of the
4769 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
4770 * then #$clippable will be given a fixed reduced height and/or width and will be made
4771 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
4772 * but you can build a static footer by setting #$clippableContainer to an element that contains
4773 * #$clippable and the footer.
4774 *
4775 * @abstract
4776 * @class
4777 *
4778 * @constructor
4779 * @param {Object} [config] Configuration options
4780 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
4781 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
4782 * omit to use #$clippable
4783 */
4784 OO.ui.mixin.ClippableElement = function OoUiMixinClippableElement( config ) {
4785 // Configuration initialization
4786 config = config || {};
4787
4788 // Properties
4789 this.$clippable = null;
4790 this.$clippableContainer = null;
4791 this.clipping = false;
4792 this.clippedHorizontally = false;
4793 this.clippedVertically = false;
4794 this.$clippableScrollableContainer = null;
4795 this.$clippableScroller = null;
4796 this.$clippableWindow = null;
4797 this.idealWidth = null;
4798 this.idealHeight = null;
4799 this.onClippableScrollHandler = this.clip.bind( this );
4800 this.onClippableWindowResizeHandler = this.clip.bind( this );
4801
4802 // Initialization
4803 if ( config.$clippableContainer ) {
4804 this.setClippableContainer( config.$clippableContainer );
4805 }
4806 this.setClippableElement( config.$clippable || this.$element );
4807 };
4808
4809 /* Methods */
4810
4811 /**
4812 * Set clippable element.
4813 *
4814 * If an element is already set, it will be cleaned up before setting up the new element.
4815 *
4816 * @param {jQuery} $clippable Element to make clippable
4817 */
4818 OO.ui.mixin.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
4819 if ( this.$clippable ) {
4820 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
4821 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
4822 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
4823 }
4824
4825 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
4826 this.clip();
4827 };
4828
4829 /**
4830 * Set clippable container.
4831 *
4832 * This is the container that will be measured when deciding whether to clip. When clipping,
4833 * #$clippable will be resized in order to keep the clippable container fully visible.
4834 *
4835 * If the clippable container is unset, #$clippable will be used.
4836 *
4837 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
4838 */
4839 OO.ui.mixin.ClippableElement.prototype.setClippableContainer = function ( $clippableContainer ) {
4840 this.$clippableContainer = $clippableContainer;
4841 if ( this.$clippable ) {
4842 this.clip();
4843 }
4844 };
4845
4846 /**
4847 * Toggle clipping.
4848 *
4849 * Do not turn clipping on until after the element is attached to the DOM and visible.
4850 *
4851 * @param {boolean} [clipping] Enable clipping, omit to toggle
4852 * @chainable
4853 * @return {OO.ui.Element} The element, for chaining
4854 */
4855 OO.ui.mixin.ClippableElement.prototype.toggleClipping = function ( clipping ) {
4856 clipping = clipping === undefined ? !this.clipping : !!clipping;
4857
4858 if ( clipping && !this.warnedUnattached && !this.isElementAttached() ) {
4859 OO.ui.warnDeprecation( 'ClippableElement#toggleClipping: Before calling this method, the element must be attached to the DOM.' );
4860 this.warnedUnattached = true;
4861 }
4862
4863 if ( this.clipping !== clipping ) {
4864 this.clipping = clipping;
4865 if ( clipping ) {
4866 this.$clippableScrollableContainer = $( this.getClosestScrollableElementContainer() );
4867 // If the clippable container is the root, we have to listen to scroll events and check
4868 // jQuery.scrollTop on the window because of browser inconsistencies
4869 this.$clippableScroller = this.$clippableScrollableContainer.is( 'html, body' ) ?
4870 $( OO.ui.Element.static.getWindow( this.$clippableScrollableContainer ) ) :
4871 this.$clippableScrollableContainer;
4872 this.$clippableScroller.on( 'scroll', this.onClippableScrollHandler );
4873 this.$clippableWindow = $( this.getElementWindow() )
4874 .on( 'resize', this.onClippableWindowResizeHandler );
4875 // Initial clip after visible
4876 this.clip();
4877 } else {
4878 this.$clippable.css( {
4879 width: '',
4880 height: '',
4881 maxWidth: '',
4882 maxHeight: '',
4883 overflowX: '',
4884 overflowY: ''
4885 } );
4886 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
4887
4888 this.$clippableScrollableContainer = null;
4889 this.$clippableScroller.off( 'scroll', this.onClippableScrollHandler );
4890 this.$clippableScroller = null;
4891 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
4892 this.$clippableWindow = null;
4893 }
4894 }
4895
4896 return this;
4897 };
4898
4899 /**
4900 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4901 *
4902 * @return {boolean} Element will be clipped to the visible area
4903 */
4904 OO.ui.mixin.ClippableElement.prototype.isClipping = function () {
4905 return this.clipping;
4906 };
4907
4908 /**
4909 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
4910 *
4911 * @return {boolean} Part of the element is being clipped
4912 */
4913 OO.ui.mixin.ClippableElement.prototype.isClipped = function () {
4914 return this.clippedHorizontally || this.clippedVertically;
4915 };
4916
4917 /**
4918 * Check if the right of the element is being clipped by the nearest scrollable container.
4919 *
4920 * @return {boolean} Part of the element is being clipped
4921 */
4922 OO.ui.mixin.ClippableElement.prototype.isClippedHorizontally = function () {
4923 return this.clippedHorizontally;
4924 };
4925
4926 /**
4927 * Check if the bottom of the element is being clipped by the nearest scrollable container.
4928 *
4929 * @return {boolean} Part of the element is being clipped
4930 */
4931 OO.ui.mixin.ClippableElement.prototype.isClippedVertically = function () {
4932 return this.clippedVertically;
4933 };
4934
4935 /**
4936 * Set the ideal size. These are the dimensions #$clippable will have when it's not being clipped.
4937 *
4938 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
4939 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
4940 */
4941 OO.ui.mixin.ClippableElement.prototype.setIdealSize = function ( width, height ) {
4942 this.idealWidth = width;
4943 this.idealHeight = height;
4944
4945 if ( !this.clipping ) {
4946 // Update dimensions
4947 this.$clippable.css( { width: width, height: height } );
4948 }
4949 // While clipping, idealWidth and idealHeight are not considered
4950 };
4951
4952 /**
4953 * Return the side of the clippable on which it is "anchored" (aligned to something else).
4954 * ClippableElement will clip the opposite side when reducing element's width.
4955 *
4956 * Classes that mix in ClippableElement should override this to return 'right' if their
4957 * clippable is absolutely positioned and using 'right: Npx' (and not using 'left').
4958 * If your class also mixes in FloatableElement, this is handled automatically.
4959 *
4960 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
4961 * always in pixels, even if they were unset or set to 'auto'.)
4962 *
4963 * When in doubt, 'left' (or 'right' in RTL) is a sane fallback.
4964 *
4965 * @return {string} 'left' or 'right'
4966 */
4967 OO.ui.mixin.ClippableElement.prototype.getHorizontalAnchorEdge = function () {
4968 if ( this.computePosition && this.positioning && this.computePosition().right !== '' ) {
4969 return 'right';
4970 }
4971 return 'left';
4972 };
4973
4974 /**
4975 * Return the side of the clippable on which it is "anchored" (aligned to something else).
4976 * ClippableElement will clip the opposite side when reducing element's width.
4977 *
4978 * Classes that mix in ClippableElement should override this to return 'bottom' if their
4979 * clippable is absolutely positioned and using 'bottom: Npx' (and not using 'top').
4980 * If your class also mixes in FloatableElement, this is handled automatically.
4981 *
4982 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
4983 * always in pixels, even if they were unset or set to 'auto'.)
4984 *
4985 * When in doubt, 'top' is a sane fallback.
4986 *
4987 * @return {string} 'top' or 'bottom'
4988 */
4989 OO.ui.mixin.ClippableElement.prototype.getVerticalAnchorEdge = function () {
4990 if ( this.computePosition && this.positioning && this.computePosition().bottom !== '' ) {
4991 return 'bottom';
4992 }
4993 return 'top';
4994 };
4995
4996 /**
4997 * Clip element to visible boundaries and allow scrolling when needed. You should call this method
4998 * when the element's natural height changes.
4999 *
5000 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
5001 * overlapped by, the visible area of the nearest scrollable container.
5002 *
5003 * Because calling clip() when the natural height changes isn't always possible, we also set
5004 * max-height when the element isn't being clipped. This means that if the element tries to grow
5005 * beyond the edge, something reasonable will happen before clip() is called.
5006 *
5007 * @chainable
5008 * @return {OO.ui.Element} The element, for chaining
5009 */
5010 OO.ui.mixin.ClippableElement.prototype.clip = function () {
5011 var extraHeight, extraWidth, viewportSpacing,
5012 desiredWidth, desiredHeight, allotedWidth, allotedHeight,
5013 naturalWidth, naturalHeight, clipWidth, clipHeight,
5014 $item, itemRect, $viewport, viewportRect, availableRect,
5015 direction, vertScrollbarWidth, horizScrollbarHeight,
5016 // Extra tolerance so that the sloppy code below doesn't result in results that are off
5017 // by one or two pixels. (And also so that we have space to display drop shadows.)
5018 // Chosen by fair dice roll.
5019 buffer = 7;
5020
5021 if ( !this.clipping ) {
5022 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
5023 return this;
5024 }
5025
5026 function rectIntersection( a, b ) {
5027 var out = {};
5028 out.top = Math.max( a.top, b.top );
5029 out.left = Math.max( a.left, b.left );
5030 out.bottom = Math.min( a.bottom, b.bottom );
5031 out.right = Math.min( a.right, b.right );
5032 return out;
5033 }
5034
5035 viewportSpacing = OO.ui.getViewportSpacing();
5036
5037 if ( this.$clippableScrollableContainer.is( 'html, body' ) ) {
5038 $viewport = $( this.$clippableScrollableContainer[ 0 ].ownerDocument.body );
5039 // Dimensions of the browser window, rather than the element!
5040 viewportRect = {
5041 top: 0,
5042 left: 0,
5043 right: document.documentElement.clientWidth,
5044 bottom: document.documentElement.clientHeight
5045 };
5046 viewportRect.top += viewportSpacing.top;
5047 viewportRect.left += viewportSpacing.left;
5048 viewportRect.right -= viewportSpacing.right;
5049 viewportRect.bottom -= viewportSpacing.bottom;
5050 } else {
5051 $viewport = this.$clippableScrollableContainer;
5052 viewportRect = $viewport[ 0 ].getBoundingClientRect();
5053 // Convert into a plain object
5054 viewportRect = $.extend( {}, viewportRect );
5055 }
5056
5057 // Account for scrollbar gutter
5058 direction = $viewport.css( 'direction' );
5059 vertScrollbarWidth = $viewport.innerWidth() - $viewport.prop( 'clientWidth' );
5060 horizScrollbarHeight = $viewport.innerHeight() - $viewport.prop( 'clientHeight' );
5061 viewportRect.bottom -= horizScrollbarHeight;
5062 if ( direction === 'rtl' ) {
5063 viewportRect.left += vertScrollbarWidth;
5064 } else {
5065 viewportRect.right -= vertScrollbarWidth;
5066 }
5067
5068 // Add arbitrary tolerance
5069 viewportRect.top += buffer;
5070 viewportRect.left += buffer;
5071 viewportRect.right -= buffer;
5072 viewportRect.bottom -= buffer;
5073
5074 $item = this.$clippableContainer || this.$clippable;
5075
5076 extraHeight = $item.outerHeight() - this.$clippable.outerHeight();
5077 extraWidth = $item.outerWidth() - this.$clippable.outerWidth();
5078
5079 itemRect = $item[ 0 ].getBoundingClientRect();
5080 // Convert into a plain object
5081 itemRect = $.extend( {}, itemRect );
5082
5083 // Item might already be clipped, so we can't just use its dimensions (in case we might need to
5084 // make it larger than before). Extend the rectangle to the maximum size we are allowed to take.
5085 if ( this.getHorizontalAnchorEdge() === 'right' ) {
5086 itemRect.left = viewportRect.left;
5087 } else {
5088 itemRect.right = viewportRect.right;
5089 }
5090 if ( this.getVerticalAnchorEdge() === 'bottom' ) {
5091 itemRect.top = viewportRect.top;
5092 } else {
5093 itemRect.bottom = viewportRect.bottom;
5094 }
5095
5096 availableRect = rectIntersection( viewportRect, itemRect );
5097
5098 desiredWidth = Math.max( 0, availableRect.right - availableRect.left );
5099 desiredHeight = Math.max( 0, availableRect.bottom - availableRect.top );
5100 // It should never be desirable to exceed the dimensions of the browser viewport... right?
5101 desiredWidth = Math.min( desiredWidth,
5102 document.documentElement.clientWidth - viewportSpacing.left - viewportSpacing.right );
5103 desiredHeight = Math.min( desiredHeight,
5104 document.documentElement.clientHeight - viewportSpacing.top - viewportSpacing.right );
5105 allotedWidth = Math.ceil( desiredWidth - extraWidth );
5106 allotedHeight = Math.ceil( desiredHeight - extraHeight );
5107 naturalWidth = this.$clippable.prop( 'scrollWidth' );
5108 naturalHeight = this.$clippable.prop( 'scrollHeight' );
5109 clipWidth = allotedWidth < naturalWidth;
5110 clipHeight = allotedHeight < naturalHeight;
5111
5112 if ( clipWidth ) {
5113 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. See T157672.
5114 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
5115 this.$clippable.css( 'overflowX', 'scroll' );
5116 void this.$clippable[ 0 ].offsetHeight; // Force reflow
5117 this.$clippable.css( {
5118 width: Math.max( 0, allotedWidth ),
5119 maxWidth: ''
5120 } );
5121 } else {
5122 this.$clippable.css( {
5123 overflowX: '',
5124 width: this.idealWidth || '',
5125 maxWidth: Math.max( 0, allotedWidth )
5126 } );
5127 }
5128 if ( clipHeight ) {
5129 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. See T157672.
5130 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
5131 this.$clippable.css( 'overflowY', 'scroll' );
5132 void this.$clippable[ 0 ].offsetHeight; // Force reflow
5133 this.$clippable.css( {
5134 height: Math.max( 0, allotedHeight ),
5135 maxHeight: ''
5136 } );
5137 } else {
5138 this.$clippable.css( {
5139 overflowY: '',
5140 height: this.idealHeight || '',
5141 maxHeight: Math.max( 0, allotedHeight )
5142 } );
5143 }
5144
5145 // If we stopped clipping in at least one of the dimensions
5146 if ( ( this.clippedHorizontally && !clipWidth ) || ( this.clippedVertically && !clipHeight ) ) {
5147 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
5148 }
5149
5150 this.clippedHorizontally = clipWidth;
5151 this.clippedVertically = clipHeight;
5152
5153 return this;
5154 };
5155
5156 /**
5157 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
5158 * By default, each popup has an anchor that points toward its origin.
5159 * Please see the [OOUI documentation on MediaWiki.org] [1] for more information and examples.
5160 *
5161 * Unlike most widgets, PopupWidget is initially hidden and must be shown by calling #toggle.
5162 *
5163 * @example
5164 * // A popup widget.
5165 * var popup = new OO.ui.PopupWidget( {
5166 * $content: $( '<p>Hi there!</p>' ),
5167 * padded: true,
5168 * width: 300
5169 * } );
5170 *
5171 * $( 'body' ).append( popup.$element );
5172 * // To display the popup, toggle the visibility to 'true'.
5173 * popup.toggle( true );
5174 *
5175 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups
5176 *
5177 * @class
5178 * @extends OO.ui.Widget
5179 * @mixins OO.ui.mixin.LabelElement
5180 * @mixins OO.ui.mixin.ClippableElement
5181 * @mixins OO.ui.mixin.FloatableElement
5182 *
5183 * @constructor
5184 * @param {Object} [config] Configuration options
5185 * @cfg {number|null} [width=320] Width of popup in pixels. Pass `null` to use automatic width.
5186 * @cfg {number|null} [height=null] Height of popup in pixels. Pass `null` to use automatic height.
5187 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
5188 * @cfg {string} [position='below'] Where to position the popup relative to $floatableContainer
5189 * 'above': Put popup above $floatableContainer; anchor points down to the horizontal center
5190 * of $floatableContainer
5191 * 'below': Put popup below $floatableContainer; anchor points up to the horizontal center
5192 * of $floatableContainer
5193 * 'before': Put popup to the left (LTR) / right (RTL) of $floatableContainer; anchor points
5194 * endwards (right/left) to the vertical center of $floatableContainer
5195 * 'after': Put popup to the right (LTR) / left (RTL) of $floatableContainer; anchor points
5196 * startwards (left/right) to the vertical center of $floatableContainer
5197 * @cfg {string} [align='center'] How to align the popup to $floatableContainer
5198 * 'forwards': If position is above/below, move the popup as far endwards (right in LTR, left in RTL)
5199 * as possible while still keeping the anchor within the popup;
5200 * if position is before/after, move the popup as far downwards as possible.
5201 * 'backwards': If position is above/below, move the popup as far startwards (left in LTR, right in RTL)
5202 * as possible while still keeping the anchor within the popup;
5203 * if position in before/after, move the popup as far upwards as possible.
5204 * 'center': Horizontally (if position is above/below) or vertically (before/after) align the center
5205 * of the popup with the center of $floatableContainer.
5206 * 'force-left': Alias for 'forwards' in LTR and 'backwards' in RTL
5207 * 'force-right': Alias for 'backwards' in RTL and 'forwards' in LTR
5208 * @cfg {boolean} [autoFlip=true] Whether to automatically switch the popup's position between
5209 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5210 * desired direction to display the popup without clipping
5211 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
5212 * See the [OOUI docs on MediaWiki][3] for an example.
5213 * [3]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#containerExample
5214 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
5215 * @cfg {jQuery} [$content] Content to append to the popup's body
5216 * @cfg {jQuery} [$footer] Content to append to the popup's footer
5217 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
5218 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
5219 * This config option is only relevant if #autoClose is set to `true`. See the [OOUI documentation on MediaWiki][2]
5220 * for an example.
5221 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#autocloseExample
5222 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
5223 * button.
5224 * @cfg {boolean} [padded=false] Add padding to the popup's body
5225 */
5226 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
5227 // Configuration initialization
5228 config = config || {};
5229
5230 // Parent constructor
5231 OO.ui.PopupWidget.parent.call( this, config );
5232
5233 // Properties (must be set before ClippableElement constructor call)
5234 this.$body = $( '<div>' );
5235 this.$popup = $( '<div>' );
5236
5237 // Mixin constructors
5238 OO.ui.mixin.LabelElement.call( this, config );
5239 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, {
5240 $clippable: this.$body,
5241 $clippableContainer: this.$popup
5242 } ) );
5243 OO.ui.mixin.FloatableElement.call( this, config );
5244
5245 // Properties
5246 this.$anchor = $( '<div>' );
5247 // If undefined, will be computed lazily in computePosition()
5248 this.$container = config.$container;
5249 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
5250 this.autoClose = !!config.autoClose;
5251 this.transitionTimeout = null;
5252 this.anchored = false;
5253 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
5254 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
5255
5256 // Initialization
5257 this.setSize( config.width, config.height );
5258 this.toggleAnchor( config.anchor === undefined || config.anchor );
5259 this.setAlignment( config.align || 'center' );
5260 this.setPosition( config.position || 'below' );
5261 this.setAutoFlip( config.autoFlip === undefined || config.autoFlip );
5262 this.setAutoCloseIgnore( config.$autoCloseIgnore );
5263 this.$body.addClass( 'oo-ui-popupWidget-body' );
5264 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
5265 this.$popup
5266 .addClass( 'oo-ui-popupWidget-popup' )
5267 .append( this.$body );
5268 this.$element
5269 .addClass( 'oo-ui-popupWidget' )
5270 .append( this.$popup, this.$anchor );
5271 // Move content, which was added to #$element by OO.ui.Widget, to the body
5272 // FIXME This is gross, we should use '$body' or something for the config
5273 if ( config.$content instanceof jQuery ) {
5274 this.$body.append( config.$content );
5275 }
5276
5277 if ( config.padded ) {
5278 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
5279 }
5280
5281 if ( config.head ) {
5282 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
5283 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
5284 this.$head = $( '<div>' )
5285 .addClass( 'oo-ui-popupWidget-head' )
5286 .append( this.$label, this.closeButton.$element );
5287 this.$popup.prepend( this.$head );
5288 }
5289
5290 if ( config.$footer ) {
5291 this.$footer = $( '<div>' )
5292 .addClass( 'oo-ui-popupWidget-footer' )
5293 .append( config.$footer );
5294 this.$popup.append( this.$footer );
5295 }
5296
5297 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
5298 // that reference properties not initialized at that time of parent class construction
5299 // TODO: Find a better way to handle post-constructor setup
5300 this.visible = false;
5301 this.$element.addClass( 'oo-ui-element-hidden' );
5302 };
5303
5304 /* Setup */
5305
5306 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
5307 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.LabelElement );
5308 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.ClippableElement );
5309 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.FloatableElement );
5310
5311 /* Events */
5312
5313 /**
5314 * @event ready
5315 *
5316 * The popup is ready: it is visible and has been positioned and clipped.
5317 */
5318
5319 /* Methods */
5320
5321 /**
5322 * Handles document mouse down events.
5323 *
5324 * @private
5325 * @param {MouseEvent} e Mouse down event
5326 */
5327 OO.ui.PopupWidget.prototype.onDocumentMouseDown = function ( e ) {
5328 if (
5329 this.isVisible() &&
5330 !OO.ui.contains( this.$element.add( this.$autoCloseIgnore ).get(), e.target, true )
5331 ) {
5332 this.toggle( false );
5333 }
5334 };
5335
5336 // Deprecated alias since 0.28.3
5337 OO.ui.PopupWidget.prototype.onMouseDown = function () {
5338 OO.ui.warnDeprecation( 'onMouseDown is deprecated, use onDocumentMouseDown instead' );
5339 this.onDocumentMouseDown.apply( this, arguments );
5340 };
5341
5342 /**
5343 * Bind document mouse down listener.
5344 *
5345 * @private
5346 */
5347 OO.ui.PopupWidget.prototype.bindDocumentMouseDownListener = function () {
5348 // Capture clicks outside popup
5349 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
5350 // We add 'click' event because iOS safari needs to respond to this event.
5351 // We can't use 'touchstart' (as is usually the equivalent to 'mousedown') because
5352 // then it will trigger when scrolling. While iOS Safari has some reported behavior
5353 // of occasionally not emitting 'click' properly, that event seems to be the standard
5354 // that it should be emitting, so we add it to this and will operate the event handler
5355 // on whichever of these events was triggered first
5356 this.getElementDocument().addEventListener( 'click', this.onDocumentMouseDownHandler, true );
5357 };
5358
5359 // Deprecated alias since 0.28.3
5360 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
5361 OO.ui.warnDeprecation( 'bindMouseDownListener is deprecated, use bindDocumentMouseDownListener instead' );
5362 this.bindDocumentMouseDownListener.apply( this, arguments );
5363 };
5364
5365 /**
5366 * Handles close button click events.
5367 *
5368 * @private
5369 */
5370 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
5371 if ( this.isVisible() ) {
5372 this.toggle( false );
5373 }
5374 };
5375
5376 /**
5377 * Unbind document mouse down listener.
5378 *
5379 * @private
5380 */
5381 OO.ui.PopupWidget.prototype.unbindDocumentMouseDownListener = function () {
5382 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
5383 this.getElementDocument().removeEventListener( 'click', this.onDocumentMouseDownHandler, true );
5384 };
5385
5386 // Deprecated alias since 0.28.3
5387 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
5388 OO.ui.warnDeprecation( 'unbindMouseDownListener is deprecated, use unbindDocumentMouseDownListener instead' );
5389 this.unbindDocumentMouseDownListener.apply( this, arguments );
5390 };
5391
5392 /**
5393 * Handles document key down events.
5394 *
5395 * @private
5396 * @param {KeyboardEvent} e Key down event
5397 */
5398 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
5399 if (
5400 e.which === OO.ui.Keys.ESCAPE &&
5401 this.isVisible()
5402 ) {
5403 this.toggle( false );
5404 e.preventDefault();
5405 e.stopPropagation();
5406 }
5407 };
5408
5409 /**
5410 * Bind document key down listener.
5411 *
5412 * @private
5413 */
5414 OO.ui.PopupWidget.prototype.bindDocumentKeyDownListener = function () {
5415 this.getElementDocument().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
5416 };
5417
5418 // Deprecated alias since 0.28.3
5419 OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
5420 OO.ui.warnDeprecation( 'bindKeyDownListener is deprecated, use bindDocumentKeyDownListener instead' );
5421 this.bindDocumentKeyDownListener.apply( this, arguments );
5422 };
5423
5424 /**
5425 * Unbind document key down listener.
5426 *
5427 * @private
5428 */
5429 OO.ui.PopupWidget.prototype.unbindDocumentKeyDownListener = function () {
5430 this.getElementDocument().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
5431 };
5432
5433 // Deprecated alias since 0.28.3
5434 OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
5435 OO.ui.warnDeprecation( 'unbindKeyDownListener is deprecated, use unbindDocumentKeyDownListener instead' );
5436 this.unbindDocumentKeyDownListener.apply( this, arguments );
5437 };
5438
5439 /**
5440 * Show, hide, or toggle the visibility of the anchor.
5441 *
5442 * @param {boolean} [show] Show anchor, omit to toggle
5443 */
5444 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
5445 show = show === undefined ? !this.anchored : !!show;
5446
5447 if ( this.anchored !== show ) {
5448 if ( show ) {
5449 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
5450 this.$element.addClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge );
5451 } else {
5452 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
5453 this.$element.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge );
5454 }
5455 this.anchored = show;
5456 }
5457 };
5458
5459 /**
5460 * Change which edge the anchor appears on.
5461 *
5462 * @param {string} edge 'top', 'bottom', 'start' or 'end'
5463 */
5464 OO.ui.PopupWidget.prototype.setAnchorEdge = function ( edge ) {
5465 if ( [ 'top', 'bottom', 'start', 'end' ].indexOf( edge ) === -1 ) {
5466 throw new Error( 'Invalid value for edge: ' + edge );
5467 }
5468 if ( this.anchorEdge !== null ) {
5469 this.$element.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge );
5470 }
5471 this.anchorEdge = edge;
5472 if ( this.anchored ) {
5473 this.$element.addClass( 'oo-ui-popupWidget-anchored-' + edge );
5474 }
5475 };
5476
5477 /**
5478 * Check if the anchor is visible.
5479 *
5480 * @return {boolean} Anchor is visible
5481 */
5482 OO.ui.PopupWidget.prototype.hasAnchor = function () {
5483 return this.anchored;
5484 };
5485
5486 /**
5487 * Toggle visibility of the popup. The popup is initially hidden and must be shown by calling
5488 * `.toggle( true )` after its #$element is attached to the DOM.
5489 *
5490 * Do not show the popup while it is not attached to the DOM. The calculations required to display
5491 * it in the right place and with the right dimensions only work correctly while it is attached.
5492 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
5493 * strictly enforced, so currently it only generates a warning in the browser console.
5494 *
5495 * @fires ready
5496 * @inheritdoc
5497 */
5498 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
5499 var change, normalHeight, oppositeHeight, normalWidth, oppositeWidth;
5500 show = show === undefined ? !this.isVisible() : !!show;
5501
5502 change = show !== this.isVisible();
5503
5504 if ( show && !this.warnedUnattached && !this.isElementAttached() ) {
5505 OO.ui.warnDeprecation( 'PopupWidget#toggle: Before calling this method, the popup must be attached to the DOM.' );
5506 this.warnedUnattached = true;
5507 }
5508 if ( show && !this.$floatableContainer && this.isElementAttached() ) {
5509 // Fall back to the parent node if the floatableContainer is not set
5510 this.setFloatableContainer( this.$element.parent() );
5511 }
5512
5513 if ( change && show && this.autoFlip ) {
5514 // Reset auto-flipping before showing the popup again. It's possible we no longer need to flip
5515 // (e.g. if the user scrolled).
5516 this.isAutoFlipped = false;
5517 }
5518
5519 // Parent method
5520 OO.ui.PopupWidget.parent.prototype.toggle.call( this, show );
5521
5522 if ( change ) {
5523 this.togglePositioning( show && !!this.$floatableContainer );
5524
5525 if ( show ) {
5526 if ( this.autoClose ) {
5527 this.bindDocumentMouseDownListener();
5528 this.bindDocumentKeyDownListener();
5529 }
5530 this.updateDimensions();
5531 this.toggleClipping( true );
5532
5533 if ( this.autoFlip ) {
5534 if ( this.popupPosition === 'above' || this.popupPosition === 'below' ) {
5535 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5536 // If opening the popup in the normal direction causes it to be clipped, open
5537 // in the opposite one instead
5538 normalHeight = this.$element.height();
5539 this.isAutoFlipped = !this.isAutoFlipped;
5540 this.position();
5541 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5542 // If that also causes it to be clipped, open in whichever direction
5543 // we have more space
5544 oppositeHeight = this.$element.height();
5545 if ( oppositeHeight < normalHeight ) {
5546 this.isAutoFlipped = !this.isAutoFlipped;
5547 this.position();
5548 }
5549 }
5550 }
5551 }
5552 if ( this.popupPosition === 'before' || this.popupPosition === 'after' ) {
5553 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5554 // If opening the popup in the normal direction causes it to be clipped, open
5555 // in the opposite one instead
5556 normalWidth = this.$element.width();
5557 this.isAutoFlipped = !this.isAutoFlipped;
5558 // Due to T180173 horizontally clipped PopupWidgets have messed up dimensions,
5559 // which causes positioning to be off. Toggle clipping back and fort to work around.
5560 this.toggleClipping( false );
5561 this.position();
5562 this.toggleClipping( true );
5563 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5564 // If that also causes it to be clipped, open in whichever direction
5565 // we have more space
5566 oppositeWidth = this.$element.width();
5567 if ( oppositeWidth < normalWidth ) {
5568 this.isAutoFlipped = !this.isAutoFlipped;
5569 // Due to T180173 horizontally clipped PopupWidgets have messed up dimensions,
5570 // which causes positioning to be off. Toggle clipping back and fort to work around.
5571 this.toggleClipping( false );
5572 this.position();
5573 this.toggleClipping( true );
5574 }
5575 }
5576 }
5577 }
5578 }
5579
5580 this.emit( 'ready' );
5581 } else {
5582 this.toggleClipping( false );
5583 if ( this.autoClose ) {
5584 this.unbindDocumentMouseDownListener();
5585 this.unbindDocumentKeyDownListener();
5586 }
5587 }
5588 }
5589
5590 return this;
5591 };
5592
5593 /**
5594 * Set the size of the popup.
5595 *
5596 * Changing the size may also change the popup's position depending on the alignment.
5597 *
5598 * @param {number|null} [width=320] Width in pixels. Pass `null` to use automatic width.
5599 * @param {number|null} [height=null] Height in pixels. Pass `null` to use automatic height.
5600 * @param {boolean} [transition=false] Use a smooth transition
5601 * @chainable
5602 */
5603 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
5604 this.width = width !== undefined ? width : 320;
5605 this.height = height !== undefined ? height : null;
5606 if ( this.isVisible() ) {
5607 this.updateDimensions( transition );
5608 }
5609 };
5610
5611 /**
5612 * Update the size and position.
5613 *
5614 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
5615 * be called automatically.
5616 *
5617 * @param {boolean} [transition=false] Use a smooth transition
5618 * @chainable
5619 */
5620 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
5621 var widget = this;
5622
5623 // Prevent transition from being interrupted
5624 clearTimeout( this.transitionTimeout );
5625 if ( transition ) {
5626 // Enable transition
5627 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
5628 }
5629
5630 this.position();
5631
5632 if ( transition ) {
5633 // Prevent transitioning after transition is complete
5634 this.transitionTimeout = setTimeout( function () {
5635 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
5636 }, 200 );
5637 } else {
5638 // Prevent transitioning immediately
5639 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
5640 }
5641 };
5642
5643 /**
5644 * @inheritdoc
5645 */
5646 OO.ui.PopupWidget.prototype.computePosition = function () {
5647 var direction, align, vertical, start, end, near, far, sizeProp, popupSize, anchorSize, anchorPos,
5648 anchorOffset, anchorMargin, parentPosition, positionProp, positionAdjustment, floatablePos,
5649 offsetParentPos, containerPos, popupPosition, viewportSpacing,
5650 popupPos = {},
5651 anchorCss = { left: '', right: '', top: '', bottom: '' },
5652 popupPositionOppositeMap = {
5653 above: 'below',
5654 below: 'above',
5655 before: 'after',
5656 after: 'before'
5657 },
5658 alignMap = {
5659 ltr: {
5660 'force-left': 'backwards',
5661 'force-right': 'forwards'
5662 },
5663 rtl: {
5664 'force-left': 'forwards',
5665 'force-right': 'backwards'
5666 }
5667 },
5668 anchorEdgeMap = {
5669 above: 'bottom',
5670 below: 'top',
5671 before: 'end',
5672 after: 'start'
5673 },
5674 hPosMap = {
5675 forwards: 'start',
5676 center: 'center',
5677 backwards: this.anchored ? 'before' : 'end'
5678 },
5679 vPosMap = {
5680 forwards: 'top',
5681 center: 'center',
5682 backwards: 'bottom'
5683 };
5684
5685 if ( !this.$container ) {
5686 // Lazy-initialize $container if not specified in constructor
5687 this.$container = $( this.getClosestScrollableElementContainer() );
5688 }
5689 direction = this.$container.css( 'direction' );
5690
5691 // Set height and width before we do anything else, since it might cause our measurements
5692 // to change (e.g. due to scrollbars appearing or disappearing), and it also affects centering
5693 this.$popup.css( {
5694 width: this.width !== null ? this.width : 'auto',
5695 height: this.height !== null ? this.height : 'auto'
5696 } );
5697
5698 align = alignMap[ direction ][ this.align ] || this.align;
5699 popupPosition = this.popupPosition;
5700 if ( this.isAutoFlipped ) {
5701 popupPosition = popupPositionOppositeMap[ popupPosition ];
5702 }
5703
5704 // If the popup is positioned before or after, then the anchor positioning is vertical, otherwise horizontal
5705 vertical = popupPosition === 'before' || popupPosition === 'after';
5706 start = vertical ? 'top' : ( direction === 'rtl' ? 'right' : 'left' );
5707 end = vertical ? 'bottom' : ( direction === 'rtl' ? 'left' : 'right' );
5708 near = vertical ? 'top' : 'left';
5709 far = vertical ? 'bottom' : 'right';
5710 sizeProp = vertical ? 'Height' : 'Width';
5711 popupSize = vertical ? ( this.height || this.$popup.height() ) : ( this.width || this.$popup.width() );
5712
5713 this.setAnchorEdge( anchorEdgeMap[ popupPosition ] );
5714 this.horizontalPosition = vertical ? popupPosition : hPosMap[ align ];
5715 this.verticalPosition = vertical ? vPosMap[ align ] : popupPosition;
5716
5717 // Parent method
5718 parentPosition = OO.ui.mixin.FloatableElement.prototype.computePosition.call( this );
5719 // Find out which property FloatableElement used for positioning, and adjust that value
5720 positionProp = vertical ?
5721 ( parentPosition.top !== '' ? 'top' : 'bottom' ) :
5722 ( parentPosition.left !== '' ? 'left' : 'right' );
5723
5724 // Figure out where the near and far edges of the popup and $floatableContainer are
5725 floatablePos = this.$floatableContainer.offset();
5726 floatablePos[ far ] = floatablePos[ near ] + this.$floatableContainer[ 'outer' + sizeProp ]();
5727 // Measure where the offsetParent is and compute our position based on that and parentPosition
5728 offsetParentPos = this.$element.offsetParent()[ 0 ] === document.documentElement ?
5729 { top: 0, left: 0 } :
5730 this.$element.offsetParent().offset();
5731
5732 if ( positionProp === near ) {
5733 popupPos[ near ] = offsetParentPos[ near ] + parentPosition[ near ];
5734 popupPos[ far ] = popupPos[ near ] + popupSize;
5735 } else {
5736 popupPos[ far ] = offsetParentPos[ near ] +
5737 this.$element.offsetParent()[ 'inner' + sizeProp ]() - parentPosition[ far ];
5738 popupPos[ near ] = popupPos[ far ] - popupSize;
5739 }
5740
5741 if ( this.anchored ) {
5742 // Position the anchor (which is positioned relative to the popup) to point to $floatableContainer
5743 anchorPos = ( floatablePos[ start ] + floatablePos[ end ] ) / 2;
5744 anchorOffset = ( start === far ? -1 : 1 ) * ( anchorPos - popupPos[ start ] );
5745
5746 // If the anchor is less than 2*anchorSize from either edge, move the popup to make more space
5747 // this.$anchor.width()/height() returns 0 because of the CSS trickery we use, so use scrollWidth/Height
5748 anchorSize = this.$anchor[ 0 ][ 'scroll' + sizeProp ];
5749 anchorMargin = parseFloat( this.$anchor.css( 'margin-' + start ) );
5750 if ( anchorOffset + anchorMargin < 2 * anchorSize ) {
5751 // Not enough space for the anchor on the start side; pull the popup startwards
5752 positionAdjustment = ( positionProp === start ? -1 : 1 ) *
5753 ( 2 * anchorSize - ( anchorOffset + anchorMargin ) );
5754 } else if ( anchorOffset + anchorMargin > popupSize - 2 * anchorSize ) {
5755 // Not enough space for the anchor on the end side; pull the popup endwards
5756 positionAdjustment = ( positionProp === end ? -1 : 1 ) *
5757 ( anchorOffset + anchorMargin - ( popupSize - 2 * anchorSize ) );
5758 } else {
5759 positionAdjustment = 0;
5760 }
5761 } else {
5762 positionAdjustment = 0;
5763 }
5764
5765 // Check if the popup will go beyond the edge of this.$container
5766 containerPos = this.$container[ 0 ] === document.documentElement ?
5767 { top: 0, left: 0 } :
5768 this.$container.offset();
5769 containerPos[ far ] = containerPos[ near ] + this.$container[ 'inner' + sizeProp ]();
5770 if ( this.$container[ 0 ] === document.documentElement ) {
5771 viewportSpacing = OO.ui.getViewportSpacing();
5772 containerPos[ near ] += viewportSpacing[ near ];
5773 containerPos[ far ] -= viewportSpacing[ far ];
5774 }
5775 // Take into account how much the popup will move because of the adjustments we're going to make
5776 popupPos[ near ] += ( positionProp === near ? 1 : -1 ) * positionAdjustment;
5777 popupPos[ far ] += ( positionProp === near ? 1 : -1 ) * positionAdjustment;
5778 if ( containerPos[ near ] + this.containerPadding > popupPos[ near ] ) {
5779 // Popup goes beyond the near (left/top) edge, move it to the right/bottom
5780 positionAdjustment += ( positionProp === near ? 1 : -1 ) *
5781 ( containerPos[ near ] + this.containerPadding - popupPos[ near ] );
5782 } else if ( containerPos[ far ] - this.containerPadding < popupPos[ far ] ) {
5783 // Popup goes beyond the far (right/bottom) edge, move it to the left/top
5784 positionAdjustment += ( positionProp === far ? 1 : -1 ) *
5785 ( popupPos[ far ] - ( containerPos[ far ] - this.containerPadding ) );
5786 }
5787
5788 if ( this.anchored ) {
5789 // Adjust anchorOffset for positionAdjustment
5790 anchorOffset += ( positionProp === start ? -1 : 1 ) * positionAdjustment;
5791
5792 // Position the anchor
5793 anchorCss[ start ] = anchorOffset;
5794 this.$anchor.css( anchorCss );
5795 }
5796
5797 // Move the popup if needed
5798 parentPosition[ positionProp ] += positionAdjustment;
5799
5800 return parentPosition;
5801 };
5802
5803 /**
5804 * Set popup alignment
5805 *
5806 * @param {string} [align=center] Alignment of the popup, `center`, `force-left`, `force-right`,
5807 * `backwards` or `forwards`.
5808 */
5809 OO.ui.PopupWidget.prototype.setAlignment = function ( align ) {
5810 // Validate alignment
5811 if ( [ 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align ) > -1 ) {
5812 this.align = align;
5813 } else {
5814 this.align = 'center';
5815 }
5816 this.position();
5817 };
5818
5819 /**
5820 * Get popup alignment
5821 *
5822 * @return {string} Alignment of the popup, `center`, `force-left`, `force-right`,
5823 * `backwards` or `forwards`.
5824 */
5825 OO.ui.PopupWidget.prototype.getAlignment = function () {
5826 return this.align;
5827 };
5828
5829 /**
5830 * Change the positioning of the popup.
5831 *
5832 * @param {string} position 'above', 'below', 'before' or 'after'
5833 */
5834 OO.ui.PopupWidget.prototype.setPosition = function ( position ) {
5835 if ( [ 'above', 'below', 'before', 'after' ].indexOf( position ) === -1 ) {
5836 position = 'below';
5837 }
5838 this.popupPosition = position;
5839 this.position();
5840 };
5841
5842 /**
5843 * Get popup positioning.
5844 *
5845 * @return {string} 'above', 'below', 'before' or 'after'
5846 */
5847 OO.ui.PopupWidget.prototype.getPosition = function () {
5848 return this.popupPosition;
5849 };
5850
5851 /**
5852 * Set popup auto-flipping.
5853 *
5854 * @param {boolean} autoFlip Whether to automatically switch the popup's position between
5855 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5856 * desired direction to display the popup without clipping
5857 */
5858 OO.ui.PopupWidget.prototype.setAutoFlip = function ( autoFlip ) {
5859 autoFlip = !!autoFlip;
5860
5861 if ( this.autoFlip !== autoFlip ) {
5862 this.autoFlip = autoFlip;
5863 }
5864 };
5865
5866 /**
5867 * Set which elements will not close the popup when clicked.
5868 *
5869 * For auto-closing popups, clicks on these elements will not cause the popup to auto-close.
5870 *
5871 * @param {jQuery} $autoCloseIgnore Elements to ignore for auto-closing
5872 */
5873 OO.ui.PopupWidget.prototype.setAutoCloseIgnore = function ( $autoCloseIgnore ) {
5874 this.$autoCloseIgnore = $autoCloseIgnore;
5875 };
5876
5877 /**
5878 * Get an ID of the body element, this can be used as the
5879 * `aria-describedby` attribute for an input field.
5880 *
5881 * @return {string} The ID of the body element
5882 */
5883 OO.ui.PopupWidget.prototype.getBodyId = function () {
5884 var id = this.$body.attr( 'id' );
5885 if ( id === undefined ) {
5886 id = OO.ui.generateElementId();
5887 this.$body.attr( 'id', id );
5888 }
5889 return id;
5890 };
5891
5892 /**
5893 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5894 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5895 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5896 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5897 *
5898 * @abstract
5899 * @class
5900 *
5901 * @constructor
5902 * @param {Object} [config] Configuration options
5903 * @cfg {Object} [popup] Configuration to pass to popup
5904 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5905 */
5906 OO.ui.mixin.PopupElement = function OoUiMixinPopupElement( config ) {
5907 // Configuration initialization
5908 config = config || {};
5909
5910 // Properties
5911 this.popup = new OO.ui.PopupWidget( $.extend(
5912 {
5913 autoClose: true,
5914 $floatableContainer: this.$element
5915 },
5916 config.popup,
5917 {
5918 $autoCloseIgnore: this.$element.add( config.popup && config.popup.$autoCloseIgnore )
5919 }
5920 ) );
5921 };
5922
5923 /* Methods */
5924
5925 /**
5926 * Get popup.
5927 *
5928 * @return {OO.ui.PopupWidget} Popup widget
5929 */
5930 OO.ui.mixin.PopupElement.prototype.getPopup = function () {
5931 return this.popup;
5932 };
5933
5934 /**
5935 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
5936 * which is used to display additional information or options.
5937 *
5938 * @example
5939 * // Example of a popup button.
5940 * var popupButton = new OO.ui.PopupButtonWidget( {
5941 * label: 'Popup button with options',
5942 * icon: 'menu',
5943 * popup: {
5944 * $content: $( '<p>Additional options here.</p>' ),
5945 * padded: true,
5946 * align: 'force-left'
5947 * }
5948 * } );
5949 * // Append the button to the DOM.
5950 * $( 'body' ).append( popupButton.$element );
5951 *
5952 * @class
5953 * @extends OO.ui.ButtonWidget
5954 * @mixins OO.ui.mixin.PopupElement
5955 *
5956 * @constructor
5957 * @param {Object} [config] Configuration options
5958 * @cfg {jQuery} [$overlay] Render the popup into a separate layer. This configuration is useful in cases where
5959 * the expanded popup is larger than its containing `<div>`. The specified overlay layer is usually on top of the
5960 * containing `<div>` and has a larger area. By default, the popup uses relative positioning.
5961 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
5962 */
5963 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
5964 // Configuration initialization
5965 config = config || {};
5966
5967 // Parent constructor
5968 OO.ui.PopupButtonWidget.parent.call( this, config );
5969
5970 // Mixin constructors
5971 OO.ui.mixin.PopupElement.call( this, config );
5972
5973 // Properties
5974 this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
5975
5976 // Events
5977 this.connect( this, { click: 'onAction' } );
5978
5979 // Initialization
5980 this.$element
5981 .addClass( 'oo-ui-popupButtonWidget' );
5982 this.popup.$element
5983 .addClass( 'oo-ui-popupButtonWidget-popup' )
5984 .toggleClass( 'oo-ui-popupButtonWidget-framed-popup', this.isFramed() )
5985 .toggleClass( 'oo-ui-popupButtonWidget-frameless-popup', !this.isFramed() );
5986 this.$overlay.append( this.popup.$element );
5987 };
5988
5989 /* Setup */
5990
5991 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
5992 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.mixin.PopupElement );
5993
5994 /* Methods */
5995
5996 /**
5997 * Handle the button action being triggered.
5998 *
5999 * @private
6000 */
6001 OO.ui.PopupButtonWidget.prototype.onAction = function () {
6002 this.popup.toggle();
6003 };
6004
6005 /**
6006 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
6007 *
6008 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
6009 *
6010 * @private
6011 * @abstract
6012 * @class
6013 * @mixins OO.ui.mixin.GroupElement
6014 *
6015 * @constructor
6016 * @param {Object} [config] Configuration options
6017 */
6018 OO.ui.mixin.GroupWidget = function OoUiMixinGroupWidget( config ) {
6019 // Mixin constructors
6020 OO.ui.mixin.GroupElement.call( this, config );
6021 };
6022
6023 /* Setup */
6024
6025 OO.mixinClass( OO.ui.mixin.GroupWidget, OO.ui.mixin.GroupElement );
6026
6027 /* Methods */
6028
6029 /**
6030 * Set the disabled state of the widget.
6031 *
6032 * This will also update the disabled state of child widgets.
6033 *
6034 * @param {boolean} disabled Disable widget
6035 * @chainable
6036 * @return {OO.ui.Widget} The widget, for chaining
6037 */
6038 OO.ui.mixin.GroupWidget.prototype.setDisabled = function ( disabled ) {
6039 var i, len;
6040
6041 // Parent method
6042 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
6043 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
6044
6045 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
6046 if ( this.items ) {
6047 for ( i = 0, len = this.items.length; i < len; i++ ) {
6048 this.items[ i ].updateDisabled();
6049 }
6050 }
6051
6052 return this;
6053 };
6054
6055 /**
6056 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
6057 *
6058 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
6059 * allows bidirectional communication.
6060 *
6061 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
6062 *
6063 * @private
6064 * @abstract
6065 * @class
6066 *
6067 * @constructor
6068 */
6069 OO.ui.mixin.ItemWidget = function OoUiMixinItemWidget() {
6070 //
6071 };
6072
6073 /* Methods */
6074
6075 /**
6076 * Check if widget is disabled.
6077 *
6078 * Checks parent if present, making disabled state inheritable.
6079 *
6080 * @return {boolean} Widget is disabled
6081 */
6082 OO.ui.mixin.ItemWidget.prototype.isDisabled = function () {
6083 return this.disabled ||
6084 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
6085 };
6086
6087 /**
6088 * Set group element is in.
6089 *
6090 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
6091 * @chainable
6092 * @return {OO.ui.Widget} The widget, for chaining
6093 */
6094 OO.ui.mixin.ItemWidget.prototype.setElementGroup = function ( group ) {
6095 // Parent method
6096 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
6097 OO.ui.Element.prototype.setElementGroup.call( this, group );
6098
6099 // Initialize item disabled states
6100 this.updateDisabled();
6101
6102 return this;
6103 };
6104
6105 /**
6106 * OptionWidgets are special elements that can be selected and configured with data. The
6107 * data is often unique for each option, but it does not have to be. OptionWidgets are used
6108 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
6109 * and examples, please see the [OOUI documentation on MediaWiki][1].
6110 *
6111 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6112 *
6113 * @class
6114 * @extends OO.ui.Widget
6115 * @mixins OO.ui.mixin.ItemWidget
6116 * @mixins OO.ui.mixin.LabelElement
6117 * @mixins OO.ui.mixin.FlaggedElement
6118 * @mixins OO.ui.mixin.AccessKeyedElement
6119 *
6120 * @constructor
6121 * @param {Object} [config] Configuration options
6122 */
6123 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
6124 // Configuration initialization
6125 config = config || {};
6126
6127 // Parent constructor
6128 OO.ui.OptionWidget.parent.call( this, config );
6129
6130 // Mixin constructors
6131 OO.ui.mixin.ItemWidget.call( this );
6132 OO.ui.mixin.LabelElement.call( this, config );
6133 OO.ui.mixin.FlaggedElement.call( this, config );
6134 OO.ui.mixin.AccessKeyedElement.call( this, config );
6135
6136 // Properties
6137 this.selected = false;
6138 this.highlighted = false;
6139 this.pressed = false;
6140
6141 // Initialization
6142 this.$element
6143 .data( 'oo-ui-optionWidget', this )
6144 // Allow programmatic focussing (and by accesskey), but not tabbing
6145 .attr( 'tabindex', '-1' )
6146 .attr( 'role', 'option' )
6147 .attr( 'aria-selected', 'false' )
6148 .addClass( 'oo-ui-optionWidget' )
6149 .append( this.$label );
6150 };
6151
6152 /* Setup */
6153
6154 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
6155 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.ItemWidget );
6156 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.LabelElement );
6157 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.FlaggedElement );
6158 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.AccessKeyedElement );
6159
6160 /* Static Properties */
6161
6162 /**
6163 * Whether this option can be selected. See #setSelected.
6164 *
6165 * @static
6166 * @inheritable
6167 * @property {boolean}
6168 */
6169 OO.ui.OptionWidget.static.selectable = true;
6170
6171 /**
6172 * Whether this option can be highlighted. See #setHighlighted.
6173 *
6174 * @static
6175 * @inheritable
6176 * @property {boolean}
6177 */
6178 OO.ui.OptionWidget.static.highlightable = true;
6179
6180 /**
6181 * Whether this option can be pressed. See #setPressed.
6182 *
6183 * @static
6184 * @inheritable
6185 * @property {boolean}
6186 */
6187 OO.ui.OptionWidget.static.pressable = true;
6188
6189 /**
6190 * Whether this option will be scrolled into view when it is selected.
6191 *
6192 * @static
6193 * @inheritable
6194 * @property {boolean}
6195 */
6196 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
6197
6198 /* Methods */
6199
6200 /**
6201 * Check if the option can be selected.
6202 *
6203 * @return {boolean} Item is selectable
6204 */
6205 OO.ui.OptionWidget.prototype.isSelectable = function () {
6206 return this.constructor.static.selectable && !this.disabled && this.isVisible();
6207 };
6208
6209 /**
6210 * Check if the option can be highlighted. A highlight indicates that the option
6211 * may be selected when a user presses enter or clicks. Disabled items cannot
6212 * be highlighted.
6213 *
6214 * @return {boolean} Item is highlightable
6215 */
6216 OO.ui.OptionWidget.prototype.isHighlightable = function () {
6217 return this.constructor.static.highlightable && !this.disabled && this.isVisible();
6218 };
6219
6220 /**
6221 * Check if the option can be pressed. The pressed state occurs when a user mouses
6222 * down on an item, but has not yet let go of the mouse.
6223 *
6224 * @return {boolean} Item is pressable
6225 */
6226 OO.ui.OptionWidget.prototype.isPressable = function () {
6227 return this.constructor.static.pressable && !this.disabled && this.isVisible();
6228 };
6229
6230 /**
6231 * Check if the option is selected.
6232 *
6233 * @return {boolean} Item is selected
6234 */
6235 OO.ui.OptionWidget.prototype.isSelected = function () {
6236 return this.selected;
6237 };
6238
6239 /**
6240 * Check if the option is highlighted. A highlight indicates that the
6241 * item may be selected when a user presses enter or clicks.
6242 *
6243 * @return {boolean} Item is highlighted
6244 */
6245 OO.ui.OptionWidget.prototype.isHighlighted = function () {
6246 return this.highlighted;
6247 };
6248
6249 /**
6250 * Check if the option is pressed. The pressed state occurs when a user mouses
6251 * down on an item, but has not yet let go of the mouse. The item may appear
6252 * selected, but it will not be selected until the user releases the mouse.
6253 *
6254 * @return {boolean} Item is pressed
6255 */
6256 OO.ui.OptionWidget.prototype.isPressed = function () {
6257 return this.pressed;
6258 };
6259
6260 /**
6261 * Set the option’s selected state. In general, all modifications to the selection
6262 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
6263 * method instead of this method.
6264 *
6265 * @param {boolean} [state=false] Select option
6266 * @chainable
6267 * @return {OO.ui.Widget} The widget, for chaining
6268 */
6269 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
6270 if ( this.constructor.static.selectable ) {
6271 this.selected = !!state;
6272 this.$element
6273 .toggleClass( 'oo-ui-optionWidget-selected', state )
6274 .attr( 'aria-selected', state.toString() );
6275 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
6276 this.scrollElementIntoView();
6277 }
6278 this.updateThemeClasses();
6279 }
6280 return this;
6281 };
6282
6283 /**
6284 * Set the option’s highlighted state. In general, all programmatic
6285 * modifications to the highlight should be handled by the
6286 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
6287 * method instead of this method.
6288 *
6289 * @param {boolean} [state=false] Highlight option
6290 * @chainable
6291 * @return {OO.ui.Widget} The widget, for chaining
6292 */
6293 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
6294 if ( this.constructor.static.highlightable ) {
6295 this.highlighted = !!state;
6296 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
6297 this.updateThemeClasses();
6298 }
6299 return this;
6300 };
6301
6302 /**
6303 * Set the option’s pressed state. In general, all
6304 * programmatic modifications to the pressed state should be handled by the
6305 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
6306 * method instead of this method.
6307 *
6308 * @param {boolean} [state=false] Press option
6309 * @chainable
6310 * @return {OO.ui.Widget} The widget, for chaining
6311 */
6312 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
6313 if ( this.constructor.static.pressable ) {
6314 this.pressed = !!state;
6315 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
6316 this.updateThemeClasses();
6317 }
6318 return this;
6319 };
6320
6321 /**
6322 * Get text to match search strings against.
6323 *
6324 * The default implementation returns the label text, but subclasses
6325 * can override this to provide more complex behavior.
6326 *
6327 * @return {string|boolean} String to match search string against
6328 */
6329 OO.ui.OptionWidget.prototype.getMatchText = function () {
6330 var label = this.getLabel();
6331 return typeof label === 'string' ? label : this.$label.text();
6332 };
6333
6334 /**
6335 * A SelectWidget is of a generic selection of options. The OOUI library contains several types of
6336 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
6337 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
6338 * menu selects}.
6339 *
6340 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
6341 * information, please see the [OOUI documentation on MediaWiki][1].
6342 *
6343 * @example
6344 * // Example of a select widget with three options
6345 * var select = new OO.ui.SelectWidget( {
6346 * items: [
6347 * new OO.ui.OptionWidget( {
6348 * data: 'a',
6349 * label: 'Option One',
6350 * } ),
6351 * new OO.ui.OptionWidget( {
6352 * data: 'b',
6353 * label: 'Option Two',
6354 * } ),
6355 * new OO.ui.OptionWidget( {
6356 * data: 'c',
6357 * label: 'Option Three',
6358 * } )
6359 * ]
6360 * } );
6361 * $( 'body' ).append( select.$element );
6362 *
6363 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6364 *
6365 * @abstract
6366 * @class
6367 * @extends OO.ui.Widget
6368 * @mixins OO.ui.mixin.GroupWidget
6369 *
6370 * @constructor
6371 * @param {Object} [config] Configuration options
6372 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
6373 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
6374 * the [OOUI documentation on MediaWiki] [2] for examples.
6375 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6376 */
6377 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
6378 // Configuration initialization
6379 config = config || {};
6380
6381 // Parent constructor
6382 OO.ui.SelectWidget.parent.call( this, config );
6383
6384 // Mixin constructors
6385 OO.ui.mixin.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
6386
6387 // Properties
6388 this.pressed = false;
6389 this.selecting = null;
6390 this.onDocumentMouseUpHandler = this.onDocumentMouseUp.bind( this );
6391 this.onDocumentMouseMoveHandler = this.onDocumentMouseMove.bind( this );
6392 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
6393 this.onDocumentKeyPressHandler = this.onDocumentKeyPress.bind( this );
6394 this.keyPressBuffer = '';
6395 this.keyPressBufferTimer = null;
6396 this.blockMouseOverEvents = 0;
6397
6398 // Events
6399 this.connect( this, {
6400 toggle: 'onToggle'
6401 } );
6402 this.$element.on( {
6403 focusin: this.onFocus.bind( this ),
6404 mousedown: this.onMouseDown.bind( this ),
6405 mouseover: this.onMouseOver.bind( this ),
6406 mouseleave: this.onMouseLeave.bind( this )
6407 } );
6408
6409 // Initialization
6410 this.$element
6411 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
6412 .attr( 'role', 'listbox' );
6413 this.setFocusOwner( this.$element );
6414 if ( Array.isArray( config.items ) ) {
6415 this.addItems( config.items );
6416 }
6417 };
6418
6419 /* Setup */
6420
6421 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
6422 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupWidget );
6423
6424 /* Events */
6425
6426 /**
6427 * @event highlight
6428 *
6429 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
6430 *
6431 * @param {OO.ui.OptionWidget|null} item Highlighted item
6432 */
6433
6434 /**
6435 * @event press
6436 *
6437 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
6438 * pressed state of an option.
6439 *
6440 * @param {OO.ui.OptionWidget|null} item Pressed item
6441 */
6442
6443 /**
6444 * @event select
6445 *
6446 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
6447 *
6448 * @param {OO.ui.OptionWidget|null} item Selected item
6449 */
6450
6451 /**
6452 * @event choose
6453 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
6454 * @param {OO.ui.OptionWidget} item Chosen item
6455 */
6456
6457 /**
6458 * @event add
6459 *
6460 * An `add` event is emitted when options are added to the select with the #addItems method.
6461 *
6462 * @param {OO.ui.OptionWidget[]} items Added items
6463 * @param {number} index Index of insertion point
6464 */
6465
6466 /**
6467 * @event remove
6468 *
6469 * A `remove` event is emitted when options are removed from the select with the #clearItems
6470 * or #removeItems methods.
6471 *
6472 * @param {OO.ui.OptionWidget[]} items Removed items
6473 */
6474
6475 /* Methods */
6476
6477 /**
6478 * Handle focus events
6479 *
6480 * @private
6481 * @param {jQuery.Event} event
6482 */
6483 OO.ui.SelectWidget.prototype.onFocus = function ( event ) {
6484 var item;
6485 if ( event.target === this.$element[ 0 ] ) {
6486 // This widget was focussed, e.g. by the user tabbing to it.
6487 // The styles for focus state depend on one of the items being selected.
6488 if ( !this.findSelectedItem() ) {
6489 item = this.findFirstSelectableItem();
6490 }
6491 } else {
6492 if ( event.target.tabIndex === -1 ) {
6493 // One of the options got focussed (and the event bubbled up here).
6494 // They can't be tabbed to, but they can be activated using accesskeys.
6495 // OptionWidgets and focusable UI elements inside them have tabindex="-1" set.
6496 item = this.findTargetItem( event );
6497 } else {
6498 // There is something actually user-focusable in one of the labels of the options, and the
6499 // user focussed it (e.g. by tabbing to it). Do nothing (especially, don't change the focus).
6500 return;
6501 }
6502 }
6503
6504 if ( item ) {
6505 if ( item.constructor.static.highlightable ) {
6506 this.highlightItem( item );
6507 } else {
6508 this.selectItem( item );
6509 }
6510 }
6511
6512 if ( event.target !== this.$element[ 0 ] ) {
6513 this.$focusOwner.focus();
6514 }
6515 };
6516
6517 /**
6518 * Handle mouse down events.
6519 *
6520 * @private
6521 * @param {jQuery.Event} e Mouse down event
6522 * @return {undefined/boolean} False to prevent default if event is handled
6523 */
6524 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
6525 var item;
6526
6527 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
6528 this.togglePressed( true );
6529 item = this.findTargetItem( e );
6530 if ( item && item.isSelectable() ) {
6531 this.pressItem( item );
6532 this.selecting = item;
6533 this.getElementDocument().addEventListener( 'mouseup', this.onDocumentMouseUpHandler, true );
6534 this.getElementDocument().addEventListener( 'mousemove', this.onDocumentMouseMoveHandler, true );
6535 }
6536 }
6537 return false;
6538 };
6539
6540 /**
6541 * Handle document mouse up events.
6542 *
6543 * @private
6544 * @param {MouseEvent} e Mouse up event
6545 * @return {undefined/boolean} False to prevent default if event is handled
6546 */
6547 OO.ui.SelectWidget.prototype.onDocumentMouseUp = function ( e ) {
6548 var item;
6549
6550 this.togglePressed( false );
6551 if ( !this.selecting ) {
6552 item = this.findTargetItem( e );
6553 if ( item && item.isSelectable() ) {
6554 this.selecting = item;
6555 }
6556 }
6557 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT && this.selecting ) {
6558 this.pressItem( null );
6559 this.chooseItem( this.selecting );
6560 this.selecting = null;
6561 }
6562
6563 this.getElementDocument().removeEventListener( 'mouseup', this.onDocumentMouseUpHandler, true );
6564 this.getElementDocument().removeEventListener( 'mousemove', this.onDocumentMouseMoveHandler, true );
6565
6566 return false;
6567 };
6568
6569 // Deprecated alias since 0.28.3
6570 OO.ui.SelectWidget.prototype.onMouseUp = function () {
6571 OO.ui.warnDeprecation( 'onMouseUp is deprecated, use onDocumentMouseUp instead' );
6572 this.onDocumentMouseUp.apply( this, arguments );
6573 };
6574
6575 /**
6576 * Handle document mouse move events.
6577 *
6578 * @private
6579 * @param {MouseEvent} e Mouse move event
6580 */
6581 OO.ui.SelectWidget.prototype.onDocumentMouseMove = function ( e ) {
6582 var item;
6583
6584 if ( !this.isDisabled() && this.pressed ) {
6585 item = this.findTargetItem( e );
6586 if ( item && item !== this.selecting && item.isSelectable() ) {
6587 this.pressItem( item );
6588 this.selecting = item;
6589 }
6590 }
6591 };
6592
6593 // Deprecated alias since 0.28.3
6594 OO.ui.SelectWidget.prototype.onMouseMove = function () {
6595 OO.ui.warnDeprecation( 'onMouseMove is deprecated, use onDocumentMouseMove instead' );
6596 this.onDocumentMouseMove.apply( this, arguments );
6597 };
6598
6599 /**
6600 * Handle mouse over events.
6601 *
6602 * @private
6603 * @param {jQuery.Event} e Mouse over event
6604 * @return {undefined/boolean} False to prevent default if event is handled
6605 */
6606 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
6607 var item;
6608 if ( this.blockMouseOverEvents ) {
6609 return;
6610 }
6611 if ( !this.isDisabled() ) {
6612 item = this.findTargetItem( e );
6613 this.highlightItem( item && item.isHighlightable() ? item : null );
6614 }
6615 return false;
6616 };
6617
6618 /**
6619 * Handle mouse leave events.
6620 *
6621 * @private
6622 * @param {jQuery.Event} e Mouse over event
6623 * @return {undefined/boolean} False to prevent default if event is handled
6624 */
6625 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
6626 if ( !this.isDisabled() ) {
6627 this.highlightItem( null );
6628 }
6629 return false;
6630 };
6631
6632 /**
6633 * Handle document key down events.
6634 *
6635 * @protected
6636 * @param {KeyboardEvent} e Key down event
6637 */
6638 OO.ui.SelectWidget.prototype.onDocumentKeyDown = function ( e ) {
6639 var nextItem,
6640 handled = false,
6641 currentItem = this.findHighlightedItem() || this.findSelectedItem();
6642
6643 if ( !this.isDisabled() && this.isVisible() ) {
6644 switch ( e.keyCode ) {
6645 case OO.ui.Keys.ENTER:
6646 if ( currentItem && currentItem.constructor.static.highlightable ) {
6647 // Was only highlighted, now let's select it. No-op if already selected.
6648 this.chooseItem( currentItem );
6649 handled = true;
6650 }
6651 break;
6652 case OO.ui.Keys.UP:
6653 case OO.ui.Keys.LEFT:
6654 this.clearKeyPressBuffer();
6655 nextItem = this.findRelativeSelectableItem( currentItem, -1 );
6656 handled = true;
6657 break;
6658 case OO.ui.Keys.DOWN:
6659 case OO.ui.Keys.RIGHT:
6660 this.clearKeyPressBuffer();
6661 nextItem = this.findRelativeSelectableItem( currentItem, 1 );
6662 handled = true;
6663 break;
6664 case OO.ui.Keys.ESCAPE:
6665 case OO.ui.Keys.TAB:
6666 if ( currentItem && currentItem.constructor.static.highlightable ) {
6667 currentItem.setHighlighted( false );
6668 }
6669 this.unbindDocumentKeyDownListener();
6670 this.unbindDocumentKeyPressListener();
6671 // Don't prevent tabbing away / defocusing
6672 handled = false;
6673 break;
6674 }
6675
6676 if ( nextItem ) {
6677 if ( nextItem.constructor.static.highlightable ) {
6678 this.highlightItem( nextItem );
6679 } else {
6680 this.chooseItem( nextItem );
6681 }
6682 this.scrollItemIntoView( nextItem );
6683 }
6684
6685 if ( handled ) {
6686 e.preventDefault();
6687 e.stopPropagation();
6688 }
6689 }
6690 };
6691
6692 // Deprecated alias since 0.28.3
6693 OO.ui.SelectWidget.prototype.onKeyDown = function () {
6694 OO.ui.warnDeprecation( 'onKeyDown is deprecated, use onDocumentKeyDown instead' );
6695 this.onDocumentKeyDown.apply( this, arguments );
6696 };
6697
6698 /**
6699 * Bind document key down listener.
6700 *
6701 * @protected
6702 */
6703 OO.ui.SelectWidget.prototype.bindDocumentKeyDownListener = function () {
6704 this.getElementDocument().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
6705 };
6706
6707 // Deprecated alias since 0.28.3
6708 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
6709 OO.ui.warnDeprecation( 'bindKeyDownListener is deprecated, use bindDocumentKeyDownListener instead' );
6710 this.bindDocumentKeyDownListener.apply( this, arguments );
6711 };
6712
6713 /**
6714 * Unbind document key down listener.
6715 *
6716 * @protected
6717 */
6718 OO.ui.SelectWidget.prototype.unbindDocumentKeyDownListener = function () {
6719 this.getElementDocument().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
6720 };
6721
6722 // Deprecated alias since 0.28.3
6723 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
6724 OO.ui.warnDeprecation( 'unbindKeyDownListener is deprecated, use unbindDocumentKeyDownListener instead' );
6725 this.unbindDocumentKeyDownListener.apply( this, arguments );
6726 };
6727
6728 /**
6729 * Scroll item into view, preventing spurious mouse highlight actions from happening.
6730 *
6731 * @param {OO.ui.OptionWidget} item Item to scroll into view
6732 */
6733 OO.ui.SelectWidget.prototype.scrollItemIntoView = function ( item ) {
6734 var widget = this;
6735 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling
6736 // and around 100-150 ms after it is finished.
6737 this.blockMouseOverEvents++;
6738 item.scrollElementIntoView().done( function () {
6739 setTimeout( function () {
6740 widget.blockMouseOverEvents--;
6741 }, 200 );
6742 } );
6743 };
6744
6745 /**
6746 * Clear the key-press buffer
6747 *
6748 * @protected
6749 */
6750 OO.ui.SelectWidget.prototype.clearKeyPressBuffer = function () {
6751 if ( this.keyPressBufferTimer ) {
6752 clearTimeout( this.keyPressBufferTimer );
6753 this.keyPressBufferTimer = null;
6754 }
6755 this.keyPressBuffer = '';
6756 };
6757
6758 /**
6759 * Handle key press events.
6760 *
6761 * @protected
6762 * @param {KeyboardEvent} e Key press event
6763 * @return {undefined/boolean} False to prevent default if event is handled
6764 */
6765 OO.ui.SelectWidget.prototype.onDocumentKeyPress = function ( e ) {
6766 var c, filter, item;
6767
6768 if ( !e.charCode ) {
6769 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.keyPressBuffer !== '' ) {
6770 this.keyPressBuffer = this.keyPressBuffer.substr( 0, this.keyPressBuffer.length - 1 );
6771 return false;
6772 }
6773 return;
6774 }
6775 if ( String.fromCodePoint ) {
6776 c = String.fromCodePoint( e.charCode );
6777 } else {
6778 c = String.fromCharCode( e.charCode );
6779 }
6780
6781 if ( this.keyPressBufferTimer ) {
6782 clearTimeout( this.keyPressBufferTimer );
6783 }
6784 this.keyPressBufferTimer = setTimeout( this.clearKeyPressBuffer.bind( this ), 1500 );
6785
6786 item = this.findHighlightedItem() || this.findSelectedItem();
6787
6788 if ( this.keyPressBuffer === c ) {
6789 // Common (if weird) special case: typing "xxxx" will cycle through all
6790 // the items beginning with "x".
6791 if ( item ) {
6792 item = this.findRelativeSelectableItem( item, 1 );
6793 }
6794 } else {
6795 this.keyPressBuffer += c;
6796 }
6797
6798 filter = this.getItemMatcher( this.keyPressBuffer, false );
6799 if ( !item || !filter( item ) ) {
6800 item = this.findRelativeSelectableItem( item, 1, filter );
6801 }
6802 if ( item ) {
6803 if ( this.isVisible() && item.constructor.static.highlightable ) {
6804 this.highlightItem( item );
6805 } else {
6806 this.chooseItem( item );
6807 }
6808 this.scrollItemIntoView( item );
6809 }
6810
6811 e.preventDefault();
6812 e.stopPropagation();
6813 };
6814
6815 // Deprecated alias since 0.28.3
6816 OO.ui.SelectWidget.prototype.onKeyPress = function () {
6817 OO.ui.warnDeprecation( 'onKeyPress is deprecated, use onDocumentKeyPress instead' );
6818 this.onDocumentKeyPress.apply( this, arguments );
6819 };
6820
6821 /**
6822 * Get a matcher for the specific string
6823 *
6824 * @protected
6825 * @param {string} s String to match against items
6826 * @param {boolean} [exact=false] Only accept exact matches
6827 * @return {Function} function ( OO.ui.OptionWidget ) => boolean
6828 */
6829 OO.ui.SelectWidget.prototype.getItemMatcher = function ( s, exact ) {
6830 var re;
6831
6832 if ( s.normalize ) {
6833 s = s.normalize();
6834 }
6835 s = exact ? s.trim() : s.replace( /^\s+/, '' );
6836 re = '^\\s*' + s.replace( /([\\{}()|.?*+\-^$[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
6837 if ( exact ) {
6838 re += '\\s*$';
6839 }
6840 re = new RegExp( re, 'i' );
6841 return function ( item ) {
6842 var matchText = item.getMatchText();
6843 if ( matchText.normalize ) {
6844 matchText = matchText.normalize();
6845 }
6846 return re.test( matchText );
6847 };
6848 };
6849
6850 /**
6851 * Bind document key press listener.
6852 *
6853 * @protected
6854 */
6855 OO.ui.SelectWidget.prototype.bindDocumentKeyPressListener = function () {
6856 this.getElementDocument().addEventListener( 'keypress', this.onDocumentKeyPressHandler, true );
6857 };
6858
6859 // Deprecated alias since 0.28.3
6860 OO.ui.SelectWidget.prototype.bindKeyPressListener = function () {
6861 OO.ui.warnDeprecation( 'bindKeyPressListener is deprecated, use bindDocumentKeyPressListener instead' );
6862 this.bindDocumentKeyPressListener.apply( this, arguments );
6863 };
6864
6865 /**
6866 * Unbind document key down listener.
6867 *
6868 * If you override this, be sure to call this.clearKeyPressBuffer() from your
6869 * implementation.
6870 *
6871 * @protected
6872 */
6873 OO.ui.SelectWidget.prototype.unbindDocumentKeyPressListener = function () {
6874 this.getElementDocument().removeEventListener( 'keypress', this.onDocumentKeyPressHandler, true );
6875 this.clearKeyPressBuffer();
6876 };
6877
6878 // Deprecated alias since 0.28.3
6879 OO.ui.SelectWidget.prototype.unbindKeyPressListener = function () {
6880 OO.ui.warnDeprecation( 'unbindKeyPressListener is deprecated, use unbindDocumentKeyPressListener instead' );
6881 this.unbindDocumentKeyPressListener.apply( this, arguments );
6882 };
6883
6884 /**
6885 * Visibility change handler
6886 *
6887 * @protected
6888 * @param {boolean} visible
6889 */
6890 OO.ui.SelectWidget.prototype.onToggle = function ( visible ) {
6891 if ( !visible ) {
6892 this.clearKeyPressBuffer();
6893 }
6894 };
6895
6896 /**
6897 * Get the closest item to a jQuery.Event.
6898 *
6899 * @private
6900 * @param {jQuery.Event} e
6901 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
6902 */
6903 OO.ui.SelectWidget.prototype.findTargetItem = function ( e ) {
6904 var $option = $( e.target ).closest( '.oo-ui-optionWidget' );
6905 if ( !$option.closest( '.oo-ui-selectWidget' ).is( this.$element ) ) {
6906 return null;
6907 }
6908 return $option.data( 'oo-ui-optionWidget' ) || null;
6909 };
6910
6911 /**
6912 * Find selected item.
6913 *
6914 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
6915 */
6916 OO.ui.SelectWidget.prototype.findSelectedItem = function () {
6917 var i, len;
6918
6919 for ( i = 0, len = this.items.length; i < len; i++ ) {
6920 if ( this.items[ i ].isSelected() ) {
6921 return this.items[ i ];
6922 }
6923 }
6924 return null;
6925 };
6926
6927 /**
6928 * Find highlighted item.
6929 *
6930 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
6931 */
6932 OO.ui.SelectWidget.prototype.findHighlightedItem = function () {
6933 var i, len;
6934
6935 for ( i = 0, len = this.items.length; i < len; i++ ) {
6936 if ( this.items[ i ].isHighlighted() ) {
6937 return this.items[ i ];
6938 }
6939 }
6940 return null;
6941 };
6942
6943 /**
6944 * Toggle pressed state.
6945 *
6946 * Press is a state that occurs when a user mouses down on an item, but
6947 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
6948 * until the user releases the mouse.
6949 *
6950 * @param {boolean} pressed An option is being pressed
6951 */
6952 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
6953 if ( pressed === undefined ) {
6954 pressed = !this.pressed;
6955 }
6956 if ( pressed !== this.pressed ) {
6957 this.$element
6958 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
6959 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
6960 this.pressed = pressed;
6961 }
6962 };
6963
6964 /**
6965 * Highlight an option. If the `item` param is omitted, no options will be highlighted
6966 * and any existing highlight will be removed. The highlight is mutually exclusive.
6967 *
6968 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
6969 * @fires highlight
6970 * @chainable
6971 * @return {OO.ui.Widget} The widget, for chaining
6972 */
6973 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
6974 var i, len, highlighted,
6975 changed = false;
6976
6977 for ( i = 0, len = this.items.length; i < len; i++ ) {
6978 highlighted = this.items[ i ] === item;
6979 if ( this.items[ i ].isHighlighted() !== highlighted ) {
6980 this.items[ i ].setHighlighted( highlighted );
6981 changed = true;
6982 }
6983 }
6984 if ( changed ) {
6985 if ( item ) {
6986 this.$focusOwner.attr( 'aria-activedescendant', item.getElementId() );
6987 } else {
6988 this.$focusOwner.removeAttr( 'aria-activedescendant' );
6989 }
6990 this.emit( 'highlight', item );
6991 }
6992
6993 return this;
6994 };
6995
6996 /**
6997 * Fetch an item by its label.
6998 *
6999 * @param {string} label Label of the item to select.
7000 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
7001 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
7002 */
7003 OO.ui.SelectWidget.prototype.getItemFromLabel = function ( label, prefix ) {
7004 var i, item, found,
7005 len = this.items.length,
7006 filter = this.getItemMatcher( label, true );
7007
7008 for ( i = 0; i < len; i++ ) {
7009 item = this.items[ i ];
7010 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
7011 return item;
7012 }
7013 }
7014
7015 if ( prefix ) {
7016 found = null;
7017 filter = this.getItemMatcher( label, false );
7018 for ( i = 0; i < len; i++ ) {
7019 item = this.items[ i ];
7020 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
7021 if ( found ) {
7022 return null;
7023 }
7024 found = item;
7025 }
7026 }
7027 if ( found ) {
7028 return found;
7029 }
7030 }
7031
7032 return null;
7033 };
7034
7035 /**
7036 * Programmatically select an option by its label. If the item does not exist,
7037 * all options will be deselected.
7038 *
7039 * @param {string} [label] Label of the item to select.
7040 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
7041 * @fires select
7042 * @chainable
7043 * @return {OO.ui.Widget} The widget, for chaining
7044 */
7045 OO.ui.SelectWidget.prototype.selectItemByLabel = function ( label, prefix ) {
7046 var itemFromLabel = this.getItemFromLabel( label, !!prefix );
7047 if ( label === undefined || !itemFromLabel ) {
7048 return this.selectItem();
7049 }
7050 return this.selectItem( itemFromLabel );
7051 };
7052
7053 /**
7054 * Programmatically select an option by its data. If the `data` parameter is omitted,
7055 * or if the item does not exist, all options will be deselected.
7056 *
7057 * @param {Object|string} [data] Value of the item to select, omit to deselect all
7058 * @fires select
7059 * @chainable
7060 * @return {OO.ui.Widget} The widget, for chaining
7061 */
7062 OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) {
7063 var itemFromData = this.findItemFromData( data );
7064 if ( data === undefined || !itemFromData ) {
7065 return this.selectItem();
7066 }
7067 return this.selectItem( itemFromData );
7068 };
7069
7070 /**
7071 * Programmatically select an option by its reference. If the `item` parameter is omitted,
7072 * all options will be deselected.
7073 *
7074 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
7075 * @fires select
7076 * @chainable
7077 * @return {OO.ui.Widget} The widget, for chaining
7078 */
7079 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
7080 var i, len, selected,
7081 changed = false;
7082
7083 for ( i = 0, len = this.items.length; i < len; i++ ) {
7084 selected = this.items[ i ] === item;
7085 if ( this.items[ i ].isSelected() !== selected ) {
7086 this.items[ i ].setSelected( selected );
7087 changed = true;
7088 }
7089 }
7090 if ( changed ) {
7091 if ( item && !item.constructor.static.highlightable ) {
7092 if ( item ) {
7093 this.$focusOwner.attr( 'aria-activedescendant', item.getElementId() );
7094 } else {
7095 this.$focusOwner.removeAttr( 'aria-activedescendant' );
7096 }
7097 }
7098 this.emit( 'select', item );
7099 }
7100
7101 return this;
7102 };
7103
7104 /**
7105 * Press an item.
7106 *
7107 * Press is a state that occurs when a user mouses down on an item, but has not
7108 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
7109 * releases the mouse.
7110 *
7111 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
7112 * @fires press
7113 * @chainable
7114 * @return {OO.ui.Widget} The widget, for chaining
7115 */
7116 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
7117 var i, len, pressed,
7118 changed = false;
7119
7120 for ( i = 0, len = this.items.length; i < len; i++ ) {
7121 pressed = this.items[ i ] === item;
7122 if ( this.items[ i ].isPressed() !== pressed ) {
7123 this.items[ i ].setPressed( pressed );
7124 changed = true;
7125 }
7126 }
7127 if ( changed ) {
7128 this.emit( 'press', item );
7129 }
7130
7131 return this;
7132 };
7133
7134 /**
7135 * Choose an item.
7136 *
7137 * Note that ‘choose’ should never be modified programmatically. A user can choose
7138 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
7139 * use the #selectItem method.
7140 *
7141 * This method is identical to #selectItem, but may vary in subclasses that take additional action
7142 * when users choose an item with the keyboard or mouse.
7143 *
7144 * @param {OO.ui.OptionWidget} item Item to choose
7145 * @fires choose
7146 * @chainable
7147 * @return {OO.ui.Widget} The widget, for chaining
7148 */
7149 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
7150 if ( item ) {
7151 this.selectItem( item );
7152 this.emit( 'choose', item );
7153 }
7154
7155 return this;
7156 };
7157
7158 /**
7159 * Find an option by its position relative to the specified item (or to the start of the option array,
7160 * if item is `null`). The direction in which to search through the option array is specified with a
7161 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
7162 * `null` if there are no options in the array.
7163 *
7164 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
7165 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
7166 * @param {Function} [filter] Only consider items for which this function returns
7167 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
7168 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
7169 */
7170 OO.ui.SelectWidget.prototype.findRelativeSelectableItem = function ( item, direction, filter ) {
7171 var currentIndex, nextIndex, i,
7172 increase = direction > 0 ? 1 : -1,
7173 len = this.items.length;
7174
7175 if ( item instanceof OO.ui.OptionWidget ) {
7176 currentIndex = this.items.indexOf( item );
7177 nextIndex = ( currentIndex + increase + len ) % len;
7178 } else {
7179 // If no item is selected and moving forward, start at the beginning.
7180 // If moving backward, start at the end.
7181 nextIndex = direction > 0 ? 0 : len - 1;
7182 }
7183
7184 for ( i = 0; i < len; i++ ) {
7185 item = this.items[ nextIndex ];
7186 if (
7187 item instanceof OO.ui.OptionWidget && item.isSelectable() &&
7188 ( !filter || filter( item ) )
7189 ) {
7190 return item;
7191 }
7192 nextIndex = ( nextIndex + increase + len ) % len;
7193 }
7194 return null;
7195 };
7196
7197 /**
7198 * Find the next selectable item or `null` if there are no selectable items.
7199 * Disabled options and menu-section markers and breaks are not selectable.
7200 *
7201 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
7202 */
7203 OO.ui.SelectWidget.prototype.findFirstSelectableItem = function () {
7204 return this.findRelativeSelectableItem( null, 1 );
7205 };
7206
7207 /**
7208 * Add an array of options to the select. Optionally, an index number can be used to
7209 * specify an insertion point.
7210 *
7211 * @param {OO.ui.OptionWidget[]} items Items to add
7212 * @param {number} [index] Index to insert items after
7213 * @fires add
7214 * @chainable
7215 * @return {OO.ui.Widget} The widget, for chaining
7216 */
7217 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
7218 // Mixin method
7219 OO.ui.mixin.GroupWidget.prototype.addItems.call( this, items, index );
7220
7221 // Always provide an index, even if it was omitted
7222 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
7223
7224 return this;
7225 };
7226
7227 /**
7228 * Remove the specified array of options from the select. Options will be detached
7229 * from the DOM, not removed, so they can be reused later. To remove all options from
7230 * the select, you may wish to use the #clearItems method instead.
7231 *
7232 * @param {OO.ui.OptionWidget[]} items Items to remove
7233 * @fires remove
7234 * @chainable
7235 * @return {OO.ui.Widget} The widget, for chaining
7236 */
7237 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
7238 var i, len, item;
7239
7240 // Deselect items being removed
7241 for ( i = 0, len = items.length; i < len; i++ ) {
7242 item = items[ i ];
7243 if ( item.isSelected() ) {
7244 this.selectItem( null );
7245 }
7246 }
7247
7248 // Mixin method
7249 OO.ui.mixin.GroupWidget.prototype.removeItems.call( this, items );
7250
7251 this.emit( 'remove', items );
7252
7253 return this;
7254 };
7255
7256 /**
7257 * Clear all options from the select. Options will be detached from the DOM, not removed,
7258 * so that they can be reused later. To remove a subset of options from the select, use
7259 * the #removeItems method.
7260 *
7261 * @fires remove
7262 * @chainable
7263 * @return {OO.ui.Widget} The widget, for chaining
7264 */
7265 OO.ui.SelectWidget.prototype.clearItems = function () {
7266 var items = this.items.slice();
7267
7268 // Mixin method
7269 OO.ui.mixin.GroupWidget.prototype.clearItems.call( this );
7270
7271 // Clear selection
7272 this.selectItem( null );
7273
7274 this.emit( 'remove', items );
7275
7276 return this;
7277 };
7278
7279 /**
7280 * Set the DOM element which has focus while the user is interacting with this SelectWidget.
7281 *
7282 * Currently this is just used to set `aria-activedescendant` on it.
7283 *
7284 * @protected
7285 * @param {jQuery} $focusOwner
7286 */
7287 OO.ui.SelectWidget.prototype.setFocusOwner = function ( $focusOwner ) {
7288 this.$focusOwner = $focusOwner;
7289 };
7290
7291 /**
7292 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
7293 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
7294 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
7295 * options. For more information about options and selects, please see the
7296 * [OOUI documentation on MediaWiki][1].
7297 *
7298 * @example
7299 * // Decorated options in a select widget
7300 * var select = new OO.ui.SelectWidget( {
7301 * items: [
7302 * new OO.ui.DecoratedOptionWidget( {
7303 * data: 'a',
7304 * label: 'Option with icon',
7305 * icon: 'help'
7306 * } ),
7307 * new OO.ui.DecoratedOptionWidget( {
7308 * data: 'b',
7309 * label: 'Option with indicator',
7310 * indicator: 'next'
7311 * } )
7312 * ]
7313 * } );
7314 * $( 'body' ).append( select.$element );
7315 *
7316 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7317 *
7318 * @class
7319 * @extends OO.ui.OptionWidget
7320 * @mixins OO.ui.mixin.IconElement
7321 * @mixins OO.ui.mixin.IndicatorElement
7322 *
7323 * @constructor
7324 * @param {Object} [config] Configuration options
7325 */
7326 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
7327 // Parent constructor
7328 OO.ui.DecoratedOptionWidget.parent.call( this, config );
7329
7330 // Mixin constructors
7331 OO.ui.mixin.IconElement.call( this, config );
7332 OO.ui.mixin.IndicatorElement.call( this, config );
7333
7334 // Initialization
7335 this.$element
7336 .addClass( 'oo-ui-decoratedOptionWidget' )
7337 .prepend( this.$icon )
7338 .append( this.$indicator );
7339 };
7340
7341 /* Setup */
7342
7343 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
7344 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IconElement );
7345 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IndicatorElement );
7346
7347 /**
7348 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
7349 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
7350 * the [OOUI documentation on MediaWiki] [1] for more information.
7351 *
7352 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
7353 *
7354 * @class
7355 * @extends OO.ui.DecoratedOptionWidget
7356 *
7357 * @constructor
7358 * @param {Object} [config] Configuration options
7359 */
7360 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
7361 // Parent constructor
7362 OO.ui.MenuOptionWidget.parent.call( this, config );
7363
7364 // Properties
7365 this.checkIcon = new OO.ui.IconWidget( {
7366 icon: 'check',
7367 classes: [ 'oo-ui-menuOptionWidget-checkIcon' ]
7368 } );
7369
7370 // Initialization
7371 this.$element
7372 .prepend( this.checkIcon.$element )
7373 .addClass( 'oo-ui-menuOptionWidget' );
7374 };
7375
7376 /* Setup */
7377
7378 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
7379
7380 /* Static Properties */
7381
7382 /**
7383 * @static
7384 * @inheritdoc
7385 */
7386 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
7387
7388 /**
7389 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
7390 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
7391 *
7392 * @example
7393 * var myDropdown = new OO.ui.DropdownWidget( {
7394 * menu: {
7395 * items: [
7396 * new OO.ui.MenuSectionOptionWidget( {
7397 * label: 'Dogs'
7398 * } ),
7399 * new OO.ui.MenuOptionWidget( {
7400 * data: 'corgi',
7401 * label: 'Welsh Corgi'
7402 * } ),
7403 * new OO.ui.MenuOptionWidget( {
7404 * data: 'poodle',
7405 * label: 'Standard Poodle'
7406 * } ),
7407 * new OO.ui.MenuSectionOptionWidget( {
7408 * label: 'Cats'
7409 * } ),
7410 * new OO.ui.MenuOptionWidget( {
7411 * data: 'lion',
7412 * label: 'Lion'
7413 * } )
7414 * ]
7415 * }
7416 * } );
7417 * $( 'body' ).append( myDropdown.$element );
7418 *
7419 * @class
7420 * @extends OO.ui.DecoratedOptionWidget
7421 *
7422 * @constructor
7423 * @param {Object} [config] Configuration options
7424 */
7425 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
7426 // Parent constructor
7427 OO.ui.MenuSectionOptionWidget.parent.call( this, config );
7428
7429 // Initialization
7430 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' )
7431 .removeAttr( 'role aria-selected' );
7432 };
7433
7434 /* Setup */
7435
7436 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
7437
7438 /* Static Properties */
7439
7440 /**
7441 * @static
7442 * @inheritdoc
7443 */
7444 OO.ui.MenuSectionOptionWidget.static.selectable = false;
7445
7446 /**
7447 * @static
7448 * @inheritdoc
7449 */
7450 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
7451
7452 /**
7453 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
7454 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
7455 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
7456 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
7457 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
7458 * and customized to be opened, closed, and displayed as needed.
7459 *
7460 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
7461 * mouse outside the menu.
7462 *
7463 * Menus also have support for keyboard interaction:
7464 *
7465 * - Enter/Return key: choose and select a menu option
7466 * - Up-arrow key: highlight the previous menu option
7467 * - Down-arrow key: highlight the next menu option
7468 * - Esc key: hide the menu
7469 *
7470 * Unlike most widgets, MenuSelectWidget is initially hidden and must be shown by calling #toggle.
7471 *
7472 * Please see the [OOUI documentation on MediaWiki][1] for more information.
7473 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7474 *
7475 * @class
7476 * @extends OO.ui.SelectWidget
7477 * @mixins OO.ui.mixin.ClippableElement
7478 * @mixins OO.ui.mixin.FloatableElement
7479 *
7480 * @constructor
7481 * @param {Object} [config] Configuration options
7482 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
7483 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
7484 * and {@link OO.ui.mixin.LookupElement LookupElement}
7485 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
7486 * the text the user types. This config is used by {@link OO.ui.TagMultiselectWidget TagMultiselectWidget}
7487 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
7488 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
7489 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
7490 * that button, unless the button (or its parent widget) is passed in here.
7491 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
7492 * @cfg {jQuery} [$autoCloseIgnore] If these elements are clicked, don't auto-hide the menu.
7493 * @cfg {boolean} [hideOnChoose=true] Hide the menu when the user chooses an option.
7494 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
7495 * @cfg {boolean} [highlightOnFilter] Highlight the first result when filtering
7496 * @cfg {number} [width] Width of the menu
7497 */
7498 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
7499 // Configuration initialization
7500 config = config || {};
7501
7502 // Parent constructor
7503 OO.ui.MenuSelectWidget.parent.call( this, config );
7504
7505 // Mixin constructors
7506 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
7507 OO.ui.mixin.FloatableElement.call( this, config );
7508
7509 // Initial vertical positions other than 'center' will result in
7510 // the menu being flipped if there is not enough space in the container.
7511 // Store the original position so we know what to reset to.
7512 this.originalVerticalPosition = this.verticalPosition;
7513
7514 // Properties
7515 this.autoHide = config.autoHide === undefined || !!config.autoHide;
7516 this.hideOnChoose = config.hideOnChoose === undefined || !!config.hideOnChoose;
7517 this.filterFromInput = !!config.filterFromInput;
7518 this.$input = config.$input ? config.$input : config.input ? config.input.$input : null;
7519 this.$widget = config.widget ? config.widget.$element : null;
7520 this.$autoCloseIgnore = config.$autoCloseIgnore || $( [] );
7521 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
7522 this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 );
7523 this.highlightOnFilter = !!config.highlightOnFilter;
7524 this.width = config.width;
7525
7526 // Initialization
7527 this.$element.addClass( 'oo-ui-menuSelectWidget' );
7528 if ( config.widget ) {
7529 this.setFocusOwner( config.widget.$tabIndexed );
7530 }
7531
7532 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
7533 // that reference properties not initialized at that time of parent class construction
7534 // TODO: Find a better way to handle post-constructor setup
7535 this.visible = false;
7536 this.$element.addClass( 'oo-ui-element-hidden' );
7537 };
7538
7539 /* Setup */
7540
7541 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
7542 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement );
7543 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.FloatableElement );
7544
7545 /* Events */
7546
7547 /**
7548 * @event ready
7549 *
7550 * The menu is ready: it is visible and has been positioned and clipped.
7551 */
7552
7553 /* Static properties */
7554
7555 /**
7556 * Positions to flip to if there isn't room in the container for the
7557 * menu in a specific direction.
7558 *
7559 * @property {Object.<string,string>}
7560 */
7561 OO.ui.MenuSelectWidget.static.flippedPositions = {
7562 below: 'above',
7563 above: 'below',
7564 top: 'bottom',
7565 bottom: 'top'
7566 };
7567
7568 /* Methods */
7569
7570 /**
7571 * Handles document mouse down events.
7572 *
7573 * @protected
7574 * @param {MouseEvent} e Mouse down event
7575 */
7576 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
7577 if (
7578 this.isVisible() &&
7579 !OO.ui.contains(
7580 this.$element.add( this.$widget ).add( this.$autoCloseIgnore ).get(),
7581 e.target,
7582 true
7583 )
7584 ) {
7585 this.toggle( false );
7586 }
7587 };
7588
7589 /**
7590 * @inheritdoc
7591 */
7592 OO.ui.MenuSelectWidget.prototype.onDocumentKeyDown = function ( e ) {
7593 var currentItem = this.findHighlightedItem() || this.findSelectedItem();
7594
7595 if ( !this.isDisabled() && this.isVisible() ) {
7596 switch ( e.keyCode ) {
7597 case OO.ui.Keys.LEFT:
7598 case OO.ui.Keys.RIGHT:
7599 // Do nothing if a text field is associated, arrow keys will be handled natively
7600 if ( !this.$input ) {
7601 OO.ui.MenuSelectWidget.parent.prototype.onDocumentKeyDown.call( this, e );
7602 }
7603 break;
7604 case OO.ui.Keys.ESCAPE:
7605 case OO.ui.Keys.TAB:
7606 if ( currentItem ) {
7607 currentItem.setHighlighted( false );
7608 }
7609 this.toggle( false );
7610 // Don't prevent tabbing away, prevent defocusing
7611 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
7612 e.preventDefault();
7613 e.stopPropagation();
7614 }
7615 break;
7616 default:
7617 OO.ui.MenuSelectWidget.parent.prototype.onDocumentKeyDown.call( this, e );
7618 return;
7619 }
7620 }
7621 };
7622
7623 /**
7624 * Update menu item visibility and clipping after input changes (if filterFromInput is enabled)
7625 * or after items were added/removed (always).
7626 *
7627 * @protected
7628 */
7629 OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () {
7630 var i, item, items, visible, section, sectionEmpty, filter, exactFilter,
7631 anyVisible = false,
7632 len = this.items.length,
7633 showAll = !this.isVisible(),
7634 exactMatch = false;
7635
7636 if ( this.$input && this.filterFromInput ) {
7637 filter = showAll ? null : this.getItemMatcher( this.$input.val() );
7638 exactFilter = this.getItemMatcher( this.$input.val(), true );
7639 // Hide non-matching options, and also hide section headers if all options
7640 // in their section are hidden.
7641 for ( i = 0; i < len; i++ ) {
7642 item = this.items[ i ];
7643 if ( item instanceof OO.ui.MenuSectionOptionWidget ) {
7644 if ( section ) {
7645 // If the previous section was empty, hide its header
7646 section.toggle( showAll || !sectionEmpty );
7647 }
7648 section = item;
7649 sectionEmpty = true;
7650 } else if ( item instanceof OO.ui.OptionWidget ) {
7651 visible = showAll || filter( item );
7652 exactMatch = exactMatch || exactFilter( item );
7653 anyVisible = anyVisible || visible;
7654 sectionEmpty = sectionEmpty && !visible;
7655 item.toggle( visible );
7656 }
7657 }
7658 // Process the final section
7659 if ( section ) {
7660 section.toggle( showAll || !sectionEmpty );
7661 }
7662
7663 if ( anyVisible && this.items.length && !exactMatch ) {
7664 this.scrollItemIntoView( this.items[ 0 ] );
7665 }
7666
7667 this.$element.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible );
7668
7669 if ( this.highlightOnFilter ) {
7670 // Highlight the first item on the list
7671 item = null;
7672 items = this.getItems();
7673 for ( i = 0; i < items.length; i++ ) {
7674 if ( items[ i ].isVisible() ) {
7675 item = items[ i ];
7676 break;
7677 }
7678 }
7679 this.highlightItem( item );
7680 }
7681
7682 }
7683
7684 // Reevaluate clipping
7685 this.clip();
7686 };
7687
7688 /**
7689 * @inheritdoc
7690 */
7691 OO.ui.MenuSelectWidget.prototype.bindDocumentKeyDownListener = function () {
7692 if ( this.$input ) {
7693 this.$input.on( 'keydown', this.onDocumentKeyDownHandler );
7694 } else {
7695 OO.ui.MenuSelectWidget.parent.prototype.bindDocumentKeyDownListener.call( this );
7696 }
7697 };
7698
7699 /**
7700 * @inheritdoc
7701 */
7702 OO.ui.MenuSelectWidget.prototype.unbindDocumentKeyDownListener = function () {
7703 if ( this.$input ) {
7704 this.$input.off( 'keydown', this.onDocumentKeyDownHandler );
7705 } else {
7706 OO.ui.MenuSelectWidget.parent.prototype.unbindDocumentKeyDownListener.call( this );
7707 }
7708 };
7709
7710 /**
7711 * @inheritdoc
7712 */
7713 OO.ui.MenuSelectWidget.prototype.bindDocumentKeyPressListener = function () {
7714 if ( this.$input ) {
7715 if ( this.filterFromInput ) {
7716 this.$input.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
7717 this.updateItemVisibility();
7718 }
7719 } else {
7720 OO.ui.MenuSelectWidget.parent.prototype.bindDocumentKeyPressListener.call( this );
7721 }
7722 };
7723
7724 /**
7725 * @inheritdoc
7726 */
7727 OO.ui.MenuSelectWidget.prototype.unbindDocumentKeyPressListener = function () {
7728 if ( this.$input ) {
7729 if ( this.filterFromInput ) {
7730 this.$input.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
7731 this.updateItemVisibility();
7732 }
7733 } else {
7734 OO.ui.MenuSelectWidget.parent.prototype.unbindDocumentKeyPressListener.call( this );
7735 }
7736 };
7737
7738 /**
7739 * Choose an item.
7740 *
7741 * When a user chooses an item, the menu is closed, unless the hideOnChoose config option is set to false.
7742 *
7743 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
7744 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
7745 *
7746 * @param {OO.ui.OptionWidget} item Item to choose
7747 * @chainable
7748 * @return {OO.ui.Widget} The widget, for chaining
7749 */
7750 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
7751 OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item );
7752 if ( this.hideOnChoose ) {
7753 this.toggle( false );
7754 }
7755 return this;
7756 };
7757
7758 /**
7759 * @inheritdoc
7760 */
7761 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
7762 // Parent method
7763 OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index );
7764
7765 this.updateItemVisibility();
7766
7767 return this;
7768 };
7769
7770 /**
7771 * @inheritdoc
7772 */
7773 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
7774 // Parent method
7775 OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items );
7776
7777 this.updateItemVisibility();
7778
7779 return this;
7780 };
7781
7782 /**
7783 * @inheritdoc
7784 */
7785 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
7786 // Parent method
7787 OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this );
7788
7789 this.updateItemVisibility();
7790
7791 return this;
7792 };
7793
7794 /**
7795 * Toggle visibility of the menu. The menu is initially hidden and must be shown by calling
7796 * `.toggle( true )` after its #$element is attached to the DOM.
7797 *
7798 * Do not show the menu while it is not attached to the DOM. The calculations required to display
7799 * it in the right place and with the right dimensions only work correctly while it is attached.
7800 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
7801 * strictly enforced, so currently it only generates a warning in the browser console.
7802 *
7803 * @fires ready
7804 * @inheritdoc
7805 */
7806 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
7807 var change, originalHeight, flippedHeight;
7808
7809 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
7810 change = visible !== this.isVisible();
7811
7812 if ( visible && !this.warnedUnattached && !this.isElementAttached() ) {
7813 OO.ui.warnDeprecation( 'MenuSelectWidget#toggle: Before calling this method, the menu must be attached to the DOM.' );
7814 this.warnedUnattached = true;
7815 }
7816
7817 if ( change && visible ) {
7818 // Reset position before showing the popup again. It's possible we no longer need to flip
7819 // (e.g. if the user scrolled).
7820 this.setVerticalPosition( this.originalVerticalPosition );
7821 }
7822
7823 // Parent method
7824 OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible );
7825
7826 if ( change ) {
7827 if ( visible ) {
7828
7829 if ( this.width ) {
7830 this.setIdealSize( this.width );
7831 } else if ( this.$floatableContainer ) {
7832 this.$clippable.css( 'width', 'auto' );
7833 this.setIdealSize(
7834 this.$floatableContainer[ 0 ].offsetWidth > this.$clippable[ 0 ].offsetWidth ?
7835 // Dropdown is smaller than handle so expand to width
7836 this.$floatableContainer[ 0 ].offsetWidth :
7837 // Dropdown is larger than handle so auto size
7838 'auto'
7839 );
7840 this.$clippable.css( 'width', '' );
7841 }
7842
7843 this.togglePositioning( !!this.$floatableContainer );
7844 this.toggleClipping( true );
7845
7846 this.bindDocumentKeyDownListener();
7847 this.bindDocumentKeyPressListener();
7848
7849 if (
7850 ( this.isClippedVertically() || this.isFloatableOutOfView() ) &&
7851 this.originalVerticalPosition !== 'center'
7852 ) {
7853 // If opening the menu in one direction causes it to be clipped, flip it
7854 originalHeight = this.$element.height();
7855 this.setVerticalPosition(
7856 this.constructor.static.flippedPositions[ this.originalVerticalPosition ]
7857 );
7858 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
7859 // If flipping also causes it to be clipped, open in whichever direction
7860 // we have more space
7861 flippedHeight = this.$element.height();
7862 if ( originalHeight > flippedHeight ) {
7863 this.setVerticalPosition( this.originalVerticalPosition );
7864 }
7865 }
7866 }
7867 // Note that we do not flip the menu's opening direction if the clipping changes
7868 // later (e.g. after the user scrolls), that seems like it would be annoying
7869
7870 this.$focusOwner.attr( 'aria-expanded', 'true' );
7871
7872 if ( this.findSelectedItem() ) {
7873 this.$focusOwner.attr( 'aria-activedescendant', this.findSelectedItem().getElementId() );
7874 this.findSelectedItem().scrollElementIntoView( { duration: 0 } );
7875 }
7876
7877 // Auto-hide
7878 if ( this.autoHide ) {
7879 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
7880 }
7881
7882 this.emit( 'ready' );
7883 } else {
7884 this.$focusOwner.removeAttr( 'aria-activedescendant' );
7885 this.unbindDocumentKeyDownListener();
7886 this.unbindDocumentKeyPressListener();
7887 this.$focusOwner.attr( 'aria-expanded', 'false' );
7888 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
7889 this.togglePositioning( false );
7890 this.toggleClipping( false );
7891 }
7892 }
7893
7894 return this;
7895 };
7896
7897 /**
7898 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
7899 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
7900 * users can interact with it.
7901 *
7902 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7903 * OO.ui.DropdownInputWidget instead.
7904 *
7905 * @example
7906 * // Example: A DropdownWidget with a menu that contains three options
7907 * var dropDown = new OO.ui.DropdownWidget( {
7908 * label: 'Dropdown menu: Select a menu option',
7909 * menu: {
7910 * items: [
7911 * new OO.ui.MenuOptionWidget( {
7912 * data: 'a',
7913 * label: 'First'
7914 * } ),
7915 * new OO.ui.MenuOptionWidget( {
7916 * data: 'b',
7917 * label: 'Second'
7918 * } ),
7919 * new OO.ui.MenuOptionWidget( {
7920 * data: 'c',
7921 * label: 'Third'
7922 * } )
7923 * ]
7924 * }
7925 * } );
7926 *
7927 * $( 'body' ).append( dropDown.$element );
7928 *
7929 * dropDown.getMenu().selectItemByData( 'b' );
7930 *
7931 * dropDown.getMenu().findSelectedItem().getData(); // returns 'b'
7932 *
7933 * For more information, please see the [OOUI documentation on MediaWiki] [1].
7934 *
7935 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
7936 *
7937 * @class
7938 * @extends OO.ui.Widget
7939 * @mixins OO.ui.mixin.IconElement
7940 * @mixins OO.ui.mixin.IndicatorElement
7941 * @mixins OO.ui.mixin.LabelElement
7942 * @mixins OO.ui.mixin.TitledElement
7943 * @mixins OO.ui.mixin.TabIndexedElement
7944 *
7945 * @constructor
7946 * @param {Object} [config] Configuration options
7947 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.MenuSelectWidget menu select widget}
7948 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
7949 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
7950 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
7951 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
7952 */
7953 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
7954 // Configuration initialization
7955 config = $.extend( { indicator: 'down' }, config );
7956
7957 // Parent constructor
7958 OO.ui.DropdownWidget.parent.call( this, config );
7959
7960 // Properties (must be set before TabIndexedElement constructor call)
7961 this.$handle = $( '<span>' );
7962 this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
7963
7964 // Mixin constructors
7965 OO.ui.mixin.IconElement.call( this, config );
7966 OO.ui.mixin.IndicatorElement.call( this, config );
7967 OO.ui.mixin.LabelElement.call( this, config );
7968 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
7969 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
7970
7971 // Properties
7972 this.menu = new OO.ui.MenuSelectWidget( $.extend( {
7973 widget: this,
7974 $floatableContainer: this.$element
7975 }, config.menu ) );
7976
7977 // Events
7978 this.$handle.on( {
7979 click: this.onClick.bind( this ),
7980 keydown: this.onKeyDown.bind( this ),
7981 // Hack? Handle type-to-search when menu is not expanded and not handling its own events
7982 keypress: this.menu.onDocumentKeyPressHandler,
7983 blur: this.menu.clearKeyPressBuffer.bind( this.menu )
7984 } );
7985 this.menu.connect( this, {
7986 select: 'onMenuSelect',
7987 toggle: 'onMenuToggle'
7988 } );
7989
7990 // Initialization
7991 this.$handle
7992 .addClass( 'oo-ui-dropdownWidget-handle' )
7993 .attr( {
7994 role: 'combobox',
7995 'aria-owns': this.menu.getElementId(),
7996 'aria-autocomplete': 'list'
7997 } )
7998 .append( this.$icon, this.$label, this.$indicator );
7999 this.$element
8000 .addClass( 'oo-ui-dropdownWidget' )
8001 .append( this.$handle );
8002 this.$overlay.append( this.menu.$element );
8003 };
8004
8005 /* Setup */
8006
8007 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
8008 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IconElement );
8009 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IndicatorElement );
8010 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.LabelElement );
8011 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TitledElement );
8012 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TabIndexedElement );
8013
8014 /* Methods */
8015
8016 /**
8017 * Get the menu.
8018 *
8019 * @return {OO.ui.MenuSelectWidget} Menu of widget
8020 */
8021 OO.ui.DropdownWidget.prototype.getMenu = function () {
8022 return this.menu;
8023 };
8024
8025 /**
8026 * Handles menu select events.
8027 *
8028 * @private
8029 * @param {OO.ui.MenuOptionWidget} item Selected menu item
8030 */
8031 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
8032 var selectedLabel;
8033
8034 if ( !item ) {
8035 this.setLabel( null );
8036 return;
8037 }
8038
8039 selectedLabel = item.getLabel();
8040
8041 // If the label is a DOM element, clone it, because setLabel will append() it
8042 if ( selectedLabel instanceof jQuery ) {
8043 selectedLabel = selectedLabel.clone();
8044 }
8045
8046 this.setLabel( selectedLabel );
8047 };
8048
8049 /**
8050 * Handle menu toggle events.
8051 *
8052 * @private
8053 * @param {boolean} isVisible Open state of the menu
8054 */
8055 OO.ui.DropdownWidget.prototype.onMenuToggle = function ( isVisible ) {
8056 this.$element.toggleClass( 'oo-ui-dropdownWidget-open', isVisible );
8057 this.$handle.attr(
8058 'aria-expanded',
8059 this.$element.hasClass( 'oo-ui-dropdownWidget-open' ).toString()
8060 );
8061 };
8062
8063 /**
8064 * Handle mouse click events.
8065 *
8066 * @private
8067 * @param {jQuery.Event} e Mouse click event
8068 * @return {undefined/boolean} False to prevent default if event is handled
8069 */
8070 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
8071 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
8072 this.menu.toggle();
8073 }
8074 return false;
8075 };
8076
8077 /**
8078 * Handle key down events.
8079 *
8080 * @private
8081 * @param {jQuery.Event} e Key down event
8082 * @return {undefined/boolean} False to prevent default if event is handled
8083 */
8084 OO.ui.DropdownWidget.prototype.onKeyDown = function ( e ) {
8085 if (
8086 !this.isDisabled() &&
8087 (
8088 e.which === OO.ui.Keys.ENTER ||
8089 (
8090 e.which === OO.ui.Keys.SPACE &&
8091 // Avoid conflicts with type-to-search, see SelectWidget#onKeyPress.
8092 // Space only closes the menu is the user is not typing to search.
8093 this.menu.keyPressBuffer === ''
8094 ) ||
8095 (
8096 !this.menu.isVisible() &&
8097 (
8098 e.which === OO.ui.Keys.UP ||
8099 e.which === OO.ui.Keys.DOWN
8100 )
8101 )
8102 )
8103 ) {
8104 this.menu.toggle();
8105 return false;
8106 }
8107 };
8108
8109 /**
8110 * RadioOptionWidget is an option widget that looks like a radio button.
8111 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
8112 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8113 *
8114 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8115 *
8116 * @class
8117 * @extends OO.ui.OptionWidget
8118 *
8119 * @constructor
8120 * @param {Object} [config] Configuration options
8121 */
8122 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
8123 // Configuration initialization
8124 config = config || {};
8125
8126 // Properties (must be done before parent constructor which calls #setDisabled)
8127 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
8128
8129 // Parent constructor
8130 OO.ui.RadioOptionWidget.parent.call( this, config );
8131
8132 // Initialization
8133 // Remove implicit role, we're handling it ourselves
8134 this.radio.$input.attr( 'role', 'presentation' );
8135 this.$element
8136 .addClass( 'oo-ui-radioOptionWidget' )
8137 .attr( 'role', 'radio' )
8138 .attr( 'aria-checked', 'false' )
8139 .removeAttr( 'aria-selected' )
8140 .prepend( this.radio.$element );
8141 };
8142
8143 /* Setup */
8144
8145 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
8146
8147 /* Static Properties */
8148
8149 /**
8150 * @static
8151 * @inheritdoc
8152 */
8153 OO.ui.RadioOptionWidget.static.highlightable = false;
8154
8155 /**
8156 * @static
8157 * @inheritdoc
8158 */
8159 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
8160
8161 /**
8162 * @static
8163 * @inheritdoc
8164 */
8165 OO.ui.RadioOptionWidget.static.pressable = false;
8166
8167 /**
8168 * @static
8169 * @inheritdoc
8170 */
8171 OO.ui.RadioOptionWidget.static.tagName = 'label';
8172
8173 /* Methods */
8174
8175 /**
8176 * @inheritdoc
8177 */
8178 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
8179 OO.ui.RadioOptionWidget.parent.prototype.setSelected.call( this, state );
8180
8181 this.radio.setSelected( state );
8182 this.$element
8183 .attr( 'aria-checked', state.toString() )
8184 .removeAttr( 'aria-selected' );
8185
8186 return this;
8187 };
8188
8189 /**
8190 * @inheritdoc
8191 */
8192 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
8193 OO.ui.RadioOptionWidget.parent.prototype.setDisabled.call( this, disabled );
8194
8195 this.radio.setDisabled( this.isDisabled() );
8196
8197 return this;
8198 };
8199
8200 /**
8201 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
8202 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
8203 * an interface for adding, removing and selecting options.
8204 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8205 *
8206 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8207 * OO.ui.RadioSelectInputWidget instead.
8208 *
8209 * @example
8210 * // A RadioSelectWidget with RadioOptions.
8211 * var option1 = new OO.ui.RadioOptionWidget( {
8212 * data: 'a',
8213 * label: 'Selected radio option'
8214 * } );
8215 *
8216 * var option2 = new OO.ui.RadioOptionWidget( {
8217 * data: 'b',
8218 * label: 'Unselected radio option'
8219 * } );
8220 *
8221 * var radioSelect=new OO.ui.RadioSelectWidget( {
8222 * items: [ option1, option2 ]
8223 * } );
8224 *
8225 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
8226 * radioSelect.selectItem( option1 );
8227 *
8228 * $( 'body' ).append( radioSelect.$element );
8229 *
8230 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8231
8232 *
8233 * @class
8234 * @extends OO.ui.SelectWidget
8235 * @mixins OO.ui.mixin.TabIndexedElement
8236 *
8237 * @constructor
8238 * @param {Object} [config] Configuration options
8239 */
8240 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
8241 // Parent constructor
8242 OO.ui.RadioSelectWidget.parent.call( this, config );
8243
8244 // Mixin constructors
8245 OO.ui.mixin.TabIndexedElement.call( this, config );
8246
8247 // Events
8248 this.$element.on( {
8249 focus: this.bindDocumentKeyDownListener.bind( this ),
8250 blur: this.unbindDocumentKeyDownListener.bind( this )
8251 } );
8252
8253 // Initialization
8254 this.$element
8255 .addClass( 'oo-ui-radioSelectWidget' )
8256 .attr( 'role', 'radiogroup' );
8257 };
8258
8259 /* Setup */
8260
8261 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
8262 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.mixin.TabIndexedElement );
8263
8264 /**
8265 * MultioptionWidgets are special elements that can be selected and configured with data. The
8266 * data is often unique for each option, but it does not have to be. MultioptionWidgets are used
8267 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
8268 * and examples, please see the [OOUI documentation on MediaWiki][1].
8269 *
8270 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Multioptions
8271 *
8272 * @class
8273 * @extends OO.ui.Widget
8274 * @mixins OO.ui.mixin.ItemWidget
8275 * @mixins OO.ui.mixin.LabelElement
8276 *
8277 * @constructor
8278 * @param {Object} [config] Configuration options
8279 * @cfg {boolean} [selected=false] Whether the option is initially selected
8280 */
8281 OO.ui.MultioptionWidget = function OoUiMultioptionWidget( config ) {
8282 // Configuration initialization
8283 config = config || {};
8284
8285 // Parent constructor
8286 OO.ui.MultioptionWidget.parent.call( this, config );
8287
8288 // Mixin constructors
8289 OO.ui.mixin.ItemWidget.call( this );
8290 OO.ui.mixin.LabelElement.call( this, config );
8291
8292 // Properties
8293 this.selected = null;
8294
8295 // Initialization
8296 this.$element
8297 .addClass( 'oo-ui-multioptionWidget' )
8298 .append( this.$label );
8299 this.setSelected( config.selected );
8300 };
8301
8302 /* Setup */
8303
8304 OO.inheritClass( OO.ui.MultioptionWidget, OO.ui.Widget );
8305 OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.ItemWidget );
8306 OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.LabelElement );
8307
8308 /* Events */
8309
8310 /**
8311 * @event change
8312 *
8313 * A change event is emitted when the selected state of the option changes.
8314 *
8315 * @param {boolean} selected Whether the option is now selected
8316 */
8317
8318 /* Methods */
8319
8320 /**
8321 * Check if the option is selected.
8322 *
8323 * @return {boolean} Item is selected
8324 */
8325 OO.ui.MultioptionWidget.prototype.isSelected = function () {
8326 return this.selected;
8327 };
8328
8329 /**
8330 * Set the option’s selected state. In general, all modifications to the selection
8331 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
8332 * method instead of this method.
8333 *
8334 * @param {boolean} [state=false] Select option
8335 * @chainable
8336 * @return {OO.ui.Widget} The widget, for chaining
8337 */
8338 OO.ui.MultioptionWidget.prototype.setSelected = function ( state ) {
8339 state = !!state;
8340 if ( this.selected !== state ) {
8341 this.selected = state;
8342 this.emit( 'change', state );
8343 this.$element.toggleClass( 'oo-ui-multioptionWidget-selected', state );
8344 }
8345 return this;
8346 };
8347
8348 /**
8349 * MultiselectWidget allows selecting multiple options from a list.
8350 *
8351 * For more information about menus and options, please see the [OOUI documentation on MediaWiki][1].
8352 *
8353 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
8354 *
8355 * @class
8356 * @abstract
8357 * @extends OO.ui.Widget
8358 * @mixins OO.ui.mixin.GroupWidget
8359 *
8360 * @constructor
8361 * @param {Object} [config] Configuration options
8362 * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
8363 */
8364 OO.ui.MultiselectWidget = function OoUiMultiselectWidget( config ) {
8365 // Parent constructor
8366 OO.ui.MultiselectWidget.parent.call( this, config );
8367
8368 // Configuration initialization
8369 config = config || {};
8370
8371 // Mixin constructors
8372 OO.ui.mixin.GroupWidget.call( this, config );
8373
8374 // Events
8375 this.aggregate( { change: 'select' } );
8376 // This is mostly for compatibility with TagMultiselectWidget... normally, 'change' is emitted
8377 // by GroupElement only when items are added/removed
8378 this.connect( this, { select: [ 'emit', 'change' ] } );
8379
8380 // Initialization
8381 if ( config.items ) {
8382 this.addItems( config.items );
8383 }
8384 this.$group.addClass( 'oo-ui-multiselectWidget-group' );
8385 this.$element.addClass( 'oo-ui-multiselectWidget' )
8386 .append( this.$group );
8387 };
8388
8389 /* Setup */
8390
8391 OO.inheritClass( OO.ui.MultiselectWidget, OO.ui.Widget );
8392 OO.mixinClass( OO.ui.MultiselectWidget, OO.ui.mixin.GroupWidget );
8393
8394 /* Events */
8395
8396 /**
8397 * @event change
8398 *
8399 * A change event is emitted when the set of items changes, or an item is selected or deselected.
8400 */
8401
8402 /**
8403 * @event select
8404 *
8405 * A select event is emitted when an item is selected or deselected.
8406 */
8407
8408 /* Methods */
8409
8410 /**
8411 * Find options that are selected.
8412 *
8413 * @return {OO.ui.MultioptionWidget[]} Selected options
8414 */
8415 OO.ui.MultiselectWidget.prototype.findSelectedItems = function () {
8416 return this.items.filter( function ( item ) {
8417 return item.isSelected();
8418 } );
8419 };
8420
8421 /**
8422 * Find the data of options that are selected.
8423 *
8424 * @return {Object[]|string[]} Values of selected options
8425 */
8426 OO.ui.MultiselectWidget.prototype.findSelectedItemsData = function () {
8427 return this.findSelectedItems().map( function ( item ) {
8428 return item.data;
8429 } );
8430 };
8431
8432 /**
8433 * Select options by reference. Options not mentioned in the `items` array will be deselected.
8434 *
8435 * @param {OO.ui.MultioptionWidget[]} items Items to select
8436 * @chainable
8437 * @return {OO.ui.Widget} The widget, for chaining
8438 */
8439 OO.ui.MultiselectWidget.prototype.selectItems = function ( items ) {
8440 this.items.forEach( function ( item ) {
8441 var selected = items.indexOf( item ) !== -1;
8442 item.setSelected( selected );
8443 } );
8444 return this;
8445 };
8446
8447 /**
8448 * Select items by their data. Options not mentioned in the `datas` array will be deselected.
8449 *
8450 * @param {Object[]|string[]} datas Values of items to select
8451 * @chainable
8452 * @return {OO.ui.Widget} The widget, for chaining
8453 */
8454 OO.ui.MultiselectWidget.prototype.selectItemsByData = function ( datas ) {
8455 var items,
8456 widget = this;
8457 items = datas.map( function ( data ) {
8458 return widget.findItemFromData( data );
8459 } );
8460 this.selectItems( items );
8461 return this;
8462 };
8463
8464 /**
8465 * CheckboxMultioptionWidget is an option widget that looks like a checkbox.
8466 * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
8467 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8468 *
8469 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8470 *
8471 * @class
8472 * @extends OO.ui.MultioptionWidget
8473 *
8474 * @constructor
8475 * @param {Object} [config] Configuration options
8476 */
8477 OO.ui.CheckboxMultioptionWidget = function OoUiCheckboxMultioptionWidget( config ) {
8478 // Configuration initialization
8479 config = config || {};
8480
8481 // Properties (must be done before parent constructor which calls #setDisabled)
8482 this.checkbox = new OO.ui.CheckboxInputWidget();
8483
8484 // Parent constructor
8485 OO.ui.CheckboxMultioptionWidget.parent.call( this, config );
8486
8487 // Events
8488 this.checkbox.on( 'change', this.onCheckboxChange.bind( this ) );
8489 this.$element.on( 'keydown', this.onKeyDown.bind( this ) );
8490
8491 // Initialization
8492 this.$element
8493 .addClass( 'oo-ui-checkboxMultioptionWidget' )
8494 .prepend( this.checkbox.$element );
8495 };
8496
8497 /* Setup */
8498
8499 OO.inheritClass( OO.ui.CheckboxMultioptionWidget, OO.ui.MultioptionWidget );
8500
8501 /* Static Properties */
8502
8503 /**
8504 * @static
8505 * @inheritdoc
8506 */
8507 OO.ui.CheckboxMultioptionWidget.static.tagName = 'label';
8508
8509 /* Methods */
8510
8511 /**
8512 * Handle checkbox selected state change.
8513 *
8514 * @private
8515 */
8516 OO.ui.CheckboxMultioptionWidget.prototype.onCheckboxChange = function () {
8517 this.setSelected( this.checkbox.isSelected() );
8518 };
8519
8520 /**
8521 * @inheritdoc
8522 */
8523 OO.ui.CheckboxMultioptionWidget.prototype.setSelected = function ( state ) {
8524 OO.ui.CheckboxMultioptionWidget.parent.prototype.setSelected.call( this, state );
8525 this.checkbox.setSelected( state );
8526 return this;
8527 };
8528
8529 /**
8530 * @inheritdoc
8531 */
8532 OO.ui.CheckboxMultioptionWidget.prototype.setDisabled = function ( disabled ) {
8533 OO.ui.CheckboxMultioptionWidget.parent.prototype.setDisabled.call( this, disabled );
8534 this.checkbox.setDisabled( this.isDisabled() );
8535 return this;
8536 };
8537
8538 /**
8539 * Focus the widget.
8540 */
8541 OO.ui.CheckboxMultioptionWidget.prototype.focus = function () {
8542 this.checkbox.focus();
8543 };
8544
8545 /**
8546 * Handle key down events.
8547 *
8548 * @protected
8549 * @param {jQuery.Event} e
8550 */
8551 OO.ui.CheckboxMultioptionWidget.prototype.onKeyDown = function ( e ) {
8552 var
8553 element = this.getElementGroup(),
8554 nextItem;
8555
8556 if ( e.keyCode === OO.ui.Keys.LEFT || e.keyCode === OO.ui.Keys.UP ) {
8557 nextItem = element.getRelativeFocusableItem( this, -1 );
8558 } else if ( e.keyCode === OO.ui.Keys.RIGHT || e.keyCode === OO.ui.Keys.DOWN ) {
8559 nextItem = element.getRelativeFocusableItem( this, 1 );
8560 }
8561
8562 if ( nextItem ) {
8563 e.preventDefault();
8564 nextItem.focus();
8565 }
8566 };
8567
8568 /**
8569 * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
8570 * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
8571 * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
8572 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8573 *
8574 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8575 * OO.ui.CheckboxMultiselectInputWidget instead.
8576 *
8577 * @example
8578 * // A CheckboxMultiselectWidget with CheckboxMultioptions.
8579 * var option1 = new OO.ui.CheckboxMultioptionWidget( {
8580 * data: 'a',
8581 * selected: true,
8582 * label: 'Selected checkbox'
8583 * } );
8584 *
8585 * var option2 = new OO.ui.CheckboxMultioptionWidget( {
8586 * data: 'b',
8587 * label: 'Unselected checkbox'
8588 * } );
8589 *
8590 * var multiselect=new OO.ui.CheckboxMultiselectWidget( {
8591 * items: [ option1, option2 ]
8592 * } );
8593 *
8594 * $( 'body' ).append( multiselect.$element );
8595 *
8596 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8597 *
8598 * @class
8599 * @extends OO.ui.MultiselectWidget
8600 *
8601 * @constructor
8602 * @param {Object} [config] Configuration options
8603 */
8604 OO.ui.CheckboxMultiselectWidget = function OoUiCheckboxMultiselectWidget( config ) {
8605 // Parent constructor
8606 OO.ui.CheckboxMultiselectWidget.parent.call( this, config );
8607
8608 // Properties
8609 this.$lastClicked = null;
8610
8611 // Events
8612 this.$group.on( 'click', this.onClick.bind( this ) );
8613
8614 // Initialization
8615 this.$element
8616 .addClass( 'oo-ui-checkboxMultiselectWidget' );
8617 };
8618
8619 /* Setup */
8620
8621 OO.inheritClass( OO.ui.CheckboxMultiselectWidget, OO.ui.MultiselectWidget );
8622
8623 /* Methods */
8624
8625 /**
8626 * Get an option by its position relative to the specified item (or to the start of the option array,
8627 * if item is `null`). The direction in which to search through the option array is specified with a
8628 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
8629 * `null` if there are no options in the array.
8630 *
8631 * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
8632 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
8633 * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items in the select
8634 */
8635 OO.ui.CheckboxMultiselectWidget.prototype.getRelativeFocusableItem = function ( item, direction ) {
8636 var currentIndex, nextIndex, i,
8637 increase = direction > 0 ? 1 : -1,
8638 len = this.items.length;
8639
8640 if ( item ) {
8641 currentIndex = this.items.indexOf( item );
8642 nextIndex = ( currentIndex + increase + len ) % len;
8643 } else {
8644 // If no item is selected and moving forward, start at the beginning.
8645 // If moving backward, start at the end.
8646 nextIndex = direction > 0 ? 0 : len - 1;
8647 }
8648
8649 for ( i = 0; i < len; i++ ) {
8650 item = this.items[ nextIndex ];
8651 if ( item && !item.isDisabled() ) {
8652 return item;
8653 }
8654 nextIndex = ( nextIndex + increase + len ) % len;
8655 }
8656 return null;
8657 };
8658
8659 /**
8660 * Handle click events on checkboxes.
8661 *
8662 * @param {jQuery.Event} e
8663 */
8664 OO.ui.CheckboxMultiselectWidget.prototype.onClick = function ( e ) {
8665 var $options, lastClickedIndex, nowClickedIndex, i, direction, wasSelected, items,
8666 $lastClicked = this.$lastClicked,
8667 $nowClicked = $( e.target ).closest( '.oo-ui-checkboxMultioptionWidget' )
8668 .not( '.oo-ui-widget-disabled' );
8669
8670 // Allow selecting multiple options at once by Shift-clicking them
8671 if ( $lastClicked && $nowClicked.length && e.shiftKey ) {
8672 $options = this.$group.find( '.oo-ui-checkboxMultioptionWidget' );
8673 lastClickedIndex = $options.index( $lastClicked );
8674 nowClickedIndex = $options.index( $nowClicked );
8675 // If it's the same item, either the user is being silly, or it's a fake event generated by the
8676 // browser. In either case we don't need custom handling.
8677 if ( nowClickedIndex !== lastClickedIndex ) {
8678 items = this.items;
8679 wasSelected = items[ nowClickedIndex ].isSelected();
8680 direction = nowClickedIndex > lastClickedIndex ? 1 : -1;
8681
8682 // This depends on the DOM order of the items and the order of the .items array being the same.
8683 for ( i = lastClickedIndex; i !== nowClickedIndex; i += direction ) {
8684 if ( !items[ i ].isDisabled() ) {
8685 items[ i ].setSelected( !wasSelected );
8686 }
8687 }
8688 // For the now-clicked element, use immediate timeout to allow the browser to do its own
8689 // handling first, then set our value. The order in which events happen is different for
8690 // clicks on the <input> and on the <label> and there are additional fake clicks fired for
8691 // non-click actions that change the checkboxes.
8692 e.preventDefault();
8693 setTimeout( function () {
8694 if ( !items[ nowClickedIndex ].isDisabled() ) {
8695 items[ nowClickedIndex ].setSelected( !wasSelected );
8696 }
8697 } );
8698 }
8699 }
8700
8701 if ( $nowClicked.length ) {
8702 this.$lastClicked = $nowClicked;
8703 }
8704 };
8705
8706 /**
8707 * Focus the widget
8708 *
8709 * @chainable
8710 * @return {OO.ui.Widget} The widget, for chaining
8711 */
8712 OO.ui.CheckboxMultiselectWidget.prototype.focus = function () {
8713 var item;
8714 if ( !this.isDisabled() ) {
8715 item = this.getRelativeFocusableItem( null, 1 );
8716 if ( item ) {
8717 item.focus();
8718 }
8719 }
8720 return this;
8721 };
8722
8723 /**
8724 * @inheritdoc
8725 */
8726 OO.ui.CheckboxMultiselectWidget.prototype.simulateLabelClick = function () {
8727 this.focus();
8728 };
8729
8730 /**
8731 * Progress bars visually display the status of an operation, such as a download,
8732 * and can be either determinate or indeterminate:
8733 *
8734 * - **determinate** process bars show the percent of an operation that is complete.
8735 *
8736 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
8737 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
8738 * not use percentages.
8739 *
8740 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
8741 *
8742 * @example
8743 * // Examples of determinate and indeterminate progress bars.
8744 * var progressBar1 = new OO.ui.ProgressBarWidget( {
8745 * progress: 33
8746 * } );
8747 * var progressBar2 = new OO.ui.ProgressBarWidget();
8748 *
8749 * // Create a FieldsetLayout to layout progress bars
8750 * var fieldset = new OO.ui.FieldsetLayout;
8751 * fieldset.addItems( [
8752 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
8753 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
8754 * ] );
8755 * $( 'body' ).append( fieldset.$element );
8756 *
8757 * @class
8758 * @extends OO.ui.Widget
8759 *
8760 * @constructor
8761 * @param {Object} [config] Configuration options
8762 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
8763 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
8764 * By default, the progress bar is indeterminate.
8765 */
8766 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
8767 // Configuration initialization
8768 config = config || {};
8769
8770 // Parent constructor
8771 OO.ui.ProgressBarWidget.parent.call( this, config );
8772
8773 // Properties
8774 this.$bar = $( '<div>' );
8775 this.progress = null;
8776
8777 // Initialization
8778 this.setProgress( config.progress !== undefined ? config.progress : false );
8779 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
8780 this.$element
8781 .attr( {
8782 role: 'progressbar',
8783 'aria-valuemin': 0,
8784 'aria-valuemax': 100
8785 } )
8786 .addClass( 'oo-ui-progressBarWidget' )
8787 .append( this.$bar );
8788 };
8789
8790 /* Setup */
8791
8792 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
8793
8794 /* Static Properties */
8795
8796 /**
8797 * @static
8798 * @inheritdoc
8799 */
8800 OO.ui.ProgressBarWidget.static.tagName = 'div';
8801
8802 /* Methods */
8803
8804 /**
8805 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
8806 *
8807 * @return {number|boolean} Progress percent
8808 */
8809 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
8810 return this.progress;
8811 };
8812
8813 /**
8814 * Set the percent of the process completed or `false` for an indeterminate process.
8815 *
8816 * @param {number|boolean} progress Progress percent or `false` for indeterminate
8817 */
8818 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
8819 this.progress = progress;
8820
8821 if ( progress !== false ) {
8822 this.$bar.css( 'width', this.progress + '%' );
8823 this.$element.attr( 'aria-valuenow', this.progress );
8824 } else {
8825 this.$bar.css( 'width', '' );
8826 this.$element.removeAttr( 'aria-valuenow' );
8827 }
8828 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress === false );
8829 };
8830
8831 /**
8832 * InputWidget is the base class for all input widgets, which
8833 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
8834 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
8835 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
8836 *
8837 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
8838 *
8839 * @abstract
8840 * @class
8841 * @extends OO.ui.Widget
8842 * @mixins OO.ui.mixin.FlaggedElement
8843 * @mixins OO.ui.mixin.TabIndexedElement
8844 * @mixins OO.ui.mixin.TitledElement
8845 * @mixins OO.ui.mixin.AccessKeyedElement
8846 *
8847 * @constructor
8848 * @param {Object} [config] Configuration options
8849 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
8850 * @cfg {string} [value=''] The value of the input.
8851 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
8852 * @cfg {string} [inputId] The value of the input’s HTML `id` attribute.
8853 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
8854 * before it is accepted.
8855 */
8856 OO.ui.InputWidget = function OoUiInputWidget( config ) {
8857 // Configuration initialization
8858 config = config || {};
8859
8860 // Parent constructor
8861 OO.ui.InputWidget.parent.call( this, config );
8862
8863 // Properties
8864 // See #reusePreInfuseDOM about config.$input
8865 this.$input = config.$input || this.getInputElement( config );
8866 this.value = '';
8867 this.inputFilter = config.inputFilter;
8868
8869 // Mixin constructors
8870 OO.ui.mixin.FlaggedElement.call( this, config );
8871 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
8872 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
8873 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$input } ) );
8874
8875 // Events
8876 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
8877
8878 // Initialization
8879 this.$input
8880 .addClass( 'oo-ui-inputWidget-input' )
8881 .attr( 'name', config.name )
8882 .prop( 'disabled', this.isDisabled() );
8883 this.$element
8884 .addClass( 'oo-ui-inputWidget' )
8885 .append( this.$input );
8886 this.setValue( config.value );
8887 if ( config.dir ) {
8888 this.setDir( config.dir );
8889 }
8890 if ( config.inputId !== undefined ) {
8891 this.setInputId( config.inputId );
8892 }
8893 };
8894
8895 /* Setup */
8896
8897 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
8898 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.FlaggedElement );
8899 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TabIndexedElement );
8900 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TitledElement );
8901 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.AccessKeyedElement );
8902
8903 /* Static Methods */
8904
8905 /**
8906 * @inheritdoc
8907 */
8908 OO.ui.InputWidget.static.reusePreInfuseDOM = function ( node, config ) {
8909 config = OO.ui.InputWidget.parent.static.reusePreInfuseDOM( node, config );
8910 // Reusing `$input` lets browsers preserve inputted values across page reloads, see T114134.
8911 config.$input = $( node ).find( '.oo-ui-inputWidget-input' );
8912 return config;
8913 };
8914
8915 /**
8916 * @inheritdoc
8917 */
8918 OO.ui.InputWidget.static.gatherPreInfuseState = function ( node, config ) {
8919 var state = OO.ui.InputWidget.parent.static.gatherPreInfuseState( node, config );
8920 if ( config.$input && config.$input.length ) {
8921 state.value = config.$input.val();
8922 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
8923 state.focus = config.$input.is( ':focus' );
8924 }
8925 return state;
8926 };
8927
8928 /* Events */
8929
8930 /**
8931 * @event change
8932 *
8933 * A change event is emitted when the value of the input changes.
8934 *
8935 * @param {string} value
8936 */
8937
8938 /* Methods */
8939
8940 /**
8941 * Get input element.
8942 *
8943 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
8944 * different circumstances. The element must have a `value` property (like form elements).
8945 *
8946 * @protected
8947 * @param {Object} config Configuration options
8948 * @return {jQuery} Input element
8949 */
8950 OO.ui.InputWidget.prototype.getInputElement = function () {
8951 return $( '<input>' );
8952 };
8953
8954 /**
8955 * Handle potentially value-changing events.
8956 *
8957 * @private
8958 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
8959 */
8960 OO.ui.InputWidget.prototype.onEdit = function () {
8961 var widget = this;
8962 if ( !this.isDisabled() ) {
8963 // Allow the stack to clear so the value will be updated
8964 setTimeout( function () {
8965 widget.setValue( widget.$input.val() );
8966 } );
8967 }
8968 };
8969
8970 /**
8971 * Get the value of the input.
8972 *
8973 * @return {string} Input value
8974 */
8975 OO.ui.InputWidget.prototype.getValue = function () {
8976 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
8977 // it, and we won't know unless they're kind enough to trigger a 'change' event.
8978 var value = this.$input.val();
8979 if ( this.value !== value ) {
8980 this.setValue( value );
8981 }
8982 return this.value;
8983 };
8984
8985 /**
8986 * Set the directionality of the input.
8987 *
8988 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
8989 * @chainable
8990 * @return {OO.ui.Widget} The widget, for chaining
8991 */
8992 OO.ui.InputWidget.prototype.setDir = function ( dir ) {
8993 this.$input.prop( 'dir', dir );
8994 return this;
8995 };
8996
8997 /**
8998 * Set the value of the input.
8999 *
9000 * @param {string} value New value
9001 * @fires change
9002 * @chainable
9003 * @return {OO.ui.Widget} The widget, for chaining
9004 */
9005 OO.ui.InputWidget.prototype.setValue = function ( value ) {
9006 value = this.cleanUpValue( value );
9007 // Update the DOM if it has changed. Note that with cleanUpValue, it
9008 // is possible for the DOM value to change without this.value changing.
9009 if ( this.$input.val() !== value ) {
9010 this.$input.val( value );
9011 }
9012 if ( this.value !== value ) {
9013 this.value = value;
9014 this.emit( 'change', this.value );
9015 }
9016 // The first time that the value is set (probably while constructing the widget),
9017 // remember it in defaultValue. This property can be later used to check whether
9018 // the value of the input has been changed since it was created.
9019 if ( this.defaultValue === undefined ) {
9020 this.defaultValue = this.value;
9021 this.$input[ 0 ].defaultValue = this.defaultValue;
9022 }
9023 return this;
9024 };
9025
9026 /**
9027 * Clean up incoming value.
9028 *
9029 * Ensures value is a string, and converts undefined and null to empty string.
9030 *
9031 * @private
9032 * @param {string} value Original value
9033 * @return {string} Cleaned up value
9034 */
9035 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
9036 if ( value === undefined || value === null ) {
9037 return '';
9038 } else if ( this.inputFilter ) {
9039 return this.inputFilter( String( value ) );
9040 } else {
9041 return String( value );
9042 }
9043 };
9044
9045 /**
9046 * @inheritdoc
9047 */
9048 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
9049 OO.ui.InputWidget.parent.prototype.setDisabled.call( this, state );
9050 if ( this.$input ) {
9051 this.$input.prop( 'disabled', this.isDisabled() );
9052 }
9053 return this;
9054 };
9055
9056 /**
9057 * Set the 'id' attribute of the `<input>` element.
9058 *
9059 * @param {string} id
9060 * @chainable
9061 * @return {OO.ui.Widget} The widget, for chaining
9062 */
9063 OO.ui.InputWidget.prototype.setInputId = function ( id ) {
9064 this.$input.attr( 'id', id );
9065 return this;
9066 };
9067
9068 /**
9069 * @inheritdoc
9070 */
9071 OO.ui.InputWidget.prototype.restorePreInfuseState = function ( state ) {
9072 OO.ui.InputWidget.parent.prototype.restorePreInfuseState.call( this, state );
9073 if ( state.value !== undefined && state.value !== this.getValue() ) {
9074 this.setValue( state.value );
9075 }
9076 if ( state.focus ) {
9077 this.focus();
9078 }
9079 };
9080
9081 /**
9082 * Data widget intended for creating 'hidden'-type inputs.
9083 *
9084 * @class
9085 * @extends OO.ui.Widget
9086 *
9087 * @constructor
9088 * @param {Object} [config] Configuration options
9089 * @cfg {string} [value=''] The value of the input.
9090 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
9091 */
9092 OO.ui.HiddenInputWidget = function OoUiHiddenInputWidget( config ) {
9093 // Configuration initialization
9094 config = $.extend( { value: '', name: '' }, config );
9095
9096 // Parent constructor
9097 OO.ui.HiddenInputWidget.parent.call( this, config );
9098
9099 // Initialization
9100 this.$element.attr( {
9101 type: 'hidden',
9102 value: config.value,
9103 name: config.name
9104 } );
9105 this.$element.removeAttr( 'aria-disabled' );
9106 };
9107
9108 /* Setup */
9109
9110 OO.inheritClass( OO.ui.HiddenInputWidget, OO.ui.Widget );
9111
9112 /* Static Properties */
9113
9114 /**
9115 * @static
9116 * @inheritdoc
9117 */
9118 OO.ui.HiddenInputWidget.static.tagName = 'input';
9119
9120 /**
9121 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
9122 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
9123 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
9124 * HTML `<button>` (the default) or an HTML `<input>` tags. See the
9125 * [OOUI documentation on MediaWiki] [1] for more information.
9126 *
9127 * @example
9128 * // A ButtonInputWidget rendered as an HTML button, the default.
9129 * var button = new OO.ui.ButtonInputWidget( {
9130 * label: 'Input button',
9131 * icon: 'check',
9132 * value: 'check'
9133 * } );
9134 * $( 'body' ).append( button.$element );
9135 *
9136 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#Button_inputs
9137 *
9138 * @class
9139 * @extends OO.ui.InputWidget
9140 * @mixins OO.ui.mixin.ButtonElement
9141 * @mixins OO.ui.mixin.IconElement
9142 * @mixins OO.ui.mixin.IndicatorElement
9143 * @mixins OO.ui.mixin.LabelElement
9144 * @mixins OO.ui.mixin.TitledElement
9145 *
9146 * @constructor
9147 * @param {Object} [config] Configuration options
9148 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
9149 * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
9150 * Widgets configured to be an `<input>` do not support {@link #icon icons} and {@link #indicator indicators},
9151 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
9152 * be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
9153 */
9154 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
9155 // Configuration initialization
9156 config = $.extend( { type: 'button', useInputTag: false }, config );
9157
9158 // See InputWidget#reusePreInfuseDOM about config.$input
9159 if ( config.$input ) {
9160 config.$input.empty();
9161 }
9162
9163 // Properties (must be set before parent constructor, which calls #setValue)
9164 this.useInputTag = config.useInputTag;
9165
9166 // Parent constructor
9167 OO.ui.ButtonInputWidget.parent.call( this, config );
9168
9169 // Mixin constructors
9170 OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
9171 OO.ui.mixin.IconElement.call( this, config );
9172 OO.ui.mixin.IndicatorElement.call( this, config );
9173 OO.ui.mixin.LabelElement.call( this, config );
9174 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
9175
9176 // Initialization
9177 if ( !config.useInputTag ) {
9178 this.$input.append( this.$icon, this.$label, this.$indicator );
9179 }
9180 this.$element.addClass( 'oo-ui-buttonInputWidget' );
9181 };
9182
9183 /* Setup */
9184
9185 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
9186 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.ButtonElement );
9187 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IconElement );
9188 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IndicatorElement );
9189 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.LabelElement );
9190 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.TitledElement );
9191
9192 /* Static Properties */
9193
9194 /**
9195 * @static
9196 * @inheritdoc
9197 */
9198 OO.ui.ButtonInputWidget.static.tagName = 'span';
9199
9200 /* Methods */
9201
9202 /**
9203 * @inheritdoc
9204 * @protected
9205 */
9206 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
9207 var type;
9208 type = [ 'button', 'submit', 'reset' ].indexOf( config.type ) !== -1 ? config.type : 'button';
9209 return $( '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + type + '">' );
9210 };
9211
9212 /**
9213 * Set label value.
9214 *
9215 * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
9216 *
9217 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
9218 * text, or `null` for no label
9219 * @chainable
9220 * @return {OO.ui.Widget} The widget, for chaining
9221 */
9222 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
9223 if ( typeof label === 'function' ) {
9224 label = OO.ui.resolveMsg( label );
9225 }
9226
9227 if ( this.useInputTag ) {
9228 // Discard non-plaintext labels
9229 if ( typeof label !== 'string' ) {
9230 label = '';
9231 }
9232
9233 this.$input.val( label );
9234 }
9235
9236 return OO.ui.mixin.LabelElement.prototype.setLabel.call( this, label );
9237 };
9238
9239 /**
9240 * Set the value of the input.
9241 *
9242 * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
9243 * they do not support {@link #value values}.
9244 *
9245 * @param {string} value New value
9246 * @chainable
9247 * @return {OO.ui.Widget} The widget, for chaining
9248 */
9249 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
9250 if ( !this.useInputTag ) {
9251 OO.ui.ButtonInputWidget.parent.prototype.setValue.call( this, value );
9252 }
9253 return this;
9254 };
9255
9256 /**
9257 * @inheritdoc
9258 */
9259 OO.ui.ButtonInputWidget.prototype.getInputId = function () {
9260 // Disable generating `<label>` elements for buttons. One would very rarely need additional label
9261 // for a button, and it's already a big clickable target, and it causes unexpected rendering.
9262 return null;
9263 };
9264
9265 /**
9266 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
9267 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
9268 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
9269 * alignment. For more information, please see the [OOUI documentation on MediaWiki][1].
9270 *
9271 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9272 *
9273 * @example
9274 * // An example of selected, unselected, and disabled checkbox inputs
9275 * var checkbox1=new OO.ui.CheckboxInputWidget( {
9276 * value: 'a',
9277 * selected: true
9278 * } );
9279 * var checkbox2=new OO.ui.CheckboxInputWidget( {
9280 * value: 'b'
9281 * } );
9282 * var checkbox3=new OO.ui.CheckboxInputWidget( {
9283 * value:'c',
9284 * disabled: true
9285 * } );
9286 * // Create a fieldset layout with fields for each checkbox.
9287 * var fieldset = new OO.ui.FieldsetLayout( {
9288 * label: 'Checkboxes'
9289 * } );
9290 * fieldset.addItems( [
9291 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
9292 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
9293 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
9294 * ] );
9295 * $( 'body' ).append( fieldset.$element );
9296 *
9297 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9298 *
9299 * @class
9300 * @extends OO.ui.InputWidget
9301 *
9302 * @constructor
9303 * @param {Object} [config] Configuration options
9304 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
9305 */
9306 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
9307 // Configuration initialization
9308 config = config || {};
9309
9310 // Parent constructor
9311 OO.ui.CheckboxInputWidget.parent.call( this, config );
9312
9313 // Properties
9314 this.checkIcon = new OO.ui.IconWidget( {
9315 icon: 'check',
9316 classes: [ 'oo-ui-checkboxInputWidget-checkIcon' ]
9317 } );
9318
9319 // Initialization
9320 this.$element
9321 .addClass( 'oo-ui-checkboxInputWidget' )
9322 // Required for pretty styling in WikimediaUI theme
9323 .append( this.checkIcon.$element );
9324 this.setSelected( config.selected !== undefined ? config.selected : false );
9325 };
9326
9327 /* Setup */
9328
9329 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
9330
9331 /* Static Properties */
9332
9333 /**
9334 * @static
9335 * @inheritdoc
9336 */
9337 OO.ui.CheckboxInputWidget.static.tagName = 'span';
9338
9339 /* Static Methods */
9340
9341 /**
9342 * @inheritdoc
9343 */
9344 OO.ui.CheckboxInputWidget.static.gatherPreInfuseState = function ( node, config ) {
9345 var state = OO.ui.CheckboxInputWidget.parent.static.gatherPreInfuseState( node, config );
9346 state.checked = config.$input.prop( 'checked' );
9347 return state;
9348 };
9349
9350 /* Methods */
9351
9352 /**
9353 * @inheritdoc
9354 * @protected
9355 */
9356 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
9357 return $( '<input>' ).attr( 'type', 'checkbox' );
9358 };
9359
9360 /**
9361 * @inheritdoc
9362 */
9363 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
9364 var widget = this;
9365 if ( !this.isDisabled() ) {
9366 // Allow the stack to clear so the value will be updated
9367 setTimeout( function () {
9368 widget.setSelected( widget.$input.prop( 'checked' ) );
9369 } );
9370 }
9371 };
9372
9373 /**
9374 * Set selection state of this checkbox.
9375 *
9376 * @param {boolean} state `true` for selected
9377 * @chainable
9378 * @return {OO.ui.Widget} The widget, for chaining
9379 */
9380 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
9381 state = !!state;
9382 if ( this.selected !== state ) {
9383 this.selected = state;
9384 this.$input.prop( 'checked', this.selected );
9385 this.emit( 'change', this.selected );
9386 }
9387 // The first time that the selection state is set (probably while constructing the widget),
9388 // remember it in defaultSelected. This property can be later used to check whether
9389 // the selection state of the input has been changed since it was created.
9390 if ( this.defaultSelected === undefined ) {
9391 this.defaultSelected = this.selected;
9392 this.$input[ 0 ].defaultChecked = this.defaultSelected;
9393 }
9394 return this;
9395 };
9396
9397 /**
9398 * Check if this checkbox is selected.
9399 *
9400 * @return {boolean} Checkbox is selected
9401 */
9402 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
9403 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
9404 // it, and we won't know unless they're kind enough to trigger a 'change' event.
9405 var selected = this.$input.prop( 'checked' );
9406 if ( this.selected !== selected ) {
9407 this.setSelected( selected );
9408 }
9409 return this.selected;
9410 };
9411
9412 /**
9413 * @inheritdoc
9414 */
9415 OO.ui.CheckboxInputWidget.prototype.simulateLabelClick = function () {
9416 if ( !this.isDisabled() ) {
9417 this.$input.click();
9418 }
9419 this.focus();
9420 };
9421
9422 /**
9423 * @inheritdoc
9424 */
9425 OO.ui.CheckboxInputWidget.prototype.restorePreInfuseState = function ( state ) {
9426 OO.ui.CheckboxInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
9427 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
9428 this.setSelected( state.checked );
9429 }
9430 };
9431
9432 /**
9433 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
9434 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
9435 * of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9436 * more information about input widgets.
9437 *
9438 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
9439 * are no options. If no `value` configuration option is provided, the first option is selected.
9440 * If you need a state representing no value (no option being selected), use a DropdownWidget.
9441 *
9442 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
9443 *
9444 * @example
9445 * // Example: A DropdownInputWidget with three options
9446 * var dropdownInput = new OO.ui.DropdownInputWidget( {
9447 * options: [
9448 * { data: 'a', label: 'First' },
9449 * { data: 'b', label: 'Second'},
9450 * { data: 'c', label: 'Third' }
9451 * ]
9452 * } );
9453 * $( 'body' ).append( dropdownInput.$element );
9454 *
9455 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9456 *
9457 * @class
9458 * @extends OO.ui.InputWidget
9459 *
9460 * @constructor
9461 * @param {Object} [config] Configuration options
9462 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9463 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
9464 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
9465 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
9466 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
9467 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
9468 */
9469 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
9470 // Configuration initialization
9471 config = config || {};
9472
9473 // Properties (must be done before parent constructor which calls #setDisabled)
9474 this.dropdownWidget = new OO.ui.DropdownWidget( $.extend(
9475 {
9476 $overlay: config.$overlay
9477 },
9478 config.dropdown
9479 ) );
9480 // Set up the options before parent constructor, which uses them to validate config.value.
9481 // Use this instead of setOptions() because this.$input is not set up yet.
9482 this.setOptionsData( config.options || [] );
9483
9484 // Parent constructor
9485 OO.ui.DropdownInputWidget.parent.call( this, config );
9486
9487 // Events
9488 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
9489
9490 // Initialization
9491 this.$element
9492 .addClass( 'oo-ui-dropdownInputWidget' )
9493 .append( this.dropdownWidget.$element );
9494 this.setTabIndexedElement( this.dropdownWidget.$tabIndexed );
9495 };
9496
9497 /* Setup */
9498
9499 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
9500
9501 /* Methods */
9502
9503 /**
9504 * @inheritdoc
9505 * @protected
9506 */
9507 OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
9508 return $( '<select>' );
9509 };
9510
9511 /**
9512 * Handles menu select events.
9513 *
9514 * @private
9515 * @param {OO.ui.MenuOptionWidget|null} item Selected menu item
9516 */
9517 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
9518 this.setValue( item ? item.getData() : '' );
9519 };
9520
9521 /**
9522 * @inheritdoc
9523 */
9524 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
9525 var selected;
9526 value = this.cleanUpValue( value );
9527 // Only allow setting values that are actually present in the dropdown
9528 selected = this.dropdownWidget.getMenu().findItemFromData( value ) ||
9529 this.dropdownWidget.getMenu().findFirstSelectableItem();
9530 this.dropdownWidget.getMenu().selectItem( selected );
9531 value = selected ? selected.getData() : '';
9532 OO.ui.DropdownInputWidget.parent.prototype.setValue.call( this, value );
9533 if ( this.optionsDirty ) {
9534 // We reached this from the constructor or from #setOptions.
9535 // We have to update the <select> element.
9536 this.updateOptionsInterface();
9537 }
9538 return this;
9539 };
9540
9541 /**
9542 * @inheritdoc
9543 */
9544 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
9545 this.dropdownWidget.setDisabled( state );
9546 OO.ui.DropdownInputWidget.parent.prototype.setDisabled.call( this, state );
9547 return this;
9548 };
9549
9550 /**
9551 * Set the options available for this input.
9552 *
9553 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9554 * @chainable
9555 * @return {OO.ui.Widget} The widget, for chaining
9556 */
9557 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
9558 var value = this.getValue();
9559
9560 this.setOptionsData( options );
9561
9562 // Re-set the value to update the visible interface (DropdownWidget and <select>).
9563 // In case the previous value is no longer an available option, select the first valid one.
9564 this.setValue( value );
9565
9566 return this;
9567 };
9568
9569 /**
9570 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
9571 *
9572 * This method may be called before the parent constructor, so various properties may not be
9573 * intialized yet.
9574 *
9575 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9576 * @private
9577 */
9578 OO.ui.DropdownInputWidget.prototype.setOptionsData = function ( options ) {
9579 var
9580 optionWidgets,
9581 widget = this;
9582
9583 this.optionsDirty = true;
9584
9585 optionWidgets = options.map( function ( opt ) {
9586 var optValue;
9587
9588 if ( opt.optgroup !== undefined ) {
9589 return widget.createMenuSectionOptionWidget( opt.optgroup );
9590 }
9591
9592 optValue = widget.cleanUpValue( opt.data );
9593 return widget.createMenuOptionWidget(
9594 optValue,
9595 opt.label !== undefined ? opt.label : optValue
9596 );
9597
9598 } );
9599
9600 this.dropdownWidget.getMenu().clearItems().addItems( optionWidgets );
9601 };
9602
9603 /**
9604 * Create a menu option widget.
9605 *
9606 * @protected
9607 * @param {string} data Item data
9608 * @param {string} label Item label
9609 * @return {OO.ui.MenuOptionWidget} Option widget
9610 */
9611 OO.ui.DropdownInputWidget.prototype.createMenuOptionWidget = function ( data, label ) {
9612 return new OO.ui.MenuOptionWidget( {
9613 data: data,
9614 label: label
9615 } );
9616 };
9617
9618 /**
9619 * Create a menu section option widget.
9620 *
9621 * @protected
9622 * @param {string} label Section item label
9623 * @return {OO.ui.MenuSectionOptionWidget} Menu section option widget
9624 */
9625 OO.ui.DropdownInputWidget.prototype.createMenuSectionOptionWidget = function ( label ) {
9626 return new OO.ui.MenuSectionOptionWidget( {
9627 label: label
9628 } );
9629 };
9630
9631 /**
9632 * Update the user-visible interface to match the internal list of options and value.
9633 *
9634 * This method must only be called after the parent constructor.
9635 *
9636 * @private
9637 */
9638 OO.ui.DropdownInputWidget.prototype.updateOptionsInterface = function () {
9639 var
9640 $optionsContainer = this.$input,
9641 defaultValue = this.defaultValue,
9642 widget = this;
9643
9644 this.$input.empty();
9645
9646 this.dropdownWidget.getMenu().getItems().forEach( function ( optionWidget ) {
9647 var $optionNode;
9648
9649 if ( !( optionWidget instanceof OO.ui.MenuSectionOptionWidget ) ) {
9650 $optionNode = $( '<option>' )
9651 .attr( 'value', optionWidget.getData() )
9652 .text( optionWidget.getLabel() );
9653
9654 // Remember original selection state. This property can be later used to check whether
9655 // the selection state of the input has been changed since it was created.
9656 $optionNode[ 0 ].defaultSelected = ( optionWidget.getData() === defaultValue );
9657
9658 $optionsContainer.append( $optionNode );
9659 } else {
9660 $optionNode = $( '<optgroup>' )
9661 .attr( 'label', optionWidget.getLabel() );
9662 widget.$input.append( $optionNode );
9663 $optionsContainer = $optionNode;
9664 }
9665 } );
9666
9667 this.optionsDirty = false;
9668 };
9669
9670 /**
9671 * @inheritdoc
9672 */
9673 OO.ui.DropdownInputWidget.prototype.focus = function () {
9674 this.dropdownWidget.focus();
9675 return this;
9676 };
9677
9678 /**
9679 * @inheritdoc
9680 */
9681 OO.ui.DropdownInputWidget.prototype.blur = function () {
9682 this.dropdownWidget.blur();
9683 return this;
9684 };
9685
9686 /**
9687 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
9688 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
9689 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
9690 * please see the [OOUI documentation on MediaWiki][1].
9691 *
9692 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9693 *
9694 * @example
9695 * // An example of selected, unselected, and disabled radio inputs
9696 * var radio1 = new OO.ui.RadioInputWidget( {
9697 * value: 'a',
9698 * selected: true
9699 * } );
9700 * var radio2 = new OO.ui.RadioInputWidget( {
9701 * value: 'b'
9702 * } );
9703 * var radio3 = new OO.ui.RadioInputWidget( {
9704 * value: 'c',
9705 * disabled: true
9706 * } );
9707 * // Create a fieldset layout with fields for each radio button.
9708 * var fieldset = new OO.ui.FieldsetLayout( {
9709 * label: 'Radio inputs'
9710 * } );
9711 * fieldset.addItems( [
9712 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
9713 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
9714 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
9715 * ] );
9716 * $( 'body' ).append( fieldset.$element );
9717 *
9718 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9719 *
9720 * @class
9721 * @extends OO.ui.InputWidget
9722 *
9723 * @constructor
9724 * @param {Object} [config] Configuration options
9725 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
9726 */
9727 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
9728 // Configuration initialization
9729 config = config || {};
9730
9731 // Parent constructor
9732 OO.ui.RadioInputWidget.parent.call( this, config );
9733
9734 // Initialization
9735 this.$element
9736 .addClass( 'oo-ui-radioInputWidget' )
9737 // Required for pretty styling in WikimediaUI theme
9738 .append( $( '<span>' ) );
9739 this.setSelected( config.selected !== undefined ? config.selected : false );
9740 };
9741
9742 /* Setup */
9743
9744 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
9745
9746 /* Static Properties */
9747
9748 /**
9749 * @static
9750 * @inheritdoc
9751 */
9752 OO.ui.RadioInputWidget.static.tagName = 'span';
9753
9754 /* Static Methods */
9755
9756 /**
9757 * @inheritdoc
9758 */
9759 OO.ui.RadioInputWidget.static.gatherPreInfuseState = function ( node, config ) {
9760 var state = OO.ui.RadioInputWidget.parent.static.gatherPreInfuseState( node, config );
9761 state.checked = config.$input.prop( 'checked' );
9762 return state;
9763 };
9764
9765 /* Methods */
9766
9767 /**
9768 * @inheritdoc
9769 * @protected
9770 */
9771 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
9772 return $( '<input>' ).attr( 'type', 'radio' );
9773 };
9774
9775 /**
9776 * @inheritdoc
9777 */
9778 OO.ui.RadioInputWidget.prototype.onEdit = function () {
9779 // RadioInputWidget doesn't track its state.
9780 };
9781
9782 /**
9783 * Set selection state of this radio button.
9784 *
9785 * @param {boolean} state `true` for selected
9786 * @chainable
9787 * @return {OO.ui.Widget} The widget, for chaining
9788 */
9789 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
9790 // RadioInputWidget doesn't track its state.
9791 this.$input.prop( 'checked', state );
9792 // The first time that the selection state is set (probably while constructing the widget),
9793 // remember it in defaultSelected. This property can be later used to check whether
9794 // the selection state of the input has been changed since it was created.
9795 if ( this.defaultSelected === undefined ) {
9796 this.defaultSelected = state;
9797 this.$input[ 0 ].defaultChecked = this.defaultSelected;
9798 }
9799 return this;
9800 };
9801
9802 /**
9803 * Check if this radio button is selected.
9804 *
9805 * @return {boolean} Radio is selected
9806 */
9807 OO.ui.RadioInputWidget.prototype.isSelected = function () {
9808 return this.$input.prop( 'checked' );
9809 };
9810
9811 /**
9812 * @inheritdoc
9813 */
9814 OO.ui.RadioInputWidget.prototype.simulateLabelClick = function () {
9815 if ( !this.isDisabled() ) {
9816 this.$input.click();
9817 }
9818 this.focus();
9819 };
9820
9821 /**
9822 * @inheritdoc
9823 */
9824 OO.ui.RadioInputWidget.prototype.restorePreInfuseState = function ( state ) {
9825 OO.ui.RadioInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
9826 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
9827 this.setSelected( state.checked );
9828 }
9829 };
9830
9831 /**
9832 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
9833 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
9834 * of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9835 * more information about input widgets.
9836 *
9837 * This and OO.ui.DropdownInputWidget support the same configuration options.
9838 *
9839 * @example
9840 * // Example: A RadioSelectInputWidget with three options
9841 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
9842 * options: [
9843 * { data: 'a', label: 'First' },
9844 * { data: 'b', label: 'Second'},
9845 * { data: 'c', label: 'Third' }
9846 * ]
9847 * } );
9848 * $( 'body' ).append( radioSelectInput.$element );
9849 *
9850 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9851 *
9852 * @class
9853 * @extends OO.ui.InputWidget
9854 *
9855 * @constructor
9856 * @param {Object} [config] Configuration options
9857 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9858 */
9859 OO.ui.RadioSelectInputWidget = function OoUiRadioSelectInputWidget( config ) {
9860 // Configuration initialization
9861 config = config || {};
9862
9863 // Properties (must be done before parent constructor which calls #setDisabled)
9864 this.radioSelectWidget = new OO.ui.RadioSelectWidget();
9865 // Set up the options before parent constructor, which uses them to validate config.value.
9866 // Use this instead of setOptions() because this.$input is not set up yet
9867 this.setOptionsData( config.options || [] );
9868
9869 // Parent constructor
9870 OO.ui.RadioSelectInputWidget.parent.call( this, config );
9871
9872 // Events
9873 this.radioSelectWidget.connect( this, { select: 'onMenuSelect' } );
9874
9875 // Initialization
9876 this.$element
9877 .addClass( 'oo-ui-radioSelectInputWidget' )
9878 .append( this.radioSelectWidget.$element );
9879 this.setTabIndexedElement( this.radioSelectWidget.$tabIndexed );
9880 };
9881
9882 /* Setup */
9883
9884 OO.inheritClass( OO.ui.RadioSelectInputWidget, OO.ui.InputWidget );
9885
9886 /* Static Methods */
9887
9888 /**
9889 * @inheritdoc
9890 */
9891 OO.ui.RadioSelectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
9892 var state = OO.ui.RadioSelectInputWidget.parent.static.gatherPreInfuseState( node, config );
9893 state.value = $( node ).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
9894 return state;
9895 };
9896
9897 /**
9898 * @inheritdoc
9899 */
9900 OO.ui.RadioSelectInputWidget.static.reusePreInfuseDOM = function ( node, config ) {
9901 config = OO.ui.RadioSelectInputWidget.parent.static.reusePreInfuseDOM( node, config );
9902 // Cannot reuse the `<input type=radio>` set
9903 delete config.$input;
9904 return config;
9905 };
9906
9907 /* Methods */
9908
9909 /**
9910 * @inheritdoc
9911 * @protected
9912 */
9913 OO.ui.RadioSelectInputWidget.prototype.getInputElement = function () {
9914 // Use this instead of <input type="hidden">, because hidden inputs do not have separate
9915 // 'value' and 'defaultValue' properties, and InputWidget wants to handle 'defaultValue'.
9916 return $( '<input>' ).addClass( 'oo-ui-element-hidden' );
9917 };
9918
9919 /**
9920 * Handles menu select events.
9921 *
9922 * @private
9923 * @param {OO.ui.RadioOptionWidget} item Selected menu item
9924 */
9925 OO.ui.RadioSelectInputWidget.prototype.onMenuSelect = function ( item ) {
9926 this.setValue( item.getData() );
9927 };
9928
9929 /**
9930 * @inheritdoc
9931 */
9932 OO.ui.RadioSelectInputWidget.prototype.setValue = function ( value ) {
9933 var selected;
9934 value = this.cleanUpValue( value );
9935 // Only allow setting values that are actually present in the dropdown
9936 selected = this.radioSelectWidget.findItemFromData( value ) ||
9937 this.radioSelectWidget.findFirstSelectableItem();
9938 this.radioSelectWidget.selectItem( selected );
9939 value = selected ? selected.getData() : '';
9940 OO.ui.RadioSelectInputWidget.parent.prototype.setValue.call( this, value );
9941 return this;
9942 };
9943
9944 /**
9945 * @inheritdoc
9946 */
9947 OO.ui.RadioSelectInputWidget.prototype.setDisabled = function ( state ) {
9948 this.radioSelectWidget.setDisabled( state );
9949 OO.ui.RadioSelectInputWidget.parent.prototype.setDisabled.call( this, state );
9950 return this;
9951 };
9952
9953 /**
9954 * Set the options available for this input.
9955 *
9956 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9957 * @chainable
9958 * @return {OO.ui.Widget} The widget, for chaining
9959 */
9960 OO.ui.RadioSelectInputWidget.prototype.setOptions = function ( options ) {
9961 var value = this.getValue();
9962
9963 this.setOptionsData( options );
9964
9965 // Re-set the value to update the visible interface (RadioSelectWidget).
9966 // In case the previous value is no longer an available option, select the first valid one.
9967 this.setValue( value );
9968
9969 return this;
9970 };
9971
9972 /**
9973 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
9974 *
9975 * This method may be called before the parent constructor, so various properties may not be
9976 * intialized yet.
9977 *
9978 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9979 * @private
9980 */
9981 OO.ui.RadioSelectInputWidget.prototype.setOptionsData = function ( options ) {
9982 var widget = this;
9983
9984 this.radioSelectWidget
9985 .clearItems()
9986 .addItems( options.map( function ( opt ) {
9987 var optValue = widget.cleanUpValue( opt.data );
9988 return new OO.ui.RadioOptionWidget( {
9989 data: optValue,
9990 label: opt.label !== undefined ? opt.label : optValue
9991 } );
9992 } ) );
9993 };
9994
9995 /**
9996 * @inheritdoc
9997 */
9998 OO.ui.RadioSelectInputWidget.prototype.focus = function () {
9999 this.radioSelectWidget.focus();
10000 return this;
10001 };
10002
10003 /**
10004 * @inheritdoc
10005 */
10006 OO.ui.RadioSelectInputWidget.prototype.blur = function () {
10007 this.radioSelectWidget.blur();
10008 return this;
10009 };
10010
10011 /**
10012 * CheckboxMultiselectInputWidget is a
10013 * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
10014 * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
10015 * HTML `<input type=checkbox>` tags. Please see the [OOUI documentation on MediaWiki][1] for
10016 * more information about input widgets.
10017 *
10018 * @example
10019 * // Example: A CheckboxMultiselectInputWidget with three options
10020 * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
10021 * options: [
10022 * { data: 'a', label: 'First' },
10023 * { data: 'b', label: 'Second'},
10024 * { data: 'c', label: 'Third' }
10025 * ]
10026 * } );
10027 * $( 'body' ).append( multiselectInput.$element );
10028 *
10029 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
10030 *
10031 * @class
10032 * @extends OO.ui.InputWidget
10033 *
10034 * @constructor
10035 * @param {Object} [config] Configuration options
10036 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: …, disabled: … }`
10037 */
10038 OO.ui.CheckboxMultiselectInputWidget = function OoUiCheckboxMultiselectInputWidget( config ) {
10039 // Configuration initialization
10040 config = config || {};
10041
10042 // Properties (must be done before parent constructor which calls #setDisabled)
10043 this.checkboxMultiselectWidget = new OO.ui.CheckboxMultiselectWidget();
10044 // Must be set before the #setOptionsData call below
10045 this.inputName = config.name;
10046 // Set up the options before parent constructor, which uses them to validate config.value.
10047 // Use this instead of setOptions() because this.$input is not set up yet
10048 this.setOptionsData( config.options || [] );
10049
10050 // Parent constructor
10051 OO.ui.CheckboxMultiselectInputWidget.parent.call( this, config );
10052
10053 // Events
10054 this.checkboxMultiselectWidget.connect( this, { select: 'onCheckboxesSelect' } );
10055
10056 // Initialization
10057 this.$element
10058 .addClass( 'oo-ui-checkboxMultiselectInputWidget' )
10059 .append( this.checkboxMultiselectWidget.$element );
10060 // We don't use this.$input, but rather the CheckboxInputWidgets inside each option
10061 this.$input.detach();
10062 };
10063
10064 /* Setup */
10065
10066 OO.inheritClass( OO.ui.CheckboxMultiselectInputWidget, OO.ui.InputWidget );
10067
10068 /* Static Methods */
10069
10070 /**
10071 * @inheritdoc
10072 */
10073 OO.ui.CheckboxMultiselectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
10074 var state = OO.ui.CheckboxMultiselectInputWidget.parent.static.gatherPreInfuseState( node, config );
10075 state.value = $( node ).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
10076 .toArray().map( function ( el ) { return el.value; } );
10077 return state;
10078 };
10079
10080 /**
10081 * @inheritdoc
10082 */
10083 OO.ui.CheckboxMultiselectInputWidget.static.reusePreInfuseDOM = function ( node, config ) {
10084 config = OO.ui.CheckboxMultiselectInputWidget.parent.static.reusePreInfuseDOM( node, config );
10085 // Cannot reuse the `<input type=checkbox>` set
10086 delete config.$input;
10087 return config;
10088 };
10089
10090 /* Methods */
10091
10092 /**
10093 * @inheritdoc
10094 * @protected
10095 */
10096 OO.ui.CheckboxMultiselectInputWidget.prototype.getInputElement = function () {
10097 // Actually unused
10098 return $( '<unused>' );
10099 };
10100
10101 /**
10102 * Handles CheckboxMultiselectWidget select events.
10103 *
10104 * @private
10105 */
10106 OO.ui.CheckboxMultiselectInputWidget.prototype.onCheckboxesSelect = function () {
10107 this.setValue( this.checkboxMultiselectWidget.findSelectedItemsData() );
10108 };
10109
10110 /**
10111 * @inheritdoc
10112 */
10113 OO.ui.CheckboxMultiselectInputWidget.prototype.getValue = function () {
10114 var value = this.$element.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
10115 .toArray().map( function ( el ) { return el.value; } );
10116 if ( this.value !== value ) {
10117 this.setValue( value );
10118 }
10119 return this.value;
10120 };
10121
10122 /**
10123 * @inheritdoc
10124 */
10125 OO.ui.CheckboxMultiselectInputWidget.prototype.setValue = function ( value ) {
10126 value = this.cleanUpValue( value );
10127 this.checkboxMultiselectWidget.selectItemsByData( value );
10128 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.setValue.call( this, value );
10129 if ( this.optionsDirty ) {
10130 // We reached this from the constructor or from #setOptions.
10131 // We have to update the <select> element.
10132 this.updateOptionsInterface();
10133 }
10134 return this;
10135 };
10136
10137 /**
10138 * Clean up incoming value.
10139 *
10140 * @param {string[]} value Original value
10141 * @return {string[]} Cleaned up value
10142 */
10143 OO.ui.CheckboxMultiselectInputWidget.prototype.cleanUpValue = function ( value ) {
10144 var i, singleValue,
10145 cleanValue = [];
10146 if ( !Array.isArray( value ) ) {
10147 return cleanValue;
10148 }
10149 for ( i = 0; i < value.length; i++ ) {
10150 singleValue =
10151 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.cleanUpValue.call( this, value[ i ] );
10152 // Remove options that we don't have here
10153 if ( !this.checkboxMultiselectWidget.findItemFromData( singleValue ) ) {
10154 continue;
10155 }
10156 cleanValue.push( singleValue );
10157 }
10158 return cleanValue;
10159 };
10160
10161 /**
10162 * @inheritdoc
10163 */
10164 OO.ui.CheckboxMultiselectInputWidget.prototype.setDisabled = function ( state ) {
10165 this.checkboxMultiselectWidget.setDisabled( state );
10166 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.setDisabled.call( this, state );
10167 return this;
10168 };
10169
10170 /**
10171 * Set the options available for this input.
10172 *
10173 * @param {Object[]} options Array of menu options in the format `{ data: …, label: …, disabled: … }`
10174 * @chainable
10175 * @return {OO.ui.Widget} The widget, for chaining
10176 */
10177 OO.ui.CheckboxMultiselectInputWidget.prototype.setOptions = function ( options ) {
10178 var value = this.getValue();
10179
10180 this.setOptionsData( options );
10181
10182 // Re-set the value to update the visible interface (CheckboxMultiselectWidget).
10183 // This will also get rid of any stale options that we just removed.
10184 this.setValue( value );
10185
10186 return this;
10187 };
10188
10189 /**
10190 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
10191 *
10192 * This method may be called before the parent constructor, so various properties may not be
10193 * intialized yet.
10194 *
10195 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10196 * @private
10197 */
10198 OO.ui.CheckboxMultiselectInputWidget.prototype.setOptionsData = function ( options ) {
10199 var widget = this;
10200
10201 this.optionsDirty = true;
10202
10203 this.checkboxMultiselectWidget
10204 .clearItems()
10205 .addItems( options.map( function ( opt ) {
10206 var optValue, item, optDisabled;
10207 optValue =
10208 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.cleanUpValue.call( widget, opt.data );
10209 optDisabled = opt.disabled !== undefined ? opt.disabled : false;
10210 item = new OO.ui.CheckboxMultioptionWidget( {
10211 data: optValue,
10212 label: opt.label !== undefined ? opt.label : optValue,
10213 disabled: optDisabled
10214 } );
10215 // Set the 'name' and 'value' for form submission
10216 item.checkbox.$input.attr( 'name', widget.inputName );
10217 item.checkbox.setValue( optValue );
10218 return item;
10219 } ) );
10220 };
10221
10222 /**
10223 * Update the user-visible interface to match the internal list of options and value.
10224 *
10225 * This method must only be called after the parent constructor.
10226 *
10227 * @private
10228 */
10229 OO.ui.CheckboxMultiselectInputWidget.prototype.updateOptionsInterface = function () {
10230 var defaultValue = this.defaultValue;
10231
10232 this.checkboxMultiselectWidget.getItems().forEach( function ( item ) {
10233 // Remember original selection state. This property can be later used to check whether
10234 // the selection state of the input has been changed since it was created.
10235 var isDefault = defaultValue.indexOf( item.getData() ) !== -1;
10236 item.checkbox.defaultSelected = isDefault;
10237 item.checkbox.$input[ 0 ].defaultChecked = isDefault;
10238 } );
10239
10240 this.optionsDirty = false;
10241 };
10242
10243 /**
10244 * @inheritdoc
10245 */
10246 OO.ui.CheckboxMultiselectInputWidget.prototype.focus = function () {
10247 this.checkboxMultiselectWidget.focus();
10248 return this;
10249 };
10250
10251 /**
10252 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
10253 * size of the field as well as its presentation. In addition, these widgets can be configured
10254 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
10255 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
10256 * which modifies incoming values rather than validating them.
10257 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
10258 *
10259 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
10260 *
10261 * @example
10262 * // Example of a text input widget
10263 * var textInput = new OO.ui.TextInputWidget( {
10264 * value: 'Text input'
10265 * } )
10266 * $( 'body' ).append( textInput.$element );
10267 *
10268 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
10269 *
10270 * @class
10271 * @extends OO.ui.InputWidget
10272 * @mixins OO.ui.mixin.IconElement
10273 * @mixins OO.ui.mixin.IndicatorElement
10274 * @mixins OO.ui.mixin.PendingElement
10275 * @mixins OO.ui.mixin.LabelElement
10276 *
10277 * @constructor
10278 * @param {Object} [config] Configuration options
10279 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password'
10280 * 'email', 'url' or 'number'.
10281 * @cfg {string} [placeholder] Placeholder text
10282 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
10283 * instruct the browser to focus this widget.
10284 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
10285 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
10286 *
10287 * For unfortunate historical reasons, this counts the number of UTF-16 code units rather than
10288 * Unicode codepoints, which means that codepoints outside the Basic Multilingual Plane (e.g.
10289 * many emojis) count as 2 characters each.
10290 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
10291 * the value or placeholder text: `'before'` or `'after'`
10292 * @cfg {boolean} [required=false] Mark the field as required with `true`. Implies `indicator: 'required'`.
10293 * Note that `false` & setting `indicator: 'required' will result in no indicator shown.
10294 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
10295 * @cfg {boolean} [spellcheck] Should the browser support spellcheck for this field (`undefined` means
10296 * leaving it up to the browser).
10297 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
10298 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
10299 * (the value must contain only numbers); when RegExp, a regular expression that must match the
10300 * value for it to be considered valid; when Function, a function receiving the value as parameter
10301 * that must return true, or promise resolving to true, for it to be considered valid.
10302 */
10303 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
10304 // Configuration initialization
10305 config = $.extend( {
10306 type: 'text',
10307 labelPosition: 'after'
10308 }, config );
10309
10310 // Parent constructor
10311 OO.ui.TextInputWidget.parent.call( this, config );
10312
10313 // Mixin constructors
10314 OO.ui.mixin.IconElement.call( this, config );
10315 OO.ui.mixin.IndicatorElement.call( this, config );
10316 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$input } ) );
10317 OO.ui.mixin.LabelElement.call( this, config );
10318
10319 // Properties
10320 this.type = this.getSaneType( config );
10321 this.readOnly = false;
10322 this.required = false;
10323 this.validate = null;
10324 this.styleHeight = null;
10325 this.scrollWidth = null;
10326
10327 this.setValidation( config.validate );
10328 this.setLabelPosition( config.labelPosition );
10329
10330 // Events
10331 this.$input.on( {
10332 keypress: this.onKeyPress.bind( this ),
10333 blur: this.onBlur.bind( this ),
10334 focus: this.onFocus.bind( this )
10335 } );
10336 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
10337 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
10338 this.on( 'labelChange', this.updatePosition.bind( this ) );
10339 this.on( 'change', OO.ui.debounce( this.onDebouncedChange.bind( this ), 250 ) );
10340
10341 // Initialization
10342 this.$element
10343 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type )
10344 .append( this.$icon, this.$indicator );
10345 this.setReadOnly( !!config.readOnly );
10346 this.setRequired( !!config.required );
10347 if ( config.placeholder !== undefined ) {
10348 this.$input.attr( 'placeholder', config.placeholder );
10349 }
10350 if ( config.maxLength !== undefined ) {
10351 this.$input.attr( 'maxlength', config.maxLength );
10352 }
10353 if ( config.autofocus ) {
10354 this.$input.attr( 'autofocus', 'autofocus' );
10355 }
10356 if ( config.autocomplete === false ) {
10357 this.$input.attr( 'autocomplete', 'off' );
10358 // Turning off autocompletion also disables "form caching" when the user navigates to a
10359 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
10360 $( window ).on( {
10361 beforeunload: function () {
10362 this.$input.removeAttr( 'autocomplete' );
10363 }.bind( this ),
10364 pageshow: function () {
10365 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
10366 // whole page... it shouldn't hurt, though.
10367 this.$input.attr( 'autocomplete', 'off' );
10368 }.bind( this )
10369 } );
10370 }
10371 if ( config.spellcheck !== undefined ) {
10372 this.$input.attr( 'spellcheck', config.spellcheck ? 'true' : 'false' );
10373 }
10374 if ( this.label ) {
10375 this.isWaitingToBeAttached = true;
10376 this.installParentChangeDetector();
10377 }
10378 };
10379
10380 /* Setup */
10381
10382 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
10383 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IconElement );
10384 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IndicatorElement );
10385 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.PendingElement );
10386 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.LabelElement );
10387
10388 /* Static Properties */
10389
10390 OO.ui.TextInputWidget.static.validationPatterns = {
10391 'non-empty': /.+/,
10392 integer: /^\d+$/
10393 };
10394
10395 /* Events */
10396
10397 /**
10398 * An `enter` event is emitted when the user presses 'enter' inside the text box.
10399 *
10400 * @event enter
10401 */
10402
10403 /* Methods */
10404
10405 /**
10406 * Handle icon mouse down events.
10407 *
10408 * @private
10409 * @param {jQuery.Event} e Mouse down event
10410 * @return {undefined/boolean} False to prevent default if event is handled
10411 */
10412 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
10413 if ( e.which === OO.ui.MouseButtons.LEFT ) {
10414 this.focus();
10415 return false;
10416 }
10417 };
10418
10419 /**
10420 * Handle indicator mouse down events.
10421 *
10422 * @private
10423 * @param {jQuery.Event} e Mouse down event
10424 * @return {undefined/boolean} False to prevent default if event is handled
10425 */
10426 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
10427 if ( e.which === OO.ui.MouseButtons.LEFT ) {
10428 this.focus();
10429 return false;
10430 }
10431 };
10432
10433 /**
10434 * Handle key press events.
10435 *
10436 * @private
10437 * @param {jQuery.Event} e Key press event
10438 * @fires enter If enter key is pressed
10439 */
10440 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
10441 if ( e.which === OO.ui.Keys.ENTER ) {
10442 this.emit( 'enter', e );
10443 }
10444 };
10445
10446 /**
10447 * Handle blur events.
10448 *
10449 * @private
10450 * @param {jQuery.Event} e Blur event
10451 */
10452 OO.ui.TextInputWidget.prototype.onBlur = function () {
10453 this.setValidityFlag();
10454 };
10455
10456 /**
10457 * Handle focus events.
10458 *
10459 * @private
10460 * @param {jQuery.Event} e Focus event
10461 */
10462 OO.ui.TextInputWidget.prototype.onFocus = function () {
10463 if ( this.isWaitingToBeAttached ) {
10464 // If we've received focus, then we must be attached to the document, and if
10465 // isWaitingToBeAttached is still true, that means the handler never fired. Fire it now.
10466 this.onElementAttach();
10467 }
10468 this.setValidityFlag( true );
10469 };
10470
10471 /**
10472 * Handle element attach events.
10473 *
10474 * @private
10475 * @param {jQuery.Event} e Element attach event
10476 */
10477 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
10478 this.isWaitingToBeAttached = false;
10479 // Any previously calculated size is now probably invalid if we reattached elsewhere
10480 this.valCache = null;
10481 this.positionLabel();
10482 };
10483
10484 /**
10485 * Handle debounced change events.
10486 *
10487 * @param {string} value
10488 * @private
10489 */
10490 OO.ui.TextInputWidget.prototype.onDebouncedChange = function () {
10491 this.setValidityFlag();
10492 };
10493
10494 /**
10495 * Check if the input is {@link #readOnly read-only}.
10496 *
10497 * @return {boolean}
10498 */
10499 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
10500 return this.readOnly;
10501 };
10502
10503 /**
10504 * Set the {@link #readOnly read-only} state of the input.
10505 *
10506 * @param {boolean} state Make input read-only
10507 * @chainable
10508 * @return {OO.ui.Widget} The widget, for chaining
10509 */
10510 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
10511 this.readOnly = !!state;
10512 this.$input.prop( 'readOnly', this.readOnly );
10513 return this;
10514 };
10515
10516 /**
10517 * Check if the input is {@link #required required}.
10518 *
10519 * @return {boolean}
10520 */
10521 OO.ui.TextInputWidget.prototype.isRequired = function () {
10522 return this.required;
10523 };
10524
10525 /**
10526 * Set the {@link #required required} state of the input.
10527 *
10528 * @param {boolean} state Make input required
10529 * @chainable
10530 * @return {OO.ui.Widget} The widget, for chaining
10531 */
10532 OO.ui.TextInputWidget.prototype.setRequired = function ( state ) {
10533 this.required = !!state;
10534 if ( this.required ) {
10535 this.$input
10536 .prop( 'required', true )
10537 .attr( 'aria-required', 'true' );
10538 if ( this.getIndicator() === null ) {
10539 this.setIndicator( 'required' );
10540 }
10541 } else {
10542 this.$input
10543 .prop( 'required', false )
10544 .removeAttr( 'aria-required' );
10545 if ( this.getIndicator() === 'required' ) {
10546 this.setIndicator( null );
10547 }
10548 }
10549 return this;
10550 };
10551
10552 /**
10553 * Support function for making #onElementAttach work across browsers.
10554 *
10555 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
10556 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
10557 *
10558 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
10559 * first time that the element gets attached to the documented.
10560 */
10561 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
10562 var mutationObserver, onRemove, topmostNode, fakeParentNode,
10563 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
10564 widget = this;
10565
10566 if ( MutationObserver ) {
10567 // The new way. If only it wasn't so ugly.
10568
10569 if ( this.isElementAttached() ) {
10570 // Widget is attached already, do nothing. This breaks the functionality of this function when
10571 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
10572 // would require observation of the whole document, which would hurt performance of other,
10573 // more important code.
10574 return;
10575 }
10576
10577 // Find topmost node in the tree
10578 topmostNode = this.$element[ 0 ];
10579 while ( topmostNode.parentNode ) {
10580 topmostNode = topmostNode.parentNode;
10581 }
10582
10583 // We have no way to detect the $element being attached somewhere without observing the entire
10584 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
10585 // parent node of $element, and instead detect when $element is removed from it (and thus
10586 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
10587 // doesn't get attached, we end up back here and create the parent.
10588
10589 mutationObserver = new MutationObserver( function ( mutations ) {
10590 var i, j, removedNodes;
10591 for ( i = 0; i < mutations.length; i++ ) {
10592 removedNodes = mutations[ i ].removedNodes;
10593 for ( j = 0; j < removedNodes.length; j++ ) {
10594 if ( removedNodes[ j ] === topmostNode ) {
10595 setTimeout( onRemove, 0 );
10596 return;
10597 }
10598 }
10599 }
10600 } );
10601
10602 onRemove = function () {
10603 // If the node was attached somewhere else, report it
10604 if ( widget.isElementAttached() ) {
10605 widget.onElementAttach();
10606 }
10607 mutationObserver.disconnect();
10608 widget.installParentChangeDetector();
10609 };
10610
10611 // Create a fake parent and observe it
10612 fakeParentNode = $( '<div>' ).append( topmostNode )[ 0 ];
10613 mutationObserver.observe( fakeParentNode, { childList: true } );
10614 } else {
10615 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
10616 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
10617 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
10618 }
10619 };
10620
10621 /**
10622 * @inheritdoc
10623 * @protected
10624 */
10625 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
10626 if ( this.getSaneType( config ) === 'number' ) {
10627 return $( '<input>' )
10628 .attr( 'step', 'any' )
10629 .attr( 'type', 'number' );
10630 } else {
10631 return $( '<input>' ).attr( 'type', this.getSaneType( config ) );
10632 }
10633 };
10634
10635 /**
10636 * Get sanitized value for 'type' for given config.
10637 *
10638 * @param {Object} config Configuration options
10639 * @return {string|null}
10640 * @protected
10641 */
10642 OO.ui.TextInputWidget.prototype.getSaneType = function ( config ) {
10643 var allowedTypes = [
10644 'text',
10645 'password',
10646 'email',
10647 'url',
10648 'number'
10649 ];
10650 return allowedTypes.indexOf( config.type ) !== -1 ? config.type : 'text';
10651 };
10652
10653 /**
10654 * Focus the input and select a specified range within the text.
10655 *
10656 * @param {number} from Select from offset
10657 * @param {number} [to] Select to offset, defaults to from
10658 * @chainable
10659 * @return {OO.ui.Widget} The widget, for chaining
10660 */
10661 OO.ui.TextInputWidget.prototype.selectRange = function ( from, to ) {
10662 var isBackwards, start, end,
10663 input = this.$input[ 0 ];
10664
10665 to = to || from;
10666
10667 isBackwards = to < from;
10668 start = isBackwards ? to : from;
10669 end = isBackwards ? from : to;
10670
10671 this.focus();
10672
10673 try {
10674 input.setSelectionRange( start, end, isBackwards ? 'backward' : 'forward' );
10675 } catch ( e ) {
10676 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
10677 // Rather than expensively check if the input is attached every time, just check
10678 // if it was the cause of an error being thrown. If not, rethrow the error.
10679 if ( this.getElementDocument().body.contains( input ) ) {
10680 throw e;
10681 }
10682 }
10683 return this;
10684 };
10685
10686 /**
10687 * Get an object describing the current selection range in a directional manner
10688 *
10689 * @return {Object} Object containing 'from' and 'to' offsets
10690 */
10691 OO.ui.TextInputWidget.prototype.getRange = function () {
10692 var input = this.$input[ 0 ],
10693 start = input.selectionStart,
10694 end = input.selectionEnd,
10695 isBackwards = input.selectionDirection === 'backward';
10696
10697 return {
10698 from: isBackwards ? end : start,
10699 to: isBackwards ? start : end
10700 };
10701 };
10702
10703 /**
10704 * Get the length of the text input value.
10705 *
10706 * This could differ from the length of #getValue if the
10707 * value gets filtered
10708 *
10709 * @return {number} Input length
10710 */
10711 OO.ui.TextInputWidget.prototype.getInputLength = function () {
10712 return this.$input[ 0 ].value.length;
10713 };
10714
10715 /**
10716 * Focus the input and select the entire text.
10717 *
10718 * @chainable
10719 * @return {OO.ui.Widget} The widget, for chaining
10720 */
10721 OO.ui.TextInputWidget.prototype.select = function () {
10722 return this.selectRange( 0, this.getInputLength() );
10723 };
10724
10725 /**
10726 * Focus the input and move the cursor to the start.
10727 *
10728 * @chainable
10729 * @return {OO.ui.Widget} The widget, for chaining
10730 */
10731 OO.ui.TextInputWidget.prototype.moveCursorToStart = function () {
10732 return this.selectRange( 0 );
10733 };
10734
10735 /**
10736 * Focus the input and move the cursor to the end.
10737 *
10738 * @chainable
10739 * @return {OO.ui.Widget} The widget, for chaining
10740 */
10741 OO.ui.TextInputWidget.prototype.moveCursorToEnd = function () {
10742 return this.selectRange( this.getInputLength() );
10743 };
10744
10745 /**
10746 * Insert new content into the input.
10747 *
10748 * @param {string} content Content to be inserted
10749 * @chainable
10750 * @return {OO.ui.Widget} The widget, for chaining
10751 */
10752 OO.ui.TextInputWidget.prototype.insertContent = function ( content ) {
10753 var start, end,
10754 range = this.getRange(),
10755 value = this.getValue();
10756
10757 start = Math.min( range.from, range.to );
10758 end = Math.max( range.from, range.to );
10759
10760 this.setValue( value.slice( 0, start ) + content + value.slice( end ) );
10761 this.selectRange( start + content.length );
10762 return this;
10763 };
10764
10765 /**
10766 * Insert new content either side of a selection.
10767 *
10768 * @param {string} pre Content to be inserted before the selection
10769 * @param {string} post Content to be inserted after the selection
10770 * @chainable
10771 * @return {OO.ui.Widget} The widget, for chaining
10772 */
10773 OO.ui.TextInputWidget.prototype.encapsulateContent = function ( pre, post ) {
10774 var start, end,
10775 range = this.getRange(),
10776 offset = pre.length;
10777
10778 start = Math.min( range.from, range.to );
10779 end = Math.max( range.from, range.to );
10780
10781 this.selectRange( start ).insertContent( pre );
10782 this.selectRange( offset + end ).insertContent( post );
10783
10784 this.selectRange( offset + start, offset + end );
10785 return this;
10786 };
10787
10788 /**
10789 * Set the validation pattern.
10790 *
10791 * The validation pattern is either a regular expression, a function, or the symbolic name of a
10792 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
10793 * value must contain only numbers).
10794 *
10795 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
10796 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
10797 */
10798 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
10799 if ( validate instanceof RegExp || validate instanceof Function ) {
10800 this.validate = validate;
10801 } else {
10802 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
10803 }
10804 };
10805
10806 /**
10807 * Sets the 'invalid' flag appropriately.
10808 *
10809 * @param {boolean} [isValid] Optionally override validation result
10810 */
10811 OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) {
10812 var widget = this,
10813 setFlag = function ( valid ) {
10814 if ( !valid ) {
10815 widget.$input.attr( 'aria-invalid', 'true' );
10816 } else {
10817 widget.$input.removeAttr( 'aria-invalid' );
10818 }
10819 widget.setFlags( { invalid: !valid } );
10820 };
10821
10822 if ( isValid !== undefined ) {
10823 setFlag( isValid );
10824 } else {
10825 this.getValidity().then( function () {
10826 setFlag( true );
10827 }, function () {
10828 setFlag( false );
10829 } );
10830 }
10831 };
10832
10833 /**
10834 * Get the validity of current value.
10835 *
10836 * This method returns a promise that resolves if the value is valid and rejects if
10837 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
10838 *
10839 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
10840 */
10841 OO.ui.TextInputWidget.prototype.getValidity = function () {
10842 var result;
10843
10844 function rejectOrResolve( valid ) {
10845 if ( valid ) {
10846 return $.Deferred().resolve().promise();
10847 } else {
10848 return $.Deferred().reject().promise();
10849 }
10850 }
10851
10852 // Check browser validity and reject if it is invalid
10853 if (
10854 this.$input[ 0 ].checkValidity !== undefined &&
10855 this.$input[ 0 ].checkValidity() === false
10856 ) {
10857 return rejectOrResolve( false );
10858 }
10859
10860 // Run our checks if the browser thinks the field is valid
10861 if ( this.validate instanceof Function ) {
10862 result = this.validate( this.getValue() );
10863 if ( result && $.isFunction( result.promise ) ) {
10864 return result.promise().then( function ( valid ) {
10865 return rejectOrResolve( valid );
10866 } );
10867 } else {
10868 return rejectOrResolve( result );
10869 }
10870 } else {
10871 return rejectOrResolve( this.getValue().match( this.validate ) );
10872 }
10873 };
10874
10875 /**
10876 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
10877 *
10878 * @param {string} labelPosition Label position, 'before' or 'after'
10879 * @chainable
10880 * @return {OO.ui.Widget} The widget, for chaining
10881 */
10882 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
10883 this.labelPosition = labelPosition;
10884 if ( this.label ) {
10885 // If there is no label and we only change the position, #updatePosition is a no-op,
10886 // but it takes really a lot of work to do nothing.
10887 this.updatePosition();
10888 }
10889 return this;
10890 };
10891
10892 /**
10893 * Update the position of the inline label.
10894 *
10895 * This method is called by #setLabelPosition, and can also be called on its own if
10896 * something causes the label to be mispositioned.
10897 *
10898 * @chainable
10899 * @return {OO.ui.Widget} The widget, for chaining
10900 */
10901 OO.ui.TextInputWidget.prototype.updatePosition = function () {
10902 var after = this.labelPosition === 'after';
10903
10904 this.$element
10905 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
10906 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
10907
10908 this.valCache = null;
10909 this.scrollWidth = null;
10910 this.positionLabel();
10911
10912 return this;
10913 };
10914
10915 /**
10916 * Position the label by setting the correct padding on the input.
10917 *
10918 * @private
10919 * @chainable
10920 * @return {OO.ui.Widget} The widget, for chaining
10921 */
10922 OO.ui.TextInputWidget.prototype.positionLabel = function () {
10923 var after, rtl, property, newCss;
10924
10925 if ( this.isWaitingToBeAttached ) {
10926 // #onElementAttach will be called soon, which calls this method
10927 return this;
10928 }
10929
10930 newCss = {
10931 'padding-right': '',
10932 'padding-left': ''
10933 };
10934
10935 if ( this.label ) {
10936 this.$element.append( this.$label );
10937 } else {
10938 this.$label.detach();
10939 // Clear old values if present
10940 this.$input.css( newCss );
10941 return;
10942 }
10943
10944 after = this.labelPosition === 'after';
10945 rtl = this.$element.css( 'direction' ) === 'rtl';
10946 property = after === rtl ? 'padding-left' : 'padding-right';
10947
10948 newCss[ property ] = this.$label.outerWidth( true ) + ( after ? this.scrollWidth : 0 );
10949 // We have to clear the padding on the other side, in case the element direction changed
10950 this.$input.css( newCss );
10951
10952 return this;
10953 };
10954
10955 /**
10956 * @class
10957 * @extends OO.ui.TextInputWidget
10958 *
10959 * @constructor
10960 * @param {Object} [config] Configuration options
10961 */
10962 OO.ui.SearchInputWidget = function OoUiSearchInputWidget( config ) {
10963 config = $.extend( {
10964 icon: 'search'
10965 }, config );
10966
10967 // Parent constructor
10968 OO.ui.SearchInputWidget.parent.call( this, config );
10969
10970 // Events
10971 this.connect( this, {
10972 change: 'onChange'
10973 } );
10974
10975 // Initialization
10976 this.updateSearchIndicator();
10977 this.connect( this, {
10978 disable: 'onDisable'
10979 } );
10980 };
10981
10982 /* Setup */
10983
10984 OO.inheritClass( OO.ui.SearchInputWidget, OO.ui.TextInputWidget );
10985
10986 /* Methods */
10987
10988 /**
10989 * @inheritdoc
10990 * @protected
10991 */
10992 OO.ui.SearchInputWidget.prototype.getSaneType = function () {
10993 return 'search';
10994 };
10995
10996 /**
10997 * @inheritdoc
10998 */
10999 OO.ui.SearchInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
11000 if ( e.which === OO.ui.MouseButtons.LEFT ) {
11001 // Clear the text field
11002 this.setValue( '' );
11003 this.focus();
11004 return false;
11005 }
11006 };
11007
11008 /**
11009 * Update the 'clear' indicator displayed on type: 'search' text
11010 * fields, hiding it when the field is already empty or when it's not
11011 * editable.
11012 */
11013 OO.ui.SearchInputWidget.prototype.updateSearchIndicator = function () {
11014 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
11015 this.setIndicator( null );
11016 } else {
11017 this.setIndicator( 'clear' );
11018 }
11019 };
11020
11021 /**
11022 * Handle change events.
11023 *
11024 * @private
11025 */
11026 OO.ui.SearchInputWidget.prototype.onChange = function () {
11027 this.updateSearchIndicator();
11028 };
11029
11030 /**
11031 * Handle disable events.
11032 *
11033 * @param {boolean} disabled Element is disabled
11034 * @private
11035 */
11036 OO.ui.SearchInputWidget.prototype.onDisable = function () {
11037 this.updateSearchIndicator();
11038 };
11039
11040 /**
11041 * @inheritdoc
11042 */
11043 OO.ui.SearchInputWidget.prototype.setReadOnly = function ( state ) {
11044 OO.ui.SearchInputWidget.parent.prototype.setReadOnly.call( this, state );
11045 this.updateSearchIndicator();
11046 return this;
11047 };
11048
11049 /**
11050 * @class
11051 * @extends OO.ui.TextInputWidget
11052 *
11053 * @constructor
11054 * @param {Object} [config] Configuration options
11055 * @cfg {number} [rows] Number of visible lines in textarea. If used with `autosize`,
11056 * specifies minimum number of rows to display.
11057 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
11058 * Use the #maxRows config to specify a maximum number of displayed rows.
11059 * @cfg {number} [maxRows] Maximum number of rows to display when #autosize is set to true.
11060 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
11061 */
11062 OO.ui.MultilineTextInputWidget = function OoUiMultilineTextInputWidget( config ) {
11063 config = $.extend( {
11064 type: 'text'
11065 }, config );
11066 // Parent constructor
11067 OO.ui.MultilineTextInputWidget.parent.call( this, config );
11068
11069 // Properties
11070 this.autosize = !!config.autosize;
11071 this.minRows = config.rows !== undefined ? config.rows : '';
11072 this.maxRows = config.maxRows || Math.max( 2 * ( this.minRows || 0 ), 10 );
11073
11074 // Clone for resizing
11075 if ( this.autosize ) {
11076 this.$clone = this.$input
11077 .clone()
11078 .removeAttr( 'id' )
11079 .removeAttr( 'name' )
11080 .insertAfter( this.$input )
11081 .attr( 'aria-hidden', 'true' )
11082 .addClass( 'oo-ui-element-hidden' );
11083 }
11084
11085 // Events
11086 this.connect( this, {
11087 change: 'onChange'
11088 } );
11089
11090 // Initialization
11091 if ( config.rows ) {
11092 this.$input.attr( 'rows', config.rows );
11093 }
11094 if ( this.autosize ) {
11095 this.$input.addClass( 'oo-ui-textInputWidget-autosized' );
11096 this.isWaitingToBeAttached = true;
11097 this.installParentChangeDetector();
11098 }
11099 };
11100
11101 /* Setup */
11102
11103 OO.inheritClass( OO.ui.MultilineTextInputWidget, OO.ui.TextInputWidget );
11104
11105 /* Static Methods */
11106
11107 /**
11108 * @inheritdoc
11109 */
11110 OO.ui.MultilineTextInputWidget.static.gatherPreInfuseState = function ( node, config ) {
11111 var state = OO.ui.MultilineTextInputWidget.parent.static.gatherPreInfuseState( node, config );
11112 state.scrollTop = config.$input.scrollTop();
11113 return state;
11114 };
11115
11116 /* Methods */
11117
11118 /**
11119 * @inheritdoc
11120 */
11121 OO.ui.MultilineTextInputWidget.prototype.onElementAttach = function () {
11122 OO.ui.MultilineTextInputWidget.parent.prototype.onElementAttach.call( this );
11123 this.adjustSize();
11124 };
11125
11126 /**
11127 * Handle change events.
11128 *
11129 * @private
11130 */
11131 OO.ui.MultilineTextInputWidget.prototype.onChange = function () {
11132 this.adjustSize();
11133 };
11134
11135 /**
11136 * @inheritdoc
11137 */
11138 OO.ui.MultilineTextInputWidget.prototype.updatePosition = function () {
11139 OO.ui.MultilineTextInputWidget.parent.prototype.updatePosition.call( this );
11140 this.adjustSize();
11141 };
11142
11143 /**
11144 * @inheritdoc
11145 *
11146 * Modify to emit 'enter' on Ctrl/Meta+Enter, instead of plain Enter
11147 */
11148 OO.ui.MultilineTextInputWidget.prototype.onKeyPress = function ( e ) {
11149 if (
11150 ( e.which === OO.ui.Keys.ENTER && ( e.ctrlKey || e.metaKey ) ) ||
11151 // Some platforms emit keycode 10 for ctrl+enter in a textarea
11152 e.which === 10
11153 ) {
11154 this.emit( 'enter', e );
11155 }
11156 };
11157
11158 /**
11159 * Automatically adjust the size of the text input.
11160 *
11161 * This only affects multiline inputs that are {@link #autosize autosized}.
11162 *
11163 * @chainable
11164 * @return {OO.ui.Widget} The widget, for chaining
11165 * @fires resize
11166 */
11167 OO.ui.MultilineTextInputWidget.prototype.adjustSize = function () {
11168 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError,
11169 idealHeight, newHeight, scrollWidth, property;
11170
11171 if ( this.$input.val() !== this.valCache ) {
11172 if ( this.autosize ) {
11173 this.$clone
11174 .val( this.$input.val() )
11175 .attr( 'rows', this.minRows )
11176 // Set inline height property to 0 to measure scroll height
11177 .css( 'height', 0 );
11178
11179 this.$clone.removeClass( 'oo-ui-element-hidden' );
11180
11181 this.valCache = this.$input.val();
11182
11183 scrollHeight = this.$clone[ 0 ].scrollHeight;
11184
11185 // Remove inline height property to measure natural heights
11186 this.$clone.css( 'height', '' );
11187 innerHeight = this.$clone.innerHeight();
11188 outerHeight = this.$clone.outerHeight();
11189
11190 // Measure max rows height
11191 this.$clone
11192 .attr( 'rows', this.maxRows )
11193 .css( 'height', 'auto' )
11194 .val( '' );
11195 maxInnerHeight = this.$clone.innerHeight();
11196
11197 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
11198 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
11199 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
11200 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
11201
11202 this.$clone.addClass( 'oo-ui-element-hidden' );
11203
11204 // Only apply inline height when expansion beyond natural height is needed
11205 // Use the difference between the inner and outer height as a buffer
11206 newHeight = idealHeight > innerHeight ? idealHeight + ( outerHeight - innerHeight ) : '';
11207 if ( newHeight !== this.styleHeight ) {
11208 this.$input.css( 'height', newHeight );
11209 this.styleHeight = newHeight;
11210 this.emit( 'resize' );
11211 }
11212 }
11213 scrollWidth = this.$input[ 0 ].offsetWidth - this.$input[ 0 ].clientWidth;
11214 if ( scrollWidth !== this.scrollWidth ) {
11215 property = this.$element.css( 'direction' ) === 'rtl' ? 'left' : 'right';
11216 // Reset
11217 this.$label.css( { right: '', left: '' } );
11218 this.$indicator.css( { right: '', left: '' } );
11219
11220 if ( scrollWidth ) {
11221 this.$indicator.css( property, scrollWidth );
11222 if ( this.labelPosition === 'after' ) {
11223 this.$label.css( property, scrollWidth );
11224 }
11225 }
11226
11227 this.scrollWidth = scrollWidth;
11228 this.positionLabel();
11229 }
11230 }
11231 return this;
11232 };
11233
11234 /**
11235 * @inheritdoc
11236 * @protected
11237 */
11238 OO.ui.MultilineTextInputWidget.prototype.getInputElement = function () {
11239 return $( '<textarea>' );
11240 };
11241
11242 /**
11243 * Check if the input automatically adjusts its size.
11244 *
11245 * @return {boolean}
11246 */
11247 OO.ui.MultilineTextInputWidget.prototype.isAutosizing = function () {
11248 return !!this.autosize;
11249 };
11250
11251 /**
11252 * @inheritdoc
11253 */
11254 OO.ui.MultilineTextInputWidget.prototype.restorePreInfuseState = function ( state ) {
11255 OO.ui.MultilineTextInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
11256 if ( state.scrollTop !== undefined ) {
11257 this.$input.scrollTop( state.scrollTop );
11258 }
11259 };
11260
11261 /**
11262 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
11263 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
11264 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
11265 *
11266 * - by typing a value in the text input field. If the value exactly matches the value of a menu
11267 * option, that option will appear to be selected.
11268 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
11269 * input field.
11270 *
11271 * After the user chooses an option, its `data` will be used as a new value for the widget.
11272 * A `label` also can be specified for each option: if given, it will be shown instead of the
11273 * `data` in the dropdown menu.
11274 *
11275 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
11276 *
11277 * For more information about menus and options, please see the [OOUI documentation on MediaWiki][1].
11278 *
11279 * @example
11280 * // Example: A ComboBoxInputWidget.
11281 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11282 * value: 'Option 1',
11283 * options: [
11284 * { data: 'Option 1' },
11285 * { data: 'Option 2' },
11286 * { data: 'Option 3' }
11287 * ]
11288 * } );
11289 * $( 'body' ).append( comboBox.$element );
11290 *
11291 * @example
11292 * // Example: A ComboBoxInputWidget with additional option labels.
11293 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11294 * value: 'Option 1',
11295 * options: [
11296 * {
11297 * data: 'Option 1',
11298 * label: 'Option One'
11299 * },
11300 * {
11301 * data: 'Option 2',
11302 * label: 'Option Two'
11303 * },
11304 * {
11305 * data: 'Option 3',
11306 * label: 'Option Three'
11307 * }
11308 * ]
11309 * } );
11310 * $( 'body' ).append( comboBox.$element );
11311 *
11312 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
11313 *
11314 * @class
11315 * @extends OO.ui.TextInputWidget
11316 *
11317 * @constructor
11318 * @param {Object} [config] Configuration options
11319 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
11320 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
11321 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
11322 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
11323 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
11324 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11325 */
11326 OO.ui.ComboBoxInputWidget = function OoUiComboBoxInputWidget( config ) {
11327 // Configuration initialization
11328 config = $.extend( {
11329 autocomplete: false
11330 }, config );
11331
11332 // ComboBoxInputWidget shouldn't support `multiline`
11333 config.multiline = false;
11334
11335 // See InputWidget#reusePreInfuseDOM about `config.$input`
11336 if ( config.$input ) {
11337 config.$input.removeAttr( 'list' );
11338 }
11339
11340 // Parent constructor
11341 OO.ui.ComboBoxInputWidget.parent.call( this, config );
11342
11343 // Properties
11344 this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
11345 this.dropdownButton = new OO.ui.ButtonWidget( {
11346 classes: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ],
11347 indicator: 'down',
11348 disabled: this.disabled
11349 } );
11350 this.menu = new OO.ui.MenuSelectWidget( $.extend(
11351 {
11352 widget: this,
11353 input: this,
11354 $floatableContainer: this.$element,
11355 disabled: this.isDisabled()
11356 },
11357 config.menu
11358 ) );
11359
11360 // Events
11361 this.connect( this, {
11362 change: 'onInputChange',
11363 enter: 'onInputEnter'
11364 } );
11365 this.dropdownButton.connect( this, {
11366 click: 'onDropdownButtonClick'
11367 } );
11368 this.menu.connect( this, {
11369 choose: 'onMenuChoose',
11370 add: 'onMenuItemsChange',
11371 remove: 'onMenuItemsChange',
11372 toggle: 'onMenuToggle'
11373 } );
11374
11375 // Initialization
11376 this.$input.attr( {
11377 role: 'combobox',
11378 'aria-owns': this.menu.getElementId(),
11379 'aria-autocomplete': 'list'
11380 } );
11381 // Do not override options set via config.menu.items
11382 if ( config.options !== undefined ) {
11383 this.setOptions( config.options );
11384 }
11385 this.$field = $( '<div>' )
11386 .addClass( 'oo-ui-comboBoxInputWidget-field' )
11387 .append( this.$input, this.dropdownButton.$element );
11388 this.$element
11389 .addClass( 'oo-ui-comboBoxInputWidget' )
11390 .append( this.$field );
11391 this.$overlay.append( this.menu.$element );
11392 this.onMenuItemsChange();
11393 };
11394
11395 /* Setup */
11396
11397 OO.inheritClass( OO.ui.ComboBoxInputWidget, OO.ui.TextInputWidget );
11398
11399 /* Methods */
11400
11401 /**
11402 * Get the combobox's menu.
11403 *
11404 * @return {OO.ui.MenuSelectWidget} Menu widget
11405 */
11406 OO.ui.ComboBoxInputWidget.prototype.getMenu = function () {
11407 return this.menu;
11408 };
11409
11410 /**
11411 * Get the combobox's text input widget.
11412 *
11413 * @return {OO.ui.TextInputWidget} Text input widget
11414 */
11415 OO.ui.ComboBoxInputWidget.prototype.getInput = function () {
11416 return this;
11417 };
11418
11419 /**
11420 * Handle input change events.
11421 *
11422 * @private
11423 * @param {string} value New value
11424 */
11425 OO.ui.ComboBoxInputWidget.prototype.onInputChange = function ( value ) {
11426 var match = this.menu.findItemFromData( value );
11427
11428 this.menu.selectItem( match );
11429 if ( this.menu.findHighlightedItem() ) {
11430 this.menu.highlightItem( match );
11431 }
11432
11433 if ( !this.isDisabled() ) {
11434 this.menu.toggle( true );
11435 }
11436 };
11437
11438 /**
11439 * Handle input enter events.
11440 *
11441 * @private
11442 */
11443 OO.ui.ComboBoxInputWidget.prototype.onInputEnter = function () {
11444 if ( !this.isDisabled() ) {
11445 this.menu.toggle( false );
11446 }
11447 };
11448
11449 /**
11450 * Handle button click events.
11451 *
11452 * @private
11453 */
11454 OO.ui.ComboBoxInputWidget.prototype.onDropdownButtonClick = function () {
11455 this.menu.toggle();
11456 this.focus();
11457 };
11458
11459 /**
11460 * Handle menu choose events.
11461 *
11462 * @private
11463 * @param {OO.ui.OptionWidget} item Chosen item
11464 */
11465 OO.ui.ComboBoxInputWidget.prototype.onMenuChoose = function ( item ) {
11466 this.setValue( item.getData() );
11467 };
11468
11469 /**
11470 * Handle menu item change events.
11471 *
11472 * @private
11473 */
11474 OO.ui.ComboBoxInputWidget.prototype.onMenuItemsChange = function () {
11475 var match = this.menu.findItemFromData( this.getValue() );
11476 this.menu.selectItem( match );
11477 if ( this.menu.findHighlightedItem() ) {
11478 this.menu.highlightItem( match );
11479 }
11480 this.$element.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu.isEmpty() );
11481 };
11482
11483 /**
11484 * Handle menu toggle events.
11485 *
11486 * @private
11487 * @param {boolean} isVisible Open state of the menu
11488 */
11489 OO.ui.ComboBoxInputWidget.prototype.onMenuToggle = function ( isVisible ) {
11490 this.$element.toggleClass( 'oo-ui-comboBoxInputWidget-open', isVisible );
11491 };
11492
11493 /**
11494 * @inheritdoc
11495 */
11496 OO.ui.ComboBoxInputWidget.prototype.setDisabled = function ( disabled ) {
11497 // Parent method
11498 OO.ui.ComboBoxInputWidget.parent.prototype.setDisabled.call( this, disabled );
11499
11500 if ( this.dropdownButton ) {
11501 this.dropdownButton.setDisabled( this.isDisabled() );
11502 }
11503 if ( this.menu ) {
11504 this.menu.setDisabled( this.isDisabled() );
11505 }
11506
11507 return this;
11508 };
11509
11510 /**
11511 * Set the options available for this input.
11512 *
11513 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
11514 * @chainable
11515 * @return {OO.ui.Widget} The widget, for chaining
11516 */
11517 OO.ui.ComboBoxInputWidget.prototype.setOptions = function ( options ) {
11518 this.getMenu()
11519 .clearItems()
11520 .addItems( options.map( function ( opt ) {
11521 return new OO.ui.MenuOptionWidget( {
11522 data: opt.data,
11523 label: opt.label !== undefined ? opt.label : opt.data
11524 } );
11525 } ) );
11526
11527 return this;
11528 };
11529
11530 /**
11531 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
11532 * which is a widget that is specified by reference before any optional configuration settings.
11533 *
11534 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
11535 *
11536 * - **left**: The label is placed before the field-widget and aligned with the left margin.
11537 * A left-alignment is used for forms with many fields.
11538 * - **right**: The label is placed before the field-widget and aligned to the right margin.
11539 * A right-alignment is used for long but familiar forms which users tab through,
11540 * verifying the current field with a quick glance at the label.
11541 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
11542 * that users fill out from top to bottom.
11543 * - **inline**: The label is placed after the field-widget and aligned to the left.
11544 * An inline-alignment is best used with checkboxes or radio buttons.
11545 *
11546 * Help text can either be:
11547 *
11548 * - accessed via a help icon that appears in the upper right corner of the rendered field layout, or
11549 * - shown as a subtle explanation below the label.
11550 *
11551 * If the help text is brief, or is essential to always expose it, set `helpInline` to `true`. If it
11552 * is long or not essential, leave `helpInline` to its default, `false`.
11553 *
11554 * Please see the [OOUI documentation on MediaWiki] [1] for examples and more information.
11555 *
11556 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
11557 *
11558 * @class
11559 * @extends OO.ui.Layout
11560 * @mixins OO.ui.mixin.LabelElement
11561 * @mixins OO.ui.mixin.TitledElement
11562 *
11563 * @constructor
11564 * @param {OO.ui.Widget} fieldWidget Field widget
11565 * @param {Object} [config] Configuration options
11566 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top'
11567 * or 'inline'
11568 * @cfg {Array} [errors] Error messages about the widget, which will be
11569 * displayed below the widget.
11570 * The array may contain strings or OO.ui.HtmlSnippet instances.
11571 * @cfg {Array} [notices] Notices about the widget, which will be displayed
11572 * below the widget.
11573 * The array may contain strings or OO.ui.HtmlSnippet instances.
11574 * These are more visible than `help` messages when `helpInline` is set, and so
11575 * might be good for transient messages.
11576 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified
11577 * and `helpInline` is `false`, a "help" icon will appear in the upper-right
11578 * corner of the rendered field; clicking it will display the text in a popup.
11579 * If `helpInline` is `true`, then a subtle description will be shown after the
11580 * label.
11581 * @cfg {boolean} [helpInline=false] Whether or not the help should be inline,
11582 * or shown when the "help" icon is clicked.
11583 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if
11584 * `help` is given.
11585 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11586 *
11587 * @throws {Error} An error is thrown if no widget is specified
11588 */
11589 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
11590 // Allow passing positional parameters inside the config object
11591 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
11592 config = fieldWidget;
11593 fieldWidget = config.fieldWidget;
11594 }
11595
11596 // Make sure we have required constructor arguments
11597 if ( fieldWidget === undefined ) {
11598 throw new Error( 'Widget not found' );
11599 }
11600
11601 // Configuration initialization
11602 config = $.extend( { align: 'left', helpInline: false }, config );
11603
11604 // Parent constructor
11605 OO.ui.FieldLayout.parent.call( this, config );
11606
11607 // Mixin constructors
11608 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, {
11609 $label: $( '<label>' )
11610 } ) );
11611 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
11612
11613 // Properties
11614 this.fieldWidget = fieldWidget;
11615 this.errors = [];
11616 this.notices = [];
11617 this.$field = this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
11618 this.$messages = $( '<ul>' );
11619 this.$header = $( '<span>' );
11620 this.$body = $( '<div>' );
11621 this.align = null;
11622 this.helpInline = config.helpInline;
11623
11624 // Events
11625 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
11626
11627 // Initialization
11628 this.$help = config.help ?
11629 this.createHelpElement( config.help, config.$overlay ) :
11630 $( [] );
11631 if ( this.fieldWidget.getInputId() ) {
11632 this.$label.attr( 'for', this.fieldWidget.getInputId() );
11633 if ( this.helpInline ) {
11634 this.$help.attr( 'for', this.fieldWidget.getInputId() );
11635 }
11636 } else {
11637 this.$label.on( 'click', function () {
11638 this.fieldWidget.simulateLabelClick();
11639 }.bind( this ) );
11640 if ( this.helpInline ) {
11641 this.$help.on( 'click', function () {
11642 this.fieldWidget.simulateLabelClick();
11643 }.bind( this ) );
11644 }
11645 }
11646 this.$element
11647 .addClass( 'oo-ui-fieldLayout' )
11648 .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget.isDisabled() )
11649 .append( this.$body );
11650 this.$body.addClass( 'oo-ui-fieldLayout-body' );
11651 this.$header.addClass( 'oo-ui-fieldLayout-header' );
11652 this.$messages.addClass( 'oo-ui-fieldLayout-messages' );
11653 this.$field
11654 .addClass( 'oo-ui-fieldLayout-field' )
11655 .append( this.fieldWidget.$element );
11656
11657 this.setErrors( config.errors || [] );
11658 this.setNotices( config.notices || [] );
11659 this.setAlignment( config.align );
11660 // Call this again to take into account the widget's accessKey
11661 this.updateTitle();
11662 };
11663
11664 /* Setup */
11665
11666 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
11667 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.LabelElement );
11668 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.TitledElement );
11669
11670 /* Methods */
11671
11672 /**
11673 * Handle field disable events.
11674 *
11675 * @private
11676 * @param {boolean} value Field is disabled
11677 */
11678 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
11679 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
11680 };
11681
11682 /**
11683 * Get the widget contained by the field.
11684 *
11685 * @return {OO.ui.Widget} Field widget
11686 */
11687 OO.ui.FieldLayout.prototype.getField = function () {
11688 return this.fieldWidget;
11689 };
11690
11691 /**
11692 * Return `true` if the given field widget can be used with `'inline'` alignment (see
11693 * #setAlignment). Return `false` if it can't or if this can't be determined.
11694 *
11695 * @return {boolean}
11696 */
11697 OO.ui.FieldLayout.prototype.isFieldInline = function () {
11698 // This is very simplistic, but should be good enough.
11699 return this.getField().$element.prop( 'tagName' ).toLowerCase() === 'span';
11700 };
11701
11702 /**
11703 * @protected
11704 * @param {string} kind 'error' or 'notice'
11705 * @param {string|OO.ui.HtmlSnippet} text
11706 * @return {jQuery}
11707 */
11708 OO.ui.FieldLayout.prototype.makeMessage = function ( kind, text ) {
11709 var $listItem, $icon, message;
11710 $listItem = $( '<li>' );
11711 if ( kind === 'error' ) {
11712 $icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'warning' ] } ).$element;
11713 $listItem.attr( 'role', 'alert' );
11714 } else if ( kind === 'notice' ) {
11715 $icon = new OO.ui.IconWidget( { icon: 'notice' } ).$element;
11716 } else {
11717 $icon = '';
11718 }
11719 message = new OO.ui.LabelWidget( { label: text } );
11720 $listItem
11721 .append( $icon, message.$element )
11722 .addClass( 'oo-ui-fieldLayout-messages-' + kind );
11723 return $listItem;
11724 };
11725
11726 /**
11727 * Set the field alignment mode.
11728 *
11729 * @private
11730 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
11731 * @chainable
11732 * @return {OO.ui.BookletLayout} The layout, for chaining
11733 */
11734 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
11735 if ( value !== this.align ) {
11736 // Default to 'left'
11737 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
11738 value = 'left';
11739 }
11740 // Validate
11741 if ( value === 'inline' && !this.isFieldInline() ) {
11742 value = 'top';
11743 }
11744 // Reorder elements
11745
11746 if ( this.helpInline ) {
11747 if ( value === 'top' ) {
11748 this.$header.append( this.$label );
11749 this.$body.append( this.$header, this.$field, this.$help );
11750 } else if ( value === 'inline' ) {
11751 this.$header.append( this.$label, this.$help );
11752 this.$body.append( this.$field, this.$header );
11753 } else {
11754 this.$header.append( this.$label, this.$help );
11755 this.$body.append( this.$header, this.$field );
11756 }
11757 } else {
11758 if ( value === 'top' ) {
11759 this.$header.append( this.$help, this.$label );
11760 this.$body.append( this.$header, this.$field );
11761 } else if ( value === 'inline' ) {
11762 this.$header.append( this.$help, this.$label );
11763 this.$body.append( this.$field, this.$header );
11764 } else {
11765 this.$header.append( this.$label );
11766 this.$body.append( this.$header, this.$help, this.$field );
11767 }
11768 }
11769 // Set classes. The following classes can be used here:
11770 // * oo-ui-fieldLayout-align-left
11771 // * oo-ui-fieldLayout-align-right
11772 // * oo-ui-fieldLayout-align-top
11773 // * oo-ui-fieldLayout-align-inline
11774 if ( this.align ) {
11775 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
11776 }
11777 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
11778 this.align = value;
11779 }
11780
11781 return this;
11782 };
11783
11784 /**
11785 * Set the list of error messages.
11786 *
11787 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
11788 * The array may contain strings or OO.ui.HtmlSnippet instances.
11789 * @chainable
11790 * @return {OO.ui.BookletLayout} The layout, for chaining
11791 */
11792 OO.ui.FieldLayout.prototype.setErrors = function ( errors ) {
11793 this.errors = errors.slice();
11794 this.updateMessages();
11795 return this;
11796 };
11797
11798 /**
11799 * Set the list of notice messages.
11800 *
11801 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
11802 * The array may contain strings or OO.ui.HtmlSnippet instances.
11803 * @chainable
11804 * @return {OO.ui.BookletLayout} The layout, for chaining
11805 */
11806 OO.ui.FieldLayout.prototype.setNotices = function ( notices ) {
11807 this.notices = notices.slice();
11808 this.updateMessages();
11809 return this;
11810 };
11811
11812 /**
11813 * Update the rendering of error and notice messages.
11814 *
11815 * @private
11816 */
11817 OO.ui.FieldLayout.prototype.updateMessages = function () {
11818 var i;
11819 this.$messages.empty();
11820
11821 if ( this.errors.length || this.notices.length ) {
11822 this.$body.after( this.$messages );
11823 } else {
11824 this.$messages.remove();
11825 return;
11826 }
11827
11828 for ( i = 0; i < this.notices.length; i++ ) {
11829 this.$messages.append( this.makeMessage( 'notice', this.notices[ i ] ) );
11830 }
11831 for ( i = 0; i < this.errors.length; i++ ) {
11832 this.$messages.append( this.makeMessage( 'error', this.errors[ i ] ) );
11833 }
11834 };
11835
11836 /**
11837 * Include information about the widget's accessKey in our title. TitledElement calls this method.
11838 * (This is a bit of a hack.)
11839 *
11840 * @protected
11841 * @param {string} title Tooltip label for 'title' attribute
11842 * @return {string}
11843 */
11844 OO.ui.FieldLayout.prototype.formatTitleWithAccessKey = function ( title ) {
11845 if ( this.fieldWidget && this.fieldWidget.formatTitleWithAccessKey ) {
11846 return this.fieldWidget.formatTitleWithAccessKey( title );
11847 }
11848 return title;
11849 };
11850
11851 /**
11852 * Creates and returns the help element. Also sets the `aria-describedby`
11853 * attribute on the main element of the `fieldWidget`.
11854 *
11855 * @private
11856 * @param {string|OO.ui.HtmlSnippet} [help] Help text.
11857 * @param {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup.
11858 * @return {jQuery} The element that should become `this.$help`.
11859 */
11860 OO.ui.FieldLayout.prototype.createHelpElement = function ( help, $overlay ) {
11861 var helpId, helpWidget;
11862
11863 if ( this.helpInline ) {
11864 helpWidget = new OO.ui.LabelWidget( {
11865 label: help,
11866 classes: [ 'oo-ui-inline-help' ]
11867 } );
11868
11869 helpId = helpWidget.getElementId();
11870 } else {
11871 helpWidget = new OO.ui.PopupButtonWidget( {
11872 $overlay: $overlay,
11873 popup: {
11874 padded: true
11875 },
11876 classes: [ 'oo-ui-fieldLayout-help' ],
11877 framed: false,
11878 icon: 'info',
11879 label: OO.ui.msg( 'ooui-field-help' ),
11880 invisibleLabel: true
11881 } );
11882 if ( help instanceof OO.ui.HtmlSnippet ) {
11883 helpWidget.getPopup().$body.html( help.toString() );
11884 } else {
11885 helpWidget.getPopup().$body.text( help );
11886 }
11887
11888 helpId = helpWidget.getPopup().getBodyId();
11889 }
11890
11891 // Set the 'aria-describedby' attribute on the fieldWidget
11892 // Preference given to an input or a button
11893 (
11894 this.fieldWidget.$input ||
11895 this.fieldWidget.$button ||
11896 this.fieldWidget.$element
11897 ).attr( 'aria-describedby', helpId );
11898
11899 return helpWidget.$element;
11900 };
11901
11902 /**
11903 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
11904 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
11905 * is required and is specified before any optional configuration settings.
11906 *
11907 * Labels can be aligned in one of four ways:
11908 *
11909 * - **left**: The label is placed before the field-widget and aligned with the left margin.
11910 * A left-alignment is used for forms with many fields.
11911 * - **right**: The label is placed before the field-widget and aligned to the right margin.
11912 * A right-alignment is used for long but familiar forms which users tab through,
11913 * verifying the current field with a quick glance at the label.
11914 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
11915 * that users fill out from top to bottom.
11916 * - **inline**: The label is placed after the field-widget and aligned to the left.
11917 * An inline-alignment is best used with checkboxes or radio buttons.
11918 *
11919 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
11920 * text is specified.
11921 *
11922 * @example
11923 * // Example of an ActionFieldLayout
11924 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
11925 * new OO.ui.TextInputWidget( {
11926 * placeholder: 'Field widget'
11927 * } ),
11928 * new OO.ui.ButtonWidget( {
11929 * label: 'Button'
11930 * } ),
11931 * {
11932 * label: 'An ActionFieldLayout. This label is aligned top',
11933 * align: 'top',
11934 * help: 'This is help text'
11935 * }
11936 * );
11937 *
11938 * $( 'body' ).append( actionFieldLayout.$element );
11939 *
11940 * @class
11941 * @extends OO.ui.FieldLayout
11942 *
11943 * @constructor
11944 * @param {OO.ui.Widget} fieldWidget Field widget
11945 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
11946 * @param {Object} config
11947 */
11948 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
11949 // Allow passing positional parameters inside the config object
11950 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
11951 config = fieldWidget;
11952 fieldWidget = config.fieldWidget;
11953 buttonWidget = config.buttonWidget;
11954 }
11955
11956 // Parent constructor
11957 OO.ui.ActionFieldLayout.parent.call( this, fieldWidget, config );
11958
11959 // Properties
11960 this.buttonWidget = buttonWidget;
11961 this.$button = $( '<span>' );
11962 this.$input = this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
11963
11964 // Initialization
11965 this.$element
11966 .addClass( 'oo-ui-actionFieldLayout' );
11967 this.$button
11968 .addClass( 'oo-ui-actionFieldLayout-button' )
11969 .append( this.buttonWidget.$element );
11970 this.$input
11971 .addClass( 'oo-ui-actionFieldLayout-input' )
11972 .append( this.fieldWidget.$element );
11973 this.$field
11974 .append( this.$input, this.$button );
11975 };
11976
11977 /* Setup */
11978
11979 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
11980
11981 /**
11982 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
11983 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
11984 * configured with a label as well. For more information and examples,
11985 * please see the [OOUI documentation on MediaWiki][1].
11986 *
11987 * @example
11988 * // Example of a fieldset layout
11989 * var input1 = new OO.ui.TextInputWidget( {
11990 * placeholder: 'A text input field'
11991 * } );
11992 *
11993 * var input2 = new OO.ui.TextInputWidget( {
11994 * placeholder: 'A text input field'
11995 * } );
11996 *
11997 * var fieldset = new OO.ui.FieldsetLayout( {
11998 * label: 'Example of a fieldset layout'
11999 * } );
12000 *
12001 * fieldset.addItems( [
12002 * new OO.ui.FieldLayout( input1, {
12003 * label: 'Field One'
12004 * } ),
12005 * new OO.ui.FieldLayout( input2, {
12006 * label: 'Field Two'
12007 * } )
12008 * ] );
12009 * $( 'body' ).append( fieldset.$element );
12010 *
12011 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
12012 *
12013 * @class
12014 * @extends OO.ui.Layout
12015 * @mixins OO.ui.mixin.IconElement
12016 * @mixins OO.ui.mixin.LabelElement
12017 * @mixins OO.ui.mixin.GroupElement
12018 *
12019 * @constructor
12020 * @param {Object} [config] Configuration options
12021 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
12022 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
12023 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
12024 * For important messages, you are advised to use `notices`, as they are always shown.
12025 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
12026 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
12027 */
12028 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
12029 // Configuration initialization
12030 config = config || {};
12031
12032 // Parent constructor
12033 OO.ui.FieldsetLayout.parent.call( this, config );
12034
12035 // Mixin constructors
12036 OO.ui.mixin.IconElement.call( this, config );
12037 OO.ui.mixin.LabelElement.call( this, config );
12038 OO.ui.mixin.GroupElement.call( this, config );
12039
12040 // Properties
12041 this.$header = $( '<legend>' );
12042 if ( config.help ) {
12043 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
12044 $overlay: config.$overlay,
12045 popup: {
12046 padded: true
12047 },
12048 classes: [ 'oo-ui-fieldsetLayout-help' ],
12049 framed: false,
12050 icon: 'info',
12051 label: OO.ui.msg( 'ooui-field-help' ),
12052 invisibleLabel: true
12053 } );
12054 if ( config.help instanceof OO.ui.HtmlSnippet ) {
12055 this.popupButtonWidget.getPopup().$body.html( config.help.toString() );
12056 } else {
12057 this.popupButtonWidget.getPopup().$body.text( config.help );
12058 }
12059 this.$help = this.popupButtonWidget.$element;
12060 } else {
12061 this.$help = $( [] );
12062 }
12063
12064 // Initialization
12065 this.$header
12066 .addClass( 'oo-ui-fieldsetLayout-header' )
12067 .append( this.$icon, this.$label, this.$help );
12068 this.$group.addClass( 'oo-ui-fieldsetLayout-group' );
12069 this.$element
12070 .addClass( 'oo-ui-fieldsetLayout' )
12071 .prepend( this.$header, this.$group );
12072 if ( Array.isArray( config.items ) ) {
12073 this.addItems( config.items );
12074 }
12075 };
12076
12077 /* Setup */
12078
12079 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
12080 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.IconElement );
12081 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.LabelElement );
12082 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.GroupElement );
12083
12084 /* Static Properties */
12085
12086 /**
12087 * @static
12088 * @inheritdoc
12089 */
12090 OO.ui.FieldsetLayout.static.tagName = 'fieldset';
12091
12092 /**
12093 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
12094 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
12095 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
12096 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
12097 *
12098 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
12099 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
12100 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
12101 * some fancier controls. Some controls have both regular and InputWidget variants, for example
12102 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
12103 * often have simplified APIs to match the capabilities of HTML forms.
12104 * See the [OOUI documentation on MediaWiki] [2] for more information about InputWidgets.
12105 *
12106 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Forms
12107 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
12108 *
12109 * @example
12110 * // Example of a form layout that wraps a fieldset layout
12111 * var input1 = new OO.ui.TextInputWidget( {
12112 * placeholder: 'Username'
12113 * } );
12114 * var input2 = new OO.ui.TextInputWidget( {
12115 * placeholder: 'Password',
12116 * type: 'password'
12117 * } );
12118 * var submit = new OO.ui.ButtonInputWidget( {
12119 * label: 'Submit'
12120 * } );
12121 *
12122 * var fieldset = new OO.ui.FieldsetLayout( {
12123 * label: 'A form layout'
12124 * } );
12125 * fieldset.addItems( [
12126 * new OO.ui.FieldLayout( input1, {
12127 * label: 'Username',
12128 * align: 'top'
12129 * } ),
12130 * new OO.ui.FieldLayout( input2, {
12131 * label: 'Password',
12132 * align: 'top'
12133 * } ),
12134 * new OO.ui.FieldLayout( submit )
12135 * ] );
12136 * var form = new OO.ui.FormLayout( {
12137 * items: [ fieldset ],
12138 * action: '/api/formhandler',
12139 * method: 'get'
12140 * } )
12141 * $( 'body' ).append( form.$element );
12142 *
12143 * @class
12144 * @extends OO.ui.Layout
12145 * @mixins OO.ui.mixin.GroupElement
12146 *
12147 * @constructor
12148 * @param {Object} [config] Configuration options
12149 * @cfg {string} [method] HTML form `method` attribute
12150 * @cfg {string} [action] HTML form `action` attribute
12151 * @cfg {string} [enctype] HTML form `enctype` attribute
12152 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
12153 */
12154 OO.ui.FormLayout = function OoUiFormLayout( config ) {
12155 var action;
12156
12157 // Configuration initialization
12158 config = config || {};
12159
12160 // Parent constructor
12161 OO.ui.FormLayout.parent.call( this, config );
12162
12163 // Mixin constructors
12164 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
12165
12166 // Events
12167 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
12168
12169 // Make sure the action is safe
12170 action = config.action;
12171 if ( action !== undefined && !OO.ui.isSafeUrl( action ) ) {
12172 action = './' + action;
12173 }
12174
12175 // Initialization
12176 this.$element
12177 .addClass( 'oo-ui-formLayout' )
12178 .attr( {
12179 method: config.method,
12180 action: action,
12181 enctype: config.enctype
12182 } );
12183 if ( Array.isArray( config.items ) ) {
12184 this.addItems( config.items );
12185 }
12186 };
12187
12188 /* Setup */
12189
12190 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
12191 OO.mixinClass( OO.ui.FormLayout, OO.ui.mixin.GroupElement );
12192
12193 /* Events */
12194
12195 /**
12196 * A 'submit' event is emitted when the form is submitted.
12197 *
12198 * @event submit
12199 */
12200
12201 /* Static Properties */
12202
12203 /**
12204 * @static
12205 * @inheritdoc
12206 */
12207 OO.ui.FormLayout.static.tagName = 'form';
12208
12209 /* Methods */
12210
12211 /**
12212 * Handle form submit events.
12213 *
12214 * @private
12215 * @param {jQuery.Event} e Submit event
12216 * @fires submit
12217 * @return {OO.ui.FormLayout} The layout, for chaining
12218 */
12219 OO.ui.FormLayout.prototype.onFormSubmit = function () {
12220 if ( this.emit( 'submit' ) ) {
12221 return false;
12222 }
12223 };
12224
12225 /**
12226 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
12227 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
12228 *
12229 * @example
12230 * // Example of a panel layout
12231 * var panel = new OO.ui.PanelLayout( {
12232 * expanded: false,
12233 * framed: true,
12234 * padded: true,
12235 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
12236 * } );
12237 * $( 'body' ).append( panel.$element );
12238 *
12239 * @class
12240 * @extends OO.ui.Layout
12241 *
12242 * @constructor
12243 * @param {Object} [config] Configuration options
12244 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
12245 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
12246 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
12247 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
12248 */
12249 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
12250 // Configuration initialization
12251 config = $.extend( {
12252 scrollable: false,
12253 padded: false,
12254 expanded: true,
12255 framed: false
12256 }, config );
12257
12258 // Parent constructor
12259 OO.ui.PanelLayout.parent.call( this, config );
12260
12261 // Initialization
12262 this.$element.addClass( 'oo-ui-panelLayout' );
12263 if ( config.scrollable ) {
12264 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
12265 }
12266 if ( config.padded ) {
12267 this.$element.addClass( 'oo-ui-panelLayout-padded' );
12268 }
12269 if ( config.expanded ) {
12270 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
12271 }
12272 if ( config.framed ) {
12273 this.$element.addClass( 'oo-ui-panelLayout-framed' );
12274 }
12275 };
12276
12277 /* Setup */
12278
12279 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
12280
12281 /* Methods */
12282
12283 /**
12284 * Focus the panel layout
12285 *
12286 * The default implementation just focuses the first focusable element in the panel
12287 */
12288 OO.ui.PanelLayout.prototype.focus = function () {
12289 OO.ui.findFocusable( this.$element ).focus();
12290 };
12291
12292 /**
12293 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
12294 * items), with small margins between them. Convenient when you need to put a number of block-level
12295 * widgets on a single line next to each other.
12296 *
12297 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
12298 *
12299 * @example
12300 * // HorizontalLayout with a text input and a label
12301 * var layout = new OO.ui.HorizontalLayout( {
12302 * items: [
12303 * new OO.ui.LabelWidget( { label: 'Label' } ),
12304 * new OO.ui.TextInputWidget( { value: 'Text' } )
12305 * ]
12306 * } );
12307 * $( 'body' ).append( layout.$element );
12308 *
12309 * @class
12310 * @extends OO.ui.Layout
12311 * @mixins OO.ui.mixin.GroupElement
12312 *
12313 * @constructor
12314 * @param {Object} [config] Configuration options
12315 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
12316 */
12317 OO.ui.HorizontalLayout = function OoUiHorizontalLayout( config ) {
12318 // Configuration initialization
12319 config = config || {};
12320
12321 // Parent constructor
12322 OO.ui.HorizontalLayout.parent.call( this, config );
12323
12324 // Mixin constructors
12325 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
12326
12327 // Initialization
12328 this.$element.addClass( 'oo-ui-horizontalLayout' );
12329 if ( Array.isArray( config.items ) ) {
12330 this.addItems( config.items );
12331 }
12332 };
12333
12334 /* Setup */
12335
12336 OO.inheritClass( OO.ui.HorizontalLayout, OO.ui.Layout );
12337 OO.mixinClass( OO.ui.HorizontalLayout, OO.ui.mixin.GroupElement );
12338
12339 /**
12340 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
12341 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
12342 * (to adjust the value in increments) to allow the user to enter a number.
12343 *
12344 * @example
12345 * // Example: A NumberInputWidget.
12346 * var numberInput = new OO.ui.NumberInputWidget( {
12347 * label: 'NumberInputWidget',
12348 * input: { value: 5 },
12349 * min: 1,
12350 * max: 10
12351 * } );
12352 * $( 'body' ).append( numberInput.$element );
12353 *
12354 * @class
12355 * @extends OO.ui.TextInputWidget
12356 *
12357 * @constructor
12358 * @param {Object} [config] Configuration options
12359 * @cfg {Object} [minusButton] Configuration options to pass to the
12360 * {@link OO.ui.ButtonWidget decrementing button widget}.
12361 * @cfg {Object} [plusButton] Configuration options to pass to the
12362 * {@link OO.ui.ButtonWidget incrementing button widget}.
12363 * @cfg {number} [min=-Infinity] Minimum allowed value
12364 * @cfg {number} [max=Infinity] Maximum allowed value
12365 * @cfg {number|null} [step] If specified, the field only accepts values that are multiples of this.
12366 * @cfg {number} [buttonStep=step||1] Delta when using the buttons or up/down arrow keys.
12367 * Defaults to `step` if specified, otherwise `1`.
12368 * @cfg {number} [pageStep=10*buttonStep] Delta when using the page-up/page-down keys.
12369 * Defaults to 10 times `buttonStep`.
12370 * @cfg {boolean} [showButtons=true] Whether to show the plus and minus buttons.
12371 */
12372 OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
12373 var $field = $( '<div>' )
12374 .addClass( 'oo-ui-numberInputWidget-field' );
12375
12376 // Configuration initialization
12377 config = $.extend( {
12378 min: -Infinity,
12379 max: Infinity,
12380 showButtons: true
12381 }, config );
12382
12383 // For backward compatibility
12384 $.extend( config, config.input );
12385 this.input = this;
12386
12387 // Parent constructor
12388 OO.ui.NumberInputWidget.parent.call( this, $.extend( config, {
12389 type: 'number'
12390 } ) );
12391
12392 if ( config.showButtons ) {
12393 this.minusButton = new OO.ui.ButtonWidget( $.extend(
12394 {
12395 disabled: this.isDisabled(),
12396 tabIndex: -1,
12397 classes: [ 'oo-ui-numberInputWidget-minusButton' ],
12398 icon: 'subtract'
12399 },
12400 config.minusButton
12401 ) );
12402 this.minusButton.$element.attr( 'aria-hidden', 'true' );
12403 this.plusButton = new OO.ui.ButtonWidget( $.extend(
12404 {
12405 disabled: this.isDisabled(),
12406 tabIndex: -1,
12407 classes: [ 'oo-ui-numberInputWidget-plusButton' ],
12408 icon: 'add'
12409 },
12410 config.plusButton
12411 ) );
12412 this.plusButton.$element.attr( 'aria-hidden', 'true' );
12413 }
12414
12415 // Events
12416 this.$input.on( {
12417 keydown: this.onKeyDown.bind( this ),
12418 'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
12419 } );
12420 if ( config.showButtons ) {
12421 this.plusButton.connect( this, {
12422 click: [ 'onButtonClick', +1 ]
12423 } );
12424 this.minusButton.connect( this, {
12425 click: [ 'onButtonClick', -1 ]
12426 } );
12427 }
12428
12429 // Build the field
12430 $field.append( this.$input );
12431 if ( config.showButtons ) {
12432 $field
12433 .prepend( this.minusButton.$element )
12434 .append( this.plusButton.$element );
12435 }
12436
12437 // Initialization
12438 if ( config.allowInteger || config.isInteger ) {
12439 // Backward compatibility
12440 config.step = 1;
12441 }
12442 this.setRange( config.min, config.max );
12443 this.setStep( config.buttonStep, config.pageStep, config.step );
12444 // Set the validation method after we set step and range
12445 // so that it doesn't immediately call setValidityFlag
12446 this.setValidation( this.validateNumber.bind( this ) );
12447
12448 this.$element
12449 .addClass( 'oo-ui-numberInputWidget' )
12450 .toggleClass( 'oo-ui-numberInputWidget-buttoned', config.showButtons )
12451 .append( $field );
12452 };
12453
12454 /* Setup */
12455
12456 OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.TextInputWidget );
12457
12458 /* Methods */
12459
12460 // Backward compatibility
12461 OO.ui.NumberInputWidget.prototype.setAllowInteger = function ( flag ) {
12462 this.setStep( flag ? 1 : null );
12463 };
12464 // Backward compatibility
12465 OO.ui.NumberInputWidget.prototype.setIsInteger = OO.ui.NumberInputWidget.prototype.setAllowInteger;
12466
12467 // Backward compatibility
12468 OO.ui.NumberInputWidget.prototype.getAllowInteger = function () {
12469 return this.step === 1;
12470 };
12471 // Backward compatibility
12472 OO.ui.NumberInputWidget.prototype.getIsInteger = OO.ui.NumberInputWidget.prototype.getAllowInteger;
12473
12474 /**
12475 * Set the range of allowed values
12476 *
12477 * @param {number} min Minimum allowed value
12478 * @param {number} max Maximum allowed value
12479 */
12480 OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
12481 if ( min > max ) {
12482 throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
12483 }
12484 this.min = min;
12485 this.max = max;
12486 this.$input.attr( 'min', this.min );
12487 this.$input.attr( 'max', this.max );
12488 this.setValidityFlag();
12489 };
12490
12491 /**
12492 * Get the current range
12493 *
12494 * @return {number[]} Minimum and maximum values
12495 */
12496 OO.ui.NumberInputWidget.prototype.getRange = function () {
12497 return [ this.min, this.max ];
12498 };
12499
12500 /**
12501 * Set the stepping deltas
12502 *
12503 * @param {number} [buttonStep=step||1] Delta when using the buttons or up/down arrow keys.
12504 * Defaults to `step` if specified, otherwise `1`.
12505 * @param {number} [pageStep=10*buttonStep] Delta when using the page-up/page-down keys.
12506 * Defaults to 10 times `buttonStep`.
12507 * @param {number|null} [step] If specified, the field only accepts values that are multiples of this.
12508 */
12509 OO.ui.NumberInputWidget.prototype.setStep = function ( buttonStep, pageStep, step ) {
12510 if ( buttonStep === undefined ) {
12511 buttonStep = step || 1;
12512 }
12513 if ( pageStep === undefined ) {
12514 pageStep = 10 * buttonStep;
12515 }
12516 if ( step !== null && step <= 0 ) {
12517 throw new Error( 'Step value, if given, must be positive' );
12518 }
12519 if ( buttonStep <= 0 ) {
12520 throw new Error( 'Button step value must be positive' );
12521 }
12522 if ( pageStep <= 0 ) {
12523 throw new Error( 'Page step value must be positive' );
12524 }
12525 this.step = step;
12526 this.buttonStep = buttonStep;
12527 this.pageStep = pageStep;
12528 this.$input.attr( 'step', this.step || 'any' );
12529 this.setValidityFlag();
12530 };
12531
12532 /**
12533 * @inheritdoc
12534 */
12535 OO.ui.NumberInputWidget.prototype.setValue = function ( value ) {
12536 if ( value === '' ) {
12537 // Some browsers allow a value in the input even if there isn't one reported by $input.val()
12538 // so here we make sure an 'empty' value is actually displayed as such.
12539 this.$input.val( '' );
12540 }
12541 return OO.ui.NumberInputWidget.parent.prototype.setValue.call( this, value );
12542 };
12543
12544 /**
12545 * Get the current stepping values
12546 *
12547 * @return {number[]} Button step, page step, and validity step
12548 */
12549 OO.ui.NumberInputWidget.prototype.getStep = function () {
12550 return [ this.buttonStep, this.pageStep, this.step ];
12551 };
12552
12553 /**
12554 * Get the current value of the widget as a number
12555 *
12556 * @return {number} May be NaN, or an invalid number
12557 */
12558 OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
12559 return +this.getValue();
12560 };
12561
12562 /**
12563 * Adjust the value of the widget
12564 *
12565 * @param {number} delta Adjustment amount
12566 */
12567 OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
12568 var n, v = this.getNumericValue();
12569
12570 delta = +delta;
12571 if ( isNaN( delta ) || !isFinite( delta ) ) {
12572 throw new Error( 'Delta must be a finite number' );
12573 }
12574
12575 if ( isNaN( v ) ) {
12576 n = 0;
12577 } else {
12578 n = v + delta;
12579 n = Math.max( Math.min( n, this.max ), this.min );
12580 if ( this.step ) {
12581 n = Math.round( n / this.step ) * this.step;
12582 }
12583 }
12584
12585 if ( n !== v ) {
12586 this.setValue( n );
12587 }
12588 };
12589 /**
12590 * Validate input
12591 *
12592 * @private
12593 * @param {string} value Field value
12594 * @return {boolean}
12595 */
12596 OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
12597 var n = +value;
12598 if ( value === '' ) {
12599 return !this.isRequired();
12600 }
12601
12602 if ( isNaN( n ) || !isFinite( n ) ) {
12603 return false;
12604 }
12605
12606 if ( this.step && Math.floor( n / this.step ) !== n / this.step ) {
12607 return false;
12608 }
12609
12610 if ( n < this.min || n > this.max ) {
12611 return false;
12612 }
12613
12614 return true;
12615 };
12616
12617 /**
12618 * Handle mouse click events.
12619 *
12620 * @private
12621 * @param {number} dir +1 or -1
12622 */
12623 OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
12624 this.adjustValue( dir * this.buttonStep );
12625 };
12626
12627 /**
12628 * Handle mouse wheel events.
12629 *
12630 * @private
12631 * @param {jQuery.Event} event
12632 * @return {undefined/boolean} False to prevent default if event is handled
12633 */
12634 OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
12635 var delta = 0;
12636
12637 if ( !this.isDisabled() && this.$input.is( ':focus' ) ) {
12638 // Standard 'wheel' event
12639 if ( event.originalEvent.deltaMode !== undefined ) {
12640 this.sawWheelEvent = true;
12641 }
12642 if ( event.originalEvent.deltaY ) {
12643 delta = -event.originalEvent.deltaY;
12644 } else if ( event.originalEvent.deltaX ) {
12645 delta = event.originalEvent.deltaX;
12646 }
12647
12648 // Non-standard events
12649 if ( !this.sawWheelEvent ) {
12650 if ( event.originalEvent.wheelDeltaX ) {
12651 delta = -event.originalEvent.wheelDeltaX;
12652 } else if ( event.originalEvent.wheelDeltaY ) {
12653 delta = event.originalEvent.wheelDeltaY;
12654 } else if ( event.originalEvent.wheelDelta ) {
12655 delta = event.originalEvent.wheelDelta;
12656 } else if ( event.originalEvent.detail ) {
12657 delta = -event.originalEvent.detail;
12658 }
12659 }
12660
12661 if ( delta ) {
12662 delta = delta < 0 ? -1 : 1;
12663 this.adjustValue( delta * this.buttonStep );
12664 }
12665
12666 return false;
12667 }
12668 };
12669
12670 /**
12671 * Handle key down events.
12672 *
12673 * @private
12674 * @param {jQuery.Event} e Key down event
12675 * @return {undefined/boolean} False to prevent default if event is handled
12676 */
12677 OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
12678 if ( !this.isDisabled() ) {
12679 switch ( e.which ) {
12680 case OO.ui.Keys.UP:
12681 this.adjustValue( this.buttonStep );
12682 return false;
12683 case OO.ui.Keys.DOWN:
12684 this.adjustValue( -this.buttonStep );
12685 return false;
12686 case OO.ui.Keys.PAGEUP:
12687 this.adjustValue( this.pageStep );
12688 return false;
12689 case OO.ui.Keys.PAGEDOWN:
12690 this.adjustValue( -this.pageStep );
12691 return false;
12692 }
12693 }
12694 };
12695
12696 /**
12697 * @inheritdoc
12698 */
12699 OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
12700 // Parent method
12701 OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
12702
12703 if ( this.minusButton ) {
12704 this.minusButton.setDisabled( this.isDisabled() );
12705 }
12706 if ( this.plusButton ) {
12707 this.plusButton.setDisabled( this.isDisabled() );
12708 }
12709
12710 return this;
12711 };
12712
12713 }( OO ) );
12714
12715 //# sourceMappingURL=oojs-ui-core.js.map.json