Update OOUI to v0.30.3
[lhc/web/wiklou.git] / resources / lib / ooui / oojs-ui-core.js
1 /*!
2 * OOUI v0.30.3
3 * https://www.mediawiki.org/wiki/OOUI
4 *
5 * Copyright 2011–2019 OOUI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
8 *
9 * Date: 2019-02-21T10:57: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 button in combobox input that triggers its dropdown
381 'ooui-combobox-button-label': 'Dropdown for combobox',
382 // Label for the file selection widget's select file button
383 'ooui-selectfile-button-select': 'Select a file',
384 // Label for the file selection widget if file selection is not supported
385 'ooui-selectfile-not-supported': 'File selection is not supported',
386 // Label for the file selection widget when no file is currently selected
387 'ooui-selectfile-placeholder': 'No file is selected',
388 // Label for the file selection widget's drop target
389 'ooui-selectfile-dragdrop-placeholder': 'Drop file here',
390 // Label for the help icon attached to a form field
391 'ooui-field-help': 'Help'
392 };
393
394 /**
395 * Get a localized message.
396 *
397 * After the message key, message parameters may optionally be passed. In the default implementation,
398 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
399 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
400 * they support unnamed, ordered message parameters.
401 *
402 * In environments that provide a localization system, this function should be overridden to
403 * return the message translated in the user's language. The default implementation always returns
404 * English messages. An example of doing this with [jQuery.i18n](https://github.com/wikimedia/jquery.i18n)
405 * follows.
406 *
407 * @example
408 * var i, iLen, button,
409 * messagePath = 'oojs-ui/dist/i18n/',
410 * languages = [ $.i18n().locale, 'ur', 'en' ],
411 * languageMap = {};
412 *
413 * for ( i = 0, iLen = languages.length; i < iLen; i++ ) {
414 * languageMap[ languages[ i ] ] = messagePath + languages[ i ].toLowerCase() + '.json';
415 * }
416 *
417 * $.i18n().load( languageMap ).done( function() {
418 * // Replace the built-in `msg` only once we've loaded the internationalization.
419 * // OOUI uses `OO.ui.deferMsg` for all initially-loaded messages. So long as
420 * // you put off creating any widgets until this promise is complete, no English
421 * // will be displayed.
422 * OO.ui.msg = $.i18n;
423 *
424 * // A button displaying "OK" in the default locale
425 * button = new OO.ui.ButtonWidget( {
426 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
427 * icon: 'check'
428 * } );
429 * $( document.body ).append( button.$element );
430 *
431 * // A button displaying "OK" in Urdu
432 * $.i18n().locale = 'ur';
433 * button = new OO.ui.ButtonWidget( {
434 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
435 * icon: 'check'
436 * } );
437 * $( document.body ).append( button.$element );
438 * } );
439 *
440 * @param {string} key Message key
441 * @param {...Mixed} [params] Message parameters
442 * @return {string} Translated message with parameters substituted
443 */
444 OO.ui.msg = function ( key ) {
445 var message = messages[ key ],
446 params = Array.prototype.slice.call( arguments, 1 );
447 if ( typeof message === 'string' ) {
448 // Perform $1 substitution
449 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
450 var i = parseInt( n, 10 );
451 return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n;
452 } );
453 } else {
454 // Return placeholder if message not found
455 message = '[' + key + ']';
456 }
457 return message;
458 };
459 }() );
460
461 /**
462 * Package a message and arguments for deferred resolution.
463 *
464 * Use this when you are statically specifying a message and the message may not yet be present.
465 *
466 * @param {string} key Message key
467 * @param {...Mixed} [params] Message parameters
468 * @return {Function} Function that returns the resolved message when executed
469 */
470 OO.ui.deferMsg = function () {
471 var args = arguments;
472 return function () {
473 return OO.ui.msg.apply( OO.ui, args );
474 };
475 };
476
477 /**
478 * Resolve a message.
479 *
480 * If the message is a function it will be executed, otherwise it will pass through directly.
481 *
482 * @param {Function|string} msg Deferred message, or message text
483 * @return {string} Resolved message
484 */
485 OO.ui.resolveMsg = function ( msg ) {
486 if ( typeof msg === 'function' ) {
487 return msg();
488 }
489 return msg;
490 };
491
492 /**
493 * @param {string} url
494 * @return {boolean}
495 */
496 OO.ui.isSafeUrl = function ( url ) {
497 // Keep this function in sync with php/Tag.php
498 var i, protocolWhitelist;
499
500 function stringStartsWith( haystack, needle ) {
501 return haystack.substr( 0, needle.length ) === needle;
502 }
503
504 protocolWhitelist = [
505 'bitcoin', 'ftp', 'ftps', 'geo', 'git', 'gopher', 'http', 'https', 'irc', 'ircs',
506 'magnet', 'mailto', 'mms', 'news', 'nntp', 'redis', 'sftp', 'sip', 'sips', 'sms', 'ssh',
507 'svn', 'tel', 'telnet', 'urn', 'worldwind', 'xmpp'
508 ];
509
510 if ( url === '' ) {
511 return true;
512 }
513
514 for ( i = 0; i < protocolWhitelist.length; i++ ) {
515 if ( stringStartsWith( url, protocolWhitelist[ i ] + ':' ) ) {
516 return true;
517 }
518 }
519
520 // This matches '//' too
521 if ( stringStartsWith( url, '/' ) || stringStartsWith( url, './' ) ) {
522 return true;
523 }
524 if ( stringStartsWith( url, '?' ) || stringStartsWith( url, '#' ) ) {
525 return true;
526 }
527
528 return false;
529 };
530
531 /**
532 * Check if the user has a 'mobile' device.
533 *
534 * For our purposes this means the user is primarily using an
535 * on-screen keyboard, touch input instead of a mouse and may
536 * have a physically small display.
537 *
538 * It is left up to implementors to decide how to compute this
539 * so the default implementation always returns false.
540 *
541 * @return {boolean} User is on a mobile device
542 */
543 OO.ui.isMobile = function () {
544 return false;
545 };
546
547 /**
548 * Get the additional spacing that should be taken into account when displaying elements that are
549 * clipped to the viewport, e.g. dropdown menus and popups. This is meant to be overridden to avoid
550 * such menus overlapping any fixed headers/toolbars/navigation used by the site.
551 *
552 * @return {Object} Object with the properties 'top', 'right', 'bottom', 'left', each representing
553 * the extra spacing from that edge of viewport (in pixels)
554 */
555 OO.ui.getViewportSpacing = function () {
556 return {
557 top: 0,
558 right: 0,
559 bottom: 0,
560 left: 0
561 };
562 };
563
564 /**
565 * Get the default overlay, which is used by various widgets when they are passed `$overlay: true`.
566 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
567 *
568 * @return {jQuery} Default overlay node
569 */
570 OO.ui.getDefaultOverlay = function () {
571 if ( !OO.ui.$defaultOverlay ) {
572 OO.ui.$defaultOverlay = $( '<div>' ).addClass( 'oo-ui-defaultOverlay' );
573 $( document.body ).append( OO.ui.$defaultOverlay );
574 }
575 return OO.ui.$defaultOverlay;
576 };
577
578 /*!
579 * Mixin namespace.
580 */
581
582 /**
583 * Namespace for OOUI mixins.
584 *
585 * Mixins are named according to the type of object they are intended to
586 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
587 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
588 * is intended to be mixed in to an instance of OO.ui.Widget.
589 *
590 * @class
591 * @singleton
592 */
593 OO.ui.mixin = {};
594
595 /**
596 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
597 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
598 * connected to them and can't be interacted with.
599 *
600 * @abstract
601 * @class
602 *
603 * @constructor
604 * @param {Object} [config] Configuration options
605 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
606 * to the top level (e.g., the outermost div) of the element. See the [OOUI documentation on MediaWiki][2]
607 * for an example.
608 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches#cssExample
609 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
610 * @cfg {string} [text] Text to insert
611 * @cfg {Array} [content] An array of content elements to append (after #text).
612 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
613 * Instances of OO.ui.Element will have their $element appended.
614 * @cfg {jQuery} [$content] Content elements to append (after #text).
615 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
616 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
617 * Data can also be specified with the #setData method.
618 */
619 OO.ui.Element = function OoUiElement( config ) {
620 if ( OO.ui.isDemo ) {
621 this.initialConfig = config;
622 }
623 // Configuration initialization
624 config = config || {};
625
626 // Properties
627 this.$ = function () {
628 OO.ui.warnDeprecation( 'this.$ is deprecated, use global $ instead' );
629 return $.apply( this, arguments );
630 };
631 this.elementId = null;
632 this.visible = true;
633 this.data = config.data;
634 this.$element = config.$element ||
635 $( document.createElement( this.getTagName() ) );
636 this.elementGroup = null;
637
638 // Initialization
639 if ( Array.isArray( config.classes ) ) {
640 this.$element.addClass( config.classes );
641 }
642 if ( config.id ) {
643 this.setElementId( config.id );
644 }
645 if ( config.text ) {
646 this.$element.text( config.text );
647 }
648 if ( config.content ) {
649 // The `content` property treats plain strings as text; use an
650 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
651 // appropriate $element appended.
652 this.$element.append( config.content.map( function ( v ) {
653 if ( typeof v === 'string' ) {
654 // Escape string so it is properly represented in HTML.
655 return document.createTextNode( v );
656 } else if ( v instanceof OO.ui.HtmlSnippet ) {
657 // Bypass escaping.
658 return v.toString();
659 } else if ( v instanceof OO.ui.Element ) {
660 return v.$element;
661 }
662 return v;
663 } ) );
664 }
665 if ( config.$content ) {
666 // The `$content` property treats plain strings as HTML.
667 this.$element.append( config.$content );
668 }
669 };
670
671 /* Setup */
672
673 OO.initClass( OO.ui.Element );
674
675 /* Static Properties */
676
677 /**
678 * The name of the HTML tag used by the element.
679 *
680 * The static value may be ignored if the #getTagName method is overridden.
681 *
682 * @static
683 * @inheritable
684 * @property {string}
685 */
686 OO.ui.Element.static.tagName = 'div';
687
688 /* Static Methods */
689
690 /**
691 * Reconstitute a JavaScript object corresponding to a widget created
692 * by the PHP implementation.
693 *
694 * @param {string|HTMLElement|jQuery} idOrNode
695 * A DOM id (if a string) or node for the widget to infuse.
696 * @param {Object} [config] Configuration options
697 * @return {OO.ui.Element}
698 * The `OO.ui.Element` corresponding to this (infusable) document node.
699 * For `Tag` objects emitted on the HTML side (used occasionally for content)
700 * the value returned is a newly-created Element wrapping around the existing
701 * DOM node.
702 */
703 OO.ui.Element.static.infuse = function ( idOrNode, config ) {
704 var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, config, false );
705
706 if ( typeof idOrNode === 'string' ) {
707 // IDs deprecated since 0.29.7
708 OO.ui.warnDeprecation(
709 'Passing a string ID to infuse is deprecated. Use an HTMLElement or jQuery collection instead.'
710 );
711 }
712 // Verify that the type matches up.
713 // FIXME: uncomment after T89721 is fixed, see T90929.
714 /*
715 if ( !( obj instanceof this['class'] ) ) {
716 throw new Error( 'Infusion type mismatch!' );
717 }
718 */
719 return obj;
720 };
721
722 /**
723 * Implementation helper for `infuse`; skips the type check and has an
724 * extra property so that only the top-level invocation touches the DOM.
725 *
726 * @private
727 * @param {string|HTMLElement|jQuery} idOrNode
728 * @param {Object} [config] Configuration options
729 * @param {jQuery.Promise} [domPromise] A promise that will be resolved
730 * when the top-level widget of this infusion is inserted into DOM,
731 * replacing the original node; only used internally.
732 * @return {OO.ui.Element}
733 */
734 OO.ui.Element.static.unsafeInfuse = function ( idOrNode, config, domPromise ) {
735 // look for a cached result of a previous infusion.
736 var id, $elem, error, data, cls, parts, parent, obj, top, state, infusedChildren;
737 if ( typeof idOrNode === 'string' ) {
738 id = idOrNode;
739 $elem = $( document.getElementById( id ) );
740 } else {
741 $elem = $( idOrNode );
742 id = $elem.attr( 'id' );
743 }
744 if ( !$elem.length ) {
745 if ( typeof idOrNode === 'string' ) {
746 error = 'Widget not found: ' + idOrNode;
747 } else if ( idOrNode && idOrNode.selector ) {
748 error = 'Widget not found: ' + idOrNode.selector;
749 } else {
750 error = 'Widget not found';
751 }
752 throw new Error( error );
753 }
754 if ( $elem[ 0 ].oouiInfused ) {
755 $elem = $elem[ 0 ].oouiInfused;
756 }
757 data = $elem.data( 'ooui-infused' );
758 if ( data ) {
759 // cached!
760 if ( data === true ) {
761 throw new Error( 'Circular dependency! ' + id );
762 }
763 if ( domPromise ) {
764 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
765 state = data.constructor.static.gatherPreInfuseState( $elem, data );
766 // restore dynamic state after the new element is re-inserted into DOM under infused parent
767 domPromise.done( data.restorePreInfuseState.bind( data, state ) );
768 infusedChildren = $elem.data( 'ooui-infused-children' );
769 if ( infusedChildren && infusedChildren.length ) {
770 infusedChildren.forEach( function ( data ) {
771 var state = data.constructor.static.gatherPreInfuseState( $elem, data );
772 domPromise.done( data.restorePreInfuseState.bind( data, state ) );
773 } );
774 }
775 }
776 return data;
777 }
778 data = $elem.attr( 'data-ooui' );
779 if ( !data ) {
780 throw new Error( 'No infusion data found: ' + id );
781 }
782 try {
783 data = JSON.parse( data );
784 } catch ( _ ) {
785 data = null;
786 }
787 if ( !( data && data._ ) ) {
788 throw new Error( 'No valid infusion data found: ' + id );
789 }
790 if ( data._ === 'Tag' ) {
791 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
792 return new OO.ui.Element( $.extend( {}, config, { $element: $elem } ) );
793 }
794 parts = data._.split( '.' );
795 cls = OO.getProp.apply( OO, [ window ].concat( parts ) );
796 if ( cls === undefined ) {
797 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
798 }
799
800 // Verify that we're creating an OO.ui.Element instance
801 parent = cls.parent;
802
803 while ( parent !== undefined ) {
804 if ( parent === OO.ui.Element ) {
805 // Safe
806 break;
807 }
808
809 parent = parent.parent;
810 }
811
812 if ( parent !== OO.ui.Element ) {
813 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
814 }
815
816 if ( !domPromise ) {
817 top = $.Deferred();
818 domPromise = top.promise();
819 }
820 $elem.data( 'ooui-infused', true ); // prevent loops
821 data.id = id; // implicit
822 infusedChildren = [];
823 data = OO.copy( data, null, function deserialize( value ) {
824 var infused;
825 if ( OO.isPlainObject( value ) ) {
826 if ( value.tag ) {
827 infused = OO.ui.Element.static.unsafeInfuse( value.tag, config, domPromise );
828 infusedChildren.push( infused );
829 // Flatten the structure
830 infusedChildren.push.apply( infusedChildren, infused.$element.data( 'ooui-infused-children' ) || [] );
831 infused.$element.removeData( 'ooui-infused-children' );
832 return infused;
833 }
834 if ( value.html !== undefined ) {
835 return new OO.ui.HtmlSnippet( value.html );
836 }
837 }
838 } );
839 // allow widgets to reuse parts of the DOM
840 data = cls.static.reusePreInfuseDOM( $elem[ 0 ], data );
841 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
842 state = cls.static.gatherPreInfuseState( $elem[ 0 ], data );
843 // rebuild widget
844 // eslint-disable-next-line new-cap
845 obj = new cls( $.extend( {}, config, data ) );
846 // If anyone is holding a reference to the old DOM element,
847 // let's allow them to OO.ui.infuse() it and do what they expect, see T105828.
848 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
849 $elem[ 0 ].oouiInfused = obj.$element;
850 // now replace old DOM with this new DOM.
851 if ( top ) {
852 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
853 // so only mutate the DOM if we need to.
854 if ( $elem[ 0 ] !== obj.$element[ 0 ] ) {
855 $elem.replaceWith( obj.$element );
856 }
857 top.resolve();
858 }
859 obj.$element.data( 'ooui-infused', obj );
860 obj.$element.data( 'ooui-infused-children', infusedChildren );
861 // set the 'data-ooui' attribute so we can identify infused widgets
862 obj.$element.attr( 'data-ooui', '' );
863 // restore dynamic state after the new element is inserted into DOM
864 domPromise.done( obj.restorePreInfuseState.bind( obj, state ) );
865 return obj;
866 };
867
868 /**
869 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
870 *
871 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
872 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
873 * constructor, which will be given the enhanced config.
874 *
875 * @protected
876 * @param {HTMLElement} node
877 * @param {Object} config
878 * @return {Object}
879 */
880 OO.ui.Element.static.reusePreInfuseDOM = function ( node, config ) {
881 return config;
882 };
883
884 /**
885 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of an HTML DOM node
886 * (and its children) that represent an Element of the same class and the given configuration,
887 * generated by the PHP implementation.
888 *
889 * This method is called just before `node` is detached from the DOM. The return value of this
890 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
891 * is inserted into DOM to replace `node`.
892 *
893 * @protected
894 * @param {HTMLElement} node
895 * @param {Object} config
896 * @return {Object}
897 */
898 OO.ui.Element.static.gatherPreInfuseState = function () {
899 return {};
900 };
901
902 /**
903 * Get a jQuery function within a specific document.
904 *
905 * @static
906 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
907 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
908 * not in an iframe
909 * @return {Function} Bound jQuery function
910 */
911 OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
912 function wrapper( selector ) {
913 return $( selector, wrapper.context );
914 }
915
916 wrapper.context = this.getDocument( context );
917
918 if ( $iframe ) {
919 wrapper.$iframe = $iframe;
920 }
921
922 return wrapper;
923 };
924
925 /**
926 * Get the document of an element.
927 *
928 * @static
929 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
930 * @return {HTMLDocument|null} Document object
931 */
932 OO.ui.Element.static.getDocument = function ( obj ) {
933 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
934 return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
935 // Empty jQuery selections might have a context
936 obj.context ||
937 // HTMLElement
938 obj.ownerDocument ||
939 // Window
940 obj.document ||
941 // HTMLDocument
942 ( obj.nodeType === Node.DOCUMENT_NODE && obj ) ||
943 null;
944 };
945
946 /**
947 * Get the window of an element or document.
948 *
949 * @static
950 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
951 * @return {Window} Window object
952 */
953 OO.ui.Element.static.getWindow = function ( obj ) {
954 var doc = this.getDocument( obj );
955 return doc.defaultView;
956 };
957
958 /**
959 * Get the direction of an element or document.
960 *
961 * @static
962 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
963 * @return {string} Text direction, either 'ltr' or 'rtl'
964 */
965 OO.ui.Element.static.getDir = function ( obj ) {
966 var isDoc, isWin;
967
968 if ( obj instanceof $ ) {
969 obj = obj[ 0 ];
970 }
971 isDoc = obj.nodeType === Node.DOCUMENT_NODE;
972 isWin = obj.document !== undefined;
973 if ( isDoc || isWin ) {
974 if ( isWin ) {
975 obj = obj.document;
976 }
977 obj = obj.body;
978 }
979 return $( obj ).css( 'direction' );
980 };
981
982 /**
983 * Get the offset between two frames.
984 *
985 * TODO: Make this function not use recursion.
986 *
987 * @static
988 * @param {Window} from Window of the child frame
989 * @param {Window} [to=window] Window of the parent frame
990 * @param {Object} [offset] Offset to start with, used internally
991 * @return {Object} Offset object, containing left and top properties
992 */
993 OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
994 var i, len, frames, frame, rect;
995
996 if ( !to ) {
997 to = window;
998 }
999 if ( !offset ) {
1000 offset = { top: 0, left: 0 };
1001 }
1002 if ( from.parent === from ) {
1003 return offset;
1004 }
1005
1006 // Get iframe element
1007 frames = from.parent.document.getElementsByTagName( 'iframe' );
1008 for ( i = 0, len = frames.length; i < len; i++ ) {
1009 if ( frames[ i ].contentWindow === from ) {
1010 frame = frames[ i ];
1011 break;
1012 }
1013 }
1014
1015 // Recursively accumulate offset values
1016 if ( frame ) {
1017 rect = frame.getBoundingClientRect();
1018 offset.left += rect.left;
1019 offset.top += rect.top;
1020 if ( from !== to ) {
1021 this.getFrameOffset( from.parent, offset );
1022 }
1023 }
1024 return offset;
1025 };
1026
1027 /**
1028 * Get the offset between two elements.
1029 *
1030 * The two elements may be in a different frame, but in that case the frame $element is in must
1031 * be contained in the frame $anchor is in.
1032 *
1033 * @static
1034 * @param {jQuery} $element Element whose position to get
1035 * @param {jQuery} $anchor Element to get $element's position relative to
1036 * @return {Object} Translated position coordinates, containing top and left properties
1037 */
1038 OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
1039 var iframe, iframePos,
1040 pos = $element.offset(),
1041 anchorPos = $anchor.offset(),
1042 elementDocument = this.getDocument( $element ),
1043 anchorDocument = this.getDocument( $anchor );
1044
1045 // If $element isn't in the same document as $anchor, traverse up
1046 while ( elementDocument !== anchorDocument ) {
1047 iframe = elementDocument.defaultView.frameElement;
1048 if ( !iframe ) {
1049 throw new Error( '$element frame is not contained in $anchor frame' );
1050 }
1051 iframePos = $( iframe ).offset();
1052 pos.left += iframePos.left;
1053 pos.top += iframePos.top;
1054 elementDocument = iframe.ownerDocument;
1055 }
1056 pos.left -= anchorPos.left;
1057 pos.top -= anchorPos.top;
1058 return pos;
1059 };
1060
1061 /**
1062 * Get element border sizes.
1063 *
1064 * @static
1065 * @param {HTMLElement} el Element to measure
1066 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1067 */
1068 OO.ui.Element.static.getBorders = function ( el ) {
1069 var doc = el.ownerDocument,
1070 win = doc.defaultView,
1071 style = win.getComputedStyle( el, null ),
1072 $el = $( el ),
1073 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
1074 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
1075 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
1076 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
1077
1078 return {
1079 top: top,
1080 left: left,
1081 bottom: bottom,
1082 right: right
1083 };
1084 };
1085
1086 /**
1087 * Get dimensions of an element or window.
1088 *
1089 * @static
1090 * @param {HTMLElement|Window} el Element to measure
1091 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1092 */
1093 OO.ui.Element.static.getDimensions = function ( el ) {
1094 var $el, $win,
1095 doc = el.ownerDocument || el.document,
1096 win = doc.defaultView;
1097
1098 if ( win === el || el === doc.documentElement ) {
1099 $win = $( win );
1100 return {
1101 borders: { top: 0, left: 0, bottom: 0, right: 0 },
1102 scroll: {
1103 top: $win.scrollTop(),
1104 left: $win.scrollLeft()
1105 },
1106 scrollbar: { right: 0, bottom: 0 },
1107 rect: {
1108 top: 0,
1109 left: 0,
1110 bottom: $win.innerHeight(),
1111 right: $win.innerWidth()
1112 }
1113 };
1114 } else {
1115 $el = $( el );
1116 return {
1117 borders: this.getBorders( el ),
1118 scroll: {
1119 top: $el.scrollTop(),
1120 left: $el.scrollLeft()
1121 },
1122 scrollbar: {
1123 right: $el.innerWidth() - el.clientWidth,
1124 bottom: $el.innerHeight() - el.clientHeight
1125 },
1126 rect: el.getBoundingClientRect()
1127 };
1128 }
1129 };
1130
1131 /**
1132 * Get the number of pixels that an element's content is scrolled to the left.
1133 *
1134 * Adapted from <https://github.com/othree/jquery.rtl-scroll-type>.
1135 * Original code copyright 2012 Wei-Ko Kao, licensed under the MIT License.
1136 *
1137 * This function smooths out browser inconsistencies (nicely described in the README at
1138 * <https://github.com/othree/jquery.rtl-scroll-type>) and produces a result consistent
1139 * with Firefox's 'scrollLeft', which seems the sanest.
1140 *
1141 * @static
1142 * @method
1143 * @param {HTMLElement|Window} el Element to measure
1144 * @return {number} Scroll position from the left.
1145 * If the element's direction is LTR, this is a positive number between `0` (initial scroll position)
1146 * and `el.scrollWidth - el.clientWidth` (furthest possible scroll position).
1147 * If the element's direction is RTL, this is a negative number between `0` (initial scroll position)
1148 * and `-el.scrollWidth + el.clientWidth` (furthest possible scroll position).
1149 */
1150 OO.ui.Element.static.getScrollLeft = ( function () {
1151 var rtlScrollType = null;
1152
1153 function test() {
1154 var $definer = $( '<div>' ).attr( {
1155 dir: 'rtl',
1156 style: 'font-size: 14px; width: 4px; height: 1px; position: absolute; top: -1000px; overflow: scroll;'
1157 } ).text( 'ABCD' ),
1158 definer = $definer[ 0 ];
1159
1160 $definer.appendTo( 'body' );
1161 if ( definer.scrollLeft > 0 ) {
1162 // Safari, Chrome
1163 rtlScrollType = 'default';
1164 } else {
1165 definer.scrollLeft = 1;
1166 if ( definer.scrollLeft === 0 ) {
1167 // Firefox, old Opera
1168 rtlScrollType = 'negative';
1169 } else {
1170 // Internet Explorer, Edge
1171 rtlScrollType = 'reverse';
1172 }
1173 }
1174 $definer.remove();
1175 }
1176
1177 return function getScrollLeft( el ) {
1178 var isRoot = el.window === el ||
1179 el === el.ownerDocument.body ||
1180 el === el.ownerDocument.documentElement,
1181 scrollLeft = isRoot ? $( window ).scrollLeft() : el.scrollLeft,
1182 // All browsers use the correct scroll type ('negative') on the root, so don't
1183 // do any fixups when looking at the root element
1184 direction = isRoot ? 'ltr' : $( el ).css( 'direction' );
1185
1186 if ( direction === 'rtl' ) {
1187 if ( rtlScrollType === null ) {
1188 test();
1189 }
1190 if ( rtlScrollType === 'reverse' ) {
1191 scrollLeft = -scrollLeft;
1192 } else if ( rtlScrollType === 'default' ) {
1193 scrollLeft = scrollLeft - el.scrollWidth + el.clientWidth;
1194 }
1195 }
1196
1197 return scrollLeft;
1198 };
1199 }() );
1200
1201 /**
1202 * Get the root scrollable element of given element's document.
1203 *
1204 * On Blink-based browsers (Chrome etc.), `document.documentElement` can't be used to get or set
1205 * the scrollTop property; instead we have to use `document.body`. Changing and testing the value
1206 * lets us use 'body' or 'documentElement' based on what is working.
1207 *
1208 * https://code.google.com/p/chromium/issues/detail?id=303131
1209 *
1210 * @static
1211 * @param {HTMLElement} el Element to find root scrollable parent for
1212 * @return {HTMLElement} Scrollable parent, `document.body` or `document.documentElement`
1213 * depending on browser
1214 */
1215 OO.ui.Element.static.getRootScrollableElement = function ( el ) {
1216 var scrollTop, body;
1217
1218 if ( OO.ui.scrollableElement === undefined ) {
1219 body = el.ownerDocument.body;
1220 scrollTop = body.scrollTop;
1221 body.scrollTop = 1;
1222
1223 // In some browsers (observed in Chrome 56 on Linux Mint 18.1),
1224 // body.scrollTop doesn't become exactly 1, but a fractional value like 0.76
1225 if ( Math.round( body.scrollTop ) === 1 ) {
1226 body.scrollTop = scrollTop;
1227 OO.ui.scrollableElement = 'body';
1228 } else {
1229 OO.ui.scrollableElement = 'documentElement';
1230 }
1231 }
1232
1233 return el.ownerDocument[ OO.ui.scrollableElement ];
1234 };
1235
1236 /**
1237 * Get closest scrollable container.
1238 *
1239 * Traverses up until either a scrollable element or the root is reached, in which case the root
1240 * scrollable element will be returned (see #getRootScrollableElement).
1241 *
1242 * @static
1243 * @param {HTMLElement} el Element to find scrollable container for
1244 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1245 * @return {HTMLElement} Closest scrollable container
1246 */
1247 OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
1248 var i, val,
1249 // Browsers do not correctly return the computed value of 'overflow' when 'overflow-x' and
1250 // 'overflow-y' have different values, so we need to check the separate properties.
1251 props = [ 'overflow-x', 'overflow-y' ],
1252 $parent = $( el ).parent();
1253
1254 if ( dimension === 'x' || dimension === 'y' ) {
1255 props = [ 'overflow-' + dimension ];
1256 }
1257
1258 // Special case for the document root (which doesn't really have any scrollable container, since
1259 // it is the ultimate scrollable container, but this is probably saner than null or exception)
1260 if ( $( el ).is( 'html, body' ) ) {
1261 return this.getRootScrollableElement( el );
1262 }
1263
1264 while ( $parent.length ) {
1265 if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
1266 return $parent[ 0 ];
1267 }
1268 i = props.length;
1269 while ( i-- ) {
1270 val = $parent.css( props[ i ] );
1271 // We assume that elements with 'overflow' (in any direction) set to 'hidden' will never be
1272 // scrolled in that direction, but they can actually be scrolled programatically. The user can
1273 // unintentionally perform a scroll in such case even if the application doesn't scroll
1274 // programatically, e.g. when jumping to an anchor, or when using built-in find functionality.
1275 // This could cause funny issues...
1276 if ( val === 'auto' || val === 'scroll' ) {
1277 return $parent[ 0 ];
1278 }
1279 }
1280 $parent = $parent.parent();
1281 }
1282 // The element is unattached... return something mostly sane
1283 return this.getRootScrollableElement( el );
1284 };
1285
1286 /**
1287 * Scroll element into view.
1288 *
1289 * @static
1290 * @param {HTMLElement} el Element to scroll into view
1291 * @param {Object} [config] Configuration options
1292 * @param {string} [config.duration='fast'] jQuery animation duration value
1293 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1294 * to scroll in both directions
1295 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1296 */
1297 OO.ui.Element.static.scrollIntoView = function ( el, config ) {
1298 var position, animations, container, $container, elementDimensions, containerDimensions, $window,
1299 deferred = $.Deferred();
1300
1301 // Configuration initialization
1302 config = config || {};
1303
1304 animations = {};
1305 container = this.getClosestScrollableContainer( el, config.direction );
1306 $container = $( container );
1307 elementDimensions = this.getDimensions( el );
1308 containerDimensions = this.getDimensions( container );
1309 $window = $( this.getWindow( el ) );
1310
1311 // Compute the element's position relative to the container
1312 if ( $container.is( 'html, body' ) ) {
1313 // If the scrollable container is the root, this is easy
1314 position = {
1315 top: elementDimensions.rect.top,
1316 bottom: $window.innerHeight() - elementDimensions.rect.bottom,
1317 left: elementDimensions.rect.left,
1318 right: $window.innerWidth() - elementDimensions.rect.right
1319 };
1320 } else {
1321 // Otherwise, we have to subtract el's coordinates from container's coordinates
1322 position = {
1323 top: elementDimensions.rect.top - ( containerDimensions.rect.top + containerDimensions.borders.top ),
1324 bottom: containerDimensions.rect.bottom - containerDimensions.borders.bottom - containerDimensions.scrollbar.bottom - elementDimensions.rect.bottom,
1325 left: elementDimensions.rect.left - ( containerDimensions.rect.left + containerDimensions.borders.left ),
1326 right: containerDimensions.rect.right - containerDimensions.borders.right - containerDimensions.scrollbar.right - elementDimensions.rect.right
1327 };
1328 }
1329
1330 if ( !config.direction || config.direction === 'y' ) {
1331 if ( position.top < 0 ) {
1332 animations.scrollTop = containerDimensions.scroll.top + position.top;
1333 } else if ( position.top > 0 && position.bottom < 0 ) {
1334 animations.scrollTop = containerDimensions.scroll.top + Math.min( position.top, -position.bottom );
1335 }
1336 }
1337 if ( !config.direction || config.direction === 'x' ) {
1338 if ( position.left < 0 ) {
1339 animations.scrollLeft = containerDimensions.scroll.left + position.left;
1340 } else if ( position.left > 0 && position.right < 0 ) {
1341 animations.scrollLeft = containerDimensions.scroll.left + Math.min( position.left, -position.right );
1342 }
1343 }
1344 if ( !$.isEmptyObject( animations ) ) {
1345 // eslint-disable-next-line jquery/no-animate
1346 $container.stop( true ).animate( animations, config.duration === undefined ? 'fast' : config.duration );
1347 $container.queue( function ( next ) {
1348 deferred.resolve();
1349 next();
1350 } );
1351 } else {
1352 deferred.resolve();
1353 }
1354 return deferred.promise();
1355 };
1356
1357 /**
1358 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1359 * and reserve space for them, because it probably doesn't.
1360 *
1361 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1362 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1363 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1364 * and then reattach (or show) them back.
1365 *
1366 * @static
1367 * @param {HTMLElement} el Element to reconsider the scrollbars on
1368 */
1369 OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
1370 var i, len, scrollLeft, scrollTop, nodes = [];
1371 // Save scroll position
1372 scrollLeft = el.scrollLeft;
1373 scrollTop = el.scrollTop;
1374 // Detach all children
1375 while ( el.firstChild ) {
1376 nodes.push( el.firstChild );
1377 el.removeChild( el.firstChild );
1378 }
1379 // Force reflow
1380 // eslint-disable-next-line no-void
1381 void el.offsetHeight;
1382 // Reattach all children
1383 for ( i = 0, len = nodes.length; i < len; i++ ) {
1384 el.appendChild( nodes[ i ] );
1385 }
1386 // Restore scroll position (no-op if scrollbars disappeared)
1387 el.scrollLeft = scrollLeft;
1388 el.scrollTop = scrollTop;
1389 };
1390
1391 /* Methods */
1392
1393 /**
1394 * Toggle visibility of an element.
1395 *
1396 * @param {boolean} [show] Make element visible, omit to toggle visibility
1397 * @fires visible
1398 * @chainable
1399 * @return {OO.ui.Element} The element, for chaining
1400 */
1401 OO.ui.Element.prototype.toggle = function ( show ) {
1402 show = show === undefined ? !this.visible : !!show;
1403
1404 if ( show !== this.isVisible() ) {
1405 this.visible = show;
1406 this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
1407 this.emit( 'toggle', show );
1408 }
1409
1410 return this;
1411 };
1412
1413 /**
1414 * Check if element is visible.
1415 *
1416 * @return {boolean} element is visible
1417 */
1418 OO.ui.Element.prototype.isVisible = function () {
1419 return this.visible;
1420 };
1421
1422 /**
1423 * Get element data.
1424 *
1425 * @return {Mixed} Element data
1426 */
1427 OO.ui.Element.prototype.getData = function () {
1428 return this.data;
1429 };
1430
1431 /**
1432 * Set element data.
1433 *
1434 * @param {Mixed} data Element data
1435 * @chainable
1436 * @return {OO.ui.Element} The element, for chaining
1437 */
1438 OO.ui.Element.prototype.setData = function ( data ) {
1439 this.data = data;
1440 return this;
1441 };
1442
1443 /**
1444 * Set the element has an 'id' attribute.
1445 *
1446 * @param {string} id
1447 * @chainable
1448 * @return {OO.ui.Element} The element, for chaining
1449 */
1450 OO.ui.Element.prototype.setElementId = function ( id ) {
1451 this.elementId = id;
1452 this.$element.attr( 'id', id );
1453 return this;
1454 };
1455
1456 /**
1457 * Ensure that the element has an 'id' attribute, setting it to an unique value if it's missing,
1458 * and return its value.
1459 *
1460 * @return {string}
1461 */
1462 OO.ui.Element.prototype.getElementId = function () {
1463 if ( this.elementId === null ) {
1464 this.setElementId( OO.ui.generateElementId() );
1465 }
1466 return this.elementId;
1467 };
1468
1469 /**
1470 * Check if element supports one or more methods.
1471 *
1472 * @param {string|string[]} methods Method or list of methods to check
1473 * @return {boolean} All methods are supported
1474 */
1475 OO.ui.Element.prototype.supports = function ( methods ) {
1476 var i, len,
1477 support = 0;
1478
1479 methods = Array.isArray( methods ) ? methods : [ methods ];
1480 for ( i = 0, len = methods.length; i < len; i++ ) {
1481 if ( typeof this[ methods[ i ] ] === 'function' ) {
1482 support++;
1483 }
1484 }
1485
1486 return methods.length === support;
1487 };
1488
1489 /**
1490 * Update the theme-provided classes.
1491 *
1492 * @localdoc This is called in element mixins and widget classes any time state changes.
1493 * Updating is debounced, minimizing overhead of changing multiple attributes and
1494 * guaranteeing that theme updates do not occur within an element's constructor
1495 */
1496 OO.ui.Element.prototype.updateThemeClasses = function () {
1497 OO.ui.theme.queueUpdateElementClasses( this );
1498 };
1499
1500 /**
1501 * Get the HTML tag name.
1502 *
1503 * Override this method to base the result on instance information.
1504 *
1505 * @return {string} HTML tag name
1506 */
1507 OO.ui.Element.prototype.getTagName = function () {
1508 return this.constructor.static.tagName;
1509 };
1510
1511 /**
1512 * Check if the element is attached to the DOM
1513 *
1514 * @return {boolean} The element is attached to the DOM
1515 */
1516 OO.ui.Element.prototype.isElementAttached = function () {
1517 return $.contains( this.getElementDocument(), this.$element[ 0 ] );
1518 };
1519
1520 /**
1521 * Get the DOM document.
1522 *
1523 * @return {HTMLDocument} Document object
1524 */
1525 OO.ui.Element.prototype.getElementDocument = function () {
1526 // Don't cache this in other ways either because subclasses could can change this.$element
1527 return OO.ui.Element.static.getDocument( this.$element );
1528 };
1529
1530 /**
1531 * Get the DOM window.
1532 *
1533 * @return {Window} Window object
1534 */
1535 OO.ui.Element.prototype.getElementWindow = function () {
1536 return OO.ui.Element.static.getWindow( this.$element );
1537 };
1538
1539 /**
1540 * Get closest scrollable container.
1541 *
1542 * @return {HTMLElement} Closest scrollable container
1543 */
1544 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1545 return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
1546 };
1547
1548 /**
1549 * Get group element is in.
1550 *
1551 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1552 */
1553 OO.ui.Element.prototype.getElementGroup = function () {
1554 return this.elementGroup;
1555 };
1556
1557 /**
1558 * Set group element is in.
1559 *
1560 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1561 * @chainable
1562 * @return {OO.ui.Element} The element, for chaining
1563 */
1564 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1565 this.elementGroup = group;
1566 return this;
1567 };
1568
1569 /**
1570 * Scroll element into view.
1571 *
1572 * @param {Object} [config] Configuration options
1573 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1574 */
1575 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
1576 if (
1577 !this.isElementAttached() ||
1578 !this.isVisible() ||
1579 ( this.getElementGroup() && !this.getElementGroup().isVisible() )
1580 ) {
1581 return $.Deferred().resolve();
1582 }
1583 return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
1584 };
1585
1586 /**
1587 * Restore the pre-infusion dynamic state for this widget.
1588 *
1589 * This method is called after #$element has been inserted into DOM. The parameter is the return
1590 * value of #gatherPreInfuseState.
1591 *
1592 * @protected
1593 * @param {Object} state
1594 */
1595 OO.ui.Element.prototype.restorePreInfuseState = function () {
1596 };
1597
1598 /**
1599 * Wraps an HTML snippet for use with configuration values which default
1600 * to strings. This bypasses the default html-escaping done to string
1601 * values.
1602 *
1603 * @class
1604 *
1605 * @constructor
1606 * @param {string} [content] HTML content
1607 */
1608 OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
1609 // Properties
1610 this.content = content;
1611 };
1612
1613 /* Setup */
1614
1615 OO.initClass( OO.ui.HtmlSnippet );
1616
1617 /* Methods */
1618
1619 /**
1620 * Render into HTML.
1621 *
1622 * @return {string} Unchanged HTML snippet.
1623 */
1624 OO.ui.HtmlSnippet.prototype.toString = function () {
1625 return this.content;
1626 };
1627
1628 /**
1629 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1630 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1631 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1632 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1633 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1634 *
1635 * @abstract
1636 * @class
1637 * @extends OO.ui.Element
1638 * @mixins OO.EventEmitter
1639 *
1640 * @constructor
1641 * @param {Object} [config] Configuration options
1642 */
1643 OO.ui.Layout = function OoUiLayout( config ) {
1644 // Configuration initialization
1645 config = config || {};
1646
1647 // Parent constructor
1648 OO.ui.Layout.parent.call( this, config );
1649
1650 // Mixin constructors
1651 OO.EventEmitter.call( this );
1652
1653 // Initialization
1654 this.$element.addClass( 'oo-ui-layout' );
1655 };
1656
1657 /* Setup */
1658
1659 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1660 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1661
1662 /* Methods */
1663
1664 /**
1665 * Reset scroll offsets
1666 *
1667 * @chainable
1668 * @return {OO.ui.Layout} The layout, for chaining
1669 */
1670 OO.ui.Layout.prototype.resetScroll = function () {
1671 this.$element[ 0 ].scrollTop = 0;
1672 // TODO: Reset scrollLeft in an RTL-aware manner, see OO.ui.Element.static.getScrollLeft.
1673
1674 return this;
1675 };
1676
1677 /**
1678 * Widgets are compositions of one or more OOUI elements that users can both view
1679 * and interact with. All widgets can be configured and modified via a standard API,
1680 * and their state can change dynamically according to a model.
1681 *
1682 * @abstract
1683 * @class
1684 * @extends OO.ui.Element
1685 * @mixins OO.EventEmitter
1686 *
1687 * @constructor
1688 * @param {Object} [config] Configuration options
1689 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1690 * appearance reflects this state.
1691 */
1692 OO.ui.Widget = function OoUiWidget( config ) {
1693 // Initialize config
1694 config = $.extend( { disabled: false }, config );
1695
1696 // Parent constructor
1697 OO.ui.Widget.parent.call( this, config );
1698
1699 // Mixin constructors
1700 OO.EventEmitter.call( this );
1701
1702 // Properties
1703 this.disabled = null;
1704 this.wasDisabled = null;
1705
1706 // Initialization
1707 this.$element.addClass( 'oo-ui-widget' );
1708 this.setDisabled( !!config.disabled );
1709 };
1710
1711 /* Setup */
1712
1713 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
1714 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
1715
1716 /* Events */
1717
1718 /**
1719 * @event disable
1720 *
1721 * A 'disable' event is emitted when the disabled state of the widget changes
1722 * (i.e. on disable **and** enable).
1723 *
1724 * @param {boolean} disabled Widget is disabled
1725 */
1726
1727 /**
1728 * @event toggle
1729 *
1730 * A 'toggle' event is emitted when the visibility of the widget changes.
1731 *
1732 * @param {boolean} visible Widget is visible
1733 */
1734
1735 /* Methods */
1736
1737 /**
1738 * Check if the widget is disabled.
1739 *
1740 * @return {boolean} Widget is disabled
1741 */
1742 OO.ui.Widget.prototype.isDisabled = function () {
1743 return this.disabled;
1744 };
1745
1746 /**
1747 * Set the 'disabled' state of the widget.
1748 *
1749 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1750 *
1751 * @param {boolean} disabled Disable widget
1752 * @chainable
1753 * @return {OO.ui.Widget} The widget, for chaining
1754 */
1755 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
1756 var isDisabled;
1757
1758 this.disabled = !!disabled;
1759 isDisabled = this.isDisabled();
1760 if ( isDisabled !== this.wasDisabled ) {
1761 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
1762 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
1763 this.$element.attr( 'aria-disabled', isDisabled.toString() );
1764 this.emit( 'disable', isDisabled );
1765 this.updateThemeClasses();
1766 }
1767 this.wasDisabled = isDisabled;
1768
1769 return this;
1770 };
1771
1772 /**
1773 * Update the disabled state, in case of changes in parent widget.
1774 *
1775 * @chainable
1776 * @return {OO.ui.Widget} The widget, for chaining
1777 */
1778 OO.ui.Widget.prototype.updateDisabled = function () {
1779 this.setDisabled( this.disabled );
1780 return this;
1781 };
1782
1783 /**
1784 * Get an ID of a labelable node which is part of this widget, if any, to be used for `<label for>`
1785 * value.
1786 *
1787 * If this function returns null, the widget should have a meaningful #simulateLabelClick method
1788 * instead.
1789 *
1790 * @return {string|null} The ID of the labelable element
1791 */
1792 OO.ui.Widget.prototype.getInputId = function () {
1793 return null;
1794 };
1795
1796 /**
1797 * Simulate the behavior of clicking on a label (a HTML `<label>` element) bound to this input.
1798 * HTML only allows `<label>` to act on specific "labelable" elements; complex widgets might need to
1799 * override this method to provide intuitive, accessible behavior.
1800 *
1801 * By default, this does nothing. OO.ui.mixin.TabIndexedElement overrides it for focusable widgets.
1802 * Individual widgets may override it too.
1803 *
1804 * This method is called by OO.ui.LabelWidget and OO.ui.FieldLayout. It should not be called
1805 * directly.
1806 */
1807 OO.ui.Widget.prototype.simulateLabelClick = function () {
1808 };
1809
1810 /**
1811 * Theme logic.
1812 *
1813 * @abstract
1814 * @class
1815 *
1816 * @constructor
1817 */
1818 OO.ui.Theme = function OoUiTheme() {
1819 this.elementClassesQueue = [];
1820 this.debouncedUpdateQueuedElementClasses = OO.ui.debounce( this.updateQueuedElementClasses );
1821 };
1822
1823 /* Setup */
1824
1825 OO.initClass( OO.ui.Theme );
1826
1827 /* Methods */
1828
1829 /**
1830 * Get a list of classes to be applied to a widget.
1831 *
1832 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
1833 * otherwise state transitions will not work properly.
1834 *
1835 * @param {OO.ui.Element} element Element for which to get classes
1836 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1837 */
1838 OO.ui.Theme.prototype.getElementClasses = function () {
1839 return { on: [], off: [] };
1840 };
1841
1842 /**
1843 * Update CSS classes provided by the theme.
1844 *
1845 * For elements with theme logic hooks, this should be called any time there's a state change.
1846 *
1847 * @param {OO.ui.Element} element Element for which to update classes
1848 */
1849 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
1850 var $elements = $( [] ),
1851 classes = this.getElementClasses( element );
1852
1853 if ( element.$icon ) {
1854 $elements = $elements.add( element.$icon );
1855 }
1856 if ( element.$indicator ) {
1857 $elements = $elements.add( element.$indicator );
1858 }
1859
1860 $elements
1861 .removeClass( classes.off )
1862 .addClass( classes.on );
1863 };
1864
1865 /**
1866 * @private
1867 */
1868 OO.ui.Theme.prototype.updateQueuedElementClasses = function () {
1869 var i;
1870 for ( i = 0; i < this.elementClassesQueue.length; i++ ) {
1871 this.updateElementClasses( this.elementClassesQueue[ i ] );
1872 }
1873 // Clear the queue
1874 this.elementClassesQueue = [];
1875 };
1876
1877 /**
1878 * Queue #updateElementClasses to be called for this element.
1879 *
1880 * @localdoc QUnit tests override this method to directly call #queueUpdateElementClasses,
1881 * to make them synchronous.
1882 *
1883 * @param {OO.ui.Element} element Element for which to update classes
1884 */
1885 OO.ui.Theme.prototype.queueUpdateElementClasses = function ( element ) {
1886 // Keep items in the queue unique. Use lastIndexOf to start checking from the end because that's
1887 // the most common case (this method is often called repeatedly for the same element).
1888 if ( this.elementClassesQueue.lastIndexOf( element ) !== -1 ) {
1889 return;
1890 }
1891 this.elementClassesQueue.push( element );
1892 this.debouncedUpdateQueuedElementClasses();
1893 };
1894
1895 /**
1896 * Get the transition duration in milliseconds for dialogs opening/closing
1897 *
1898 * The dialog should be fully rendered this many milliseconds after the
1899 * ready process has executed.
1900 *
1901 * @return {number} Transition duration in milliseconds
1902 */
1903 OO.ui.Theme.prototype.getDialogTransitionDuration = function () {
1904 return 0;
1905 };
1906
1907 /**
1908 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
1909 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
1910 * order in which users will navigate through the focusable elements via the “tab” key.
1911 *
1912 * @example
1913 * // TabIndexedElement is mixed into the ButtonWidget class
1914 * // to provide a tabIndex property.
1915 * var button1 = new OO.ui.ButtonWidget( {
1916 * label: 'fourth',
1917 * tabIndex: 4
1918 * } ),
1919 * button2 = new OO.ui.ButtonWidget( {
1920 * label: 'second',
1921 * tabIndex: 2
1922 * } ),
1923 * button3 = new OO.ui.ButtonWidget( {
1924 * label: 'third',
1925 * tabIndex: 3
1926 * } ),
1927 * button4 = new OO.ui.ButtonWidget( {
1928 * label: 'first',
1929 * tabIndex: 1
1930 * } );
1931 * $( document.body ).append( button1.$element, button2.$element, button3.$element, button4.$element );
1932 *
1933 * @abstract
1934 * @class
1935 *
1936 * @constructor
1937 * @param {Object} [config] Configuration options
1938 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
1939 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
1940 * functionality will be applied to it instead.
1941 * @cfg {string|number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
1942 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
1943 * to remove the element from the tab-navigation flow.
1944 */
1945 OO.ui.mixin.TabIndexedElement = function OoUiMixinTabIndexedElement( config ) {
1946 // Configuration initialization
1947 config = $.extend( { tabIndex: 0 }, config );
1948
1949 // Properties
1950 this.$tabIndexed = null;
1951 this.tabIndex = null;
1952
1953 // Events
1954 this.connect( this, { disable: 'onTabIndexedElementDisable' } );
1955
1956 // Initialization
1957 this.setTabIndex( config.tabIndex );
1958 this.setTabIndexedElement( config.$tabIndexed || this.$element );
1959 };
1960
1961 /* Setup */
1962
1963 OO.initClass( OO.ui.mixin.TabIndexedElement );
1964
1965 /* Methods */
1966
1967 /**
1968 * Set the element that should use the tabindex functionality.
1969 *
1970 * This method is used to retarget a tabindex mixin so that its functionality applies
1971 * to the specified element. If an element is currently using the functionality, the mixin’s
1972 * effect on that element is removed before the new element is set up.
1973 *
1974 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
1975 * @chainable
1976 * @return {OO.ui.Element} The element, for chaining
1977 */
1978 OO.ui.mixin.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
1979 var tabIndex = this.tabIndex;
1980 // Remove attributes from old $tabIndexed
1981 this.setTabIndex( null );
1982 // Force update of new $tabIndexed
1983 this.$tabIndexed = $tabIndexed;
1984 this.tabIndex = tabIndex;
1985 return this.updateTabIndex();
1986 };
1987
1988 /**
1989 * Set the value of the tabindex.
1990 *
1991 * @param {string|number|null} tabIndex Tabindex value, or `null` for no tabindex
1992 * @chainable
1993 * @return {OO.ui.Element} The element, for chaining
1994 */
1995 OO.ui.mixin.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
1996 tabIndex = /^-?\d+$/.test( tabIndex ) ? Number( tabIndex ) : null;
1997
1998 if ( this.tabIndex !== tabIndex ) {
1999 this.tabIndex = tabIndex;
2000 this.updateTabIndex();
2001 }
2002
2003 return this;
2004 };
2005
2006 /**
2007 * Update the `tabindex` attribute, in case of changes to tab index or
2008 * disabled state.
2009 *
2010 * @private
2011 * @chainable
2012 * @return {OO.ui.Element} The element, for chaining
2013 */
2014 OO.ui.mixin.TabIndexedElement.prototype.updateTabIndex = function () {
2015 if ( this.$tabIndexed ) {
2016 if ( this.tabIndex !== null ) {
2017 // Do not index over disabled elements
2018 this.$tabIndexed.attr( {
2019 tabindex: this.isDisabled() ? -1 : this.tabIndex,
2020 // Support: ChromeVox and NVDA
2021 // These do not seem to inherit aria-disabled from parent elements
2022 'aria-disabled': this.isDisabled().toString()
2023 } );
2024 } else {
2025 this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
2026 }
2027 }
2028 return this;
2029 };
2030
2031 /**
2032 * Handle disable events.
2033 *
2034 * @private
2035 * @param {boolean} disabled Element is disabled
2036 */
2037 OO.ui.mixin.TabIndexedElement.prototype.onTabIndexedElementDisable = function () {
2038 this.updateTabIndex();
2039 };
2040
2041 /**
2042 * Get the value of the tabindex.
2043 *
2044 * @return {number|null} Tabindex value
2045 */
2046 OO.ui.mixin.TabIndexedElement.prototype.getTabIndex = function () {
2047 return this.tabIndex;
2048 };
2049
2050 /**
2051 * Get an ID of a focusable element of this widget, if any, to be used for `<label for>` value.
2052 *
2053 * If the element already has an ID then that is returned, otherwise unique ID is
2054 * generated, set on the element, and returned.
2055 *
2056 * @return {string|null} The ID of the focusable element
2057 */
2058 OO.ui.mixin.TabIndexedElement.prototype.getInputId = function () {
2059 var id;
2060
2061 if ( !this.$tabIndexed ) {
2062 return null;
2063 }
2064 if ( !this.isLabelableNode( this.$tabIndexed ) ) {
2065 return null;
2066 }
2067
2068 id = this.$tabIndexed.attr( 'id' );
2069 if ( id === undefined ) {
2070 id = OO.ui.generateElementId();
2071 this.$tabIndexed.attr( 'id', id );
2072 }
2073
2074 return id;
2075 };
2076
2077 /**
2078 * Whether the node is 'labelable' according to the HTML spec
2079 * (i.e., whether it can be interacted with through a `<label for="…">`).
2080 * See: <https://html.spec.whatwg.org/multipage/forms.html#category-label>.
2081 *
2082 * @private
2083 * @param {jQuery} $node
2084 * @return {boolean}
2085 */
2086 OO.ui.mixin.TabIndexedElement.prototype.isLabelableNode = function ( $node ) {
2087 var
2088 labelableTags = [ 'button', 'meter', 'output', 'progress', 'select', 'textarea' ],
2089 tagName = $node.prop( 'tagName' ).toLowerCase();
2090
2091 if ( tagName === 'input' && $node.attr( 'type' ) !== 'hidden' ) {
2092 return true;
2093 }
2094 if ( labelableTags.indexOf( tagName ) !== -1 ) {
2095 return true;
2096 }
2097 return false;
2098 };
2099
2100 /**
2101 * Focus this element.
2102 *
2103 * @chainable
2104 * @return {OO.ui.Element} The element, for chaining
2105 */
2106 OO.ui.mixin.TabIndexedElement.prototype.focus = function () {
2107 if ( !this.isDisabled() ) {
2108 this.$tabIndexed.trigger( 'focus' );
2109 }
2110 return this;
2111 };
2112
2113 /**
2114 * Blur this element.
2115 *
2116 * @chainable
2117 * @return {OO.ui.Element} The element, for chaining
2118 */
2119 OO.ui.mixin.TabIndexedElement.prototype.blur = function () {
2120 this.$tabIndexed.trigger( 'blur' );
2121 return this;
2122 };
2123
2124 /**
2125 * @inheritdoc OO.ui.Widget
2126 */
2127 OO.ui.mixin.TabIndexedElement.prototype.simulateLabelClick = function () {
2128 this.focus();
2129 };
2130
2131 /**
2132 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
2133 * interface element that can be configured with access keys for keyboard interaction.
2134 * See the [OOUI documentation on MediaWiki] [1] for examples.
2135 *
2136 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches#Buttons
2137 *
2138 * @abstract
2139 * @class
2140 *
2141 * @constructor
2142 * @param {Object} [config] Configuration options
2143 * @cfg {jQuery} [$button] The button element created by the class.
2144 * If this configuration is omitted, the button element will use a generated `<a>`.
2145 * @cfg {boolean} [framed=true] Render the button with a frame
2146 */
2147 OO.ui.mixin.ButtonElement = function OoUiMixinButtonElement( config ) {
2148 // Configuration initialization
2149 config = config || {};
2150
2151 // Properties
2152 this.$button = null;
2153 this.framed = null;
2154 this.active = config.active !== undefined && config.active;
2155 this.onDocumentMouseUpHandler = this.onDocumentMouseUp.bind( this );
2156 this.onMouseDownHandler = this.onMouseDown.bind( this );
2157 this.onDocumentKeyUpHandler = this.onDocumentKeyUp.bind( this );
2158 this.onKeyDownHandler = this.onKeyDown.bind( this );
2159 this.onClickHandler = this.onClick.bind( this );
2160 this.onKeyPressHandler = this.onKeyPress.bind( this );
2161
2162 // Initialization
2163 this.$element.addClass( 'oo-ui-buttonElement' );
2164 this.toggleFramed( config.framed === undefined || config.framed );
2165 this.setButtonElement( config.$button || $( '<a>' ) );
2166 };
2167
2168 /* Setup */
2169
2170 OO.initClass( OO.ui.mixin.ButtonElement );
2171
2172 /* Static Properties */
2173
2174 /**
2175 * Cancel mouse down events.
2176 *
2177 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
2178 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
2179 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
2180 * parent widget.
2181 *
2182 * @static
2183 * @inheritable
2184 * @property {boolean}
2185 */
2186 OO.ui.mixin.ButtonElement.static.cancelButtonMouseDownEvents = true;
2187
2188 /* Events */
2189
2190 /**
2191 * A 'click' event is emitted when the button element is clicked.
2192 *
2193 * @event click
2194 */
2195
2196 /* Methods */
2197
2198 /**
2199 * Set the button element.
2200 *
2201 * This method is used to retarget a button mixin so that its functionality applies to
2202 * the specified button element instead of the one created by the class. If a button element
2203 * is already set, the method will remove the mixin’s effect on that element.
2204 *
2205 * @param {jQuery} $button Element to use as button
2206 */
2207 OO.ui.mixin.ButtonElement.prototype.setButtonElement = function ( $button ) {
2208 if ( this.$button ) {
2209 this.$button
2210 .removeClass( 'oo-ui-buttonElement-button' )
2211 .removeAttr( 'role accesskey' )
2212 .off( {
2213 mousedown: this.onMouseDownHandler,
2214 keydown: this.onKeyDownHandler,
2215 click: this.onClickHandler,
2216 keypress: this.onKeyPressHandler
2217 } );
2218 }
2219
2220 this.$button = $button
2221 .addClass( 'oo-ui-buttonElement-button' )
2222 .on( {
2223 mousedown: this.onMouseDownHandler,
2224 keydown: this.onKeyDownHandler,
2225 click: this.onClickHandler,
2226 keypress: this.onKeyPressHandler
2227 } );
2228
2229 // Add `role="button"` on `<a>` elements, where it's needed
2230 // `toUpperCase()` is added for XHTML documents
2231 if ( this.$button.prop( 'tagName' ).toUpperCase() === 'A' ) {
2232 this.$button.attr( 'role', 'button' );
2233 }
2234 };
2235
2236 /**
2237 * Handles mouse down events.
2238 *
2239 * @protected
2240 * @param {jQuery.Event} e Mouse down event
2241 * @return {undefined/boolean} False to prevent default if event is handled
2242 */
2243 OO.ui.mixin.ButtonElement.prototype.onMouseDown = function ( e ) {
2244 if ( this.isDisabled() || e.which !== OO.ui.MouseButtons.LEFT ) {
2245 return;
2246 }
2247 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
2248 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
2249 // reliably remove the pressed class
2250 this.getElementDocument().addEventListener( 'mouseup', this.onDocumentMouseUpHandler, true );
2251 // Prevent change of focus unless specifically configured otherwise
2252 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
2253 return false;
2254 }
2255 };
2256
2257 /**
2258 * Handles document mouse up events.
2259 *
2260 * @protected
2261 * @param {MouseEvent} e Mouse up event
2262 */
2263 OO.ui.mixin.ButtonElement.prototype.onDocumentMouseUp = function ( e ) {
2264 if ( this.isDisabled() || e.which !== OO.ui.MouseButtons.LEFT ) {
2265 return;
2266 }
2267 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
2268 // Stop listening for mouseup, since we only needed this once
2269 this.getElementDocument().removeEventListener( 'mouseup', this.onDocumentMouseUpHandler, true );
2270 };
2271
2272 // Deprecated alias since 0.28.3
2273 OO.ui.mixin.ButtonElement.prototype.onMouseUp = function () {
2274 OO.ui.warnDeprecation( 'onMouseUp is deprecated, use onDocumentMouseUp instead' );
2275 this.onDocumentMouseUp.apply( this, arguments );
2276 };
2277
2278 /**
2279 * Handles mouse click events.
2280 *
2281 * @protected
2282 * @param {jQuery.Event} e Mouse click event
2283 * @fires click
2284 * @return {undefined/boolean} False to prevent default if event is handled
2285 */
2286 OO.ui.mixin.ButtonElement.prototype.onClick = function ( e ) {
2287 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
2288 if ( this.emit( 'click' ) ) {
2289 return false;
2290 }
2291 }
2292 };
2293
2294 /**
2295 * Handles key down events.
2296 *
2297 * @protected
2298 * @param {jQuery.Event} e Key down event
2299 */
2300 OO.ui.mixin.ButtonElement.prototype.onKeyDown = function ( e ) {
2301 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
2302 return;
2303 }
2304 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
2305 // Run the keyup handler no matter where the key is when the button is let go, so we can
2306 // reliably remove the pressed class
2307 this.getElementDocument().addEventListener( 'keyup', this.onDocumentKeyUpHandler, true );
2308 };
2309
2310 /**
2311 * Handles document key up events.
2312 *
2313 * @protected
2314 * @param {KeyboardEvent} e Key up event
2315 */
2316 OO.ui.mixin.ButtonElement.prototype.onDocumentKeyUp = function ( e ) {
2317 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
2318 return;
2319 }
2320 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
2321 // Stop listening for keyup, since we only needed this once
2322 this.getElementDocument().removeEventListener( 'keyup', this.onDocumentKeyUpHandler, true );
2323 };
2324
2325 // Deprecated alias since 0.28.3
2326 OO.ui.mixin.ButtonElement.prototype.onKeyUp = function () {
2327 OO.ui.warnDeprecation( 'onKeyUp is deprecated, use onDocumentKeyUp instead' );
2328 this.onDocumentKeyUp.apply( this, arguments );
2329 };
2330
2331 /**
2332 * Handles key press events.
2333 *
2334 * @protected
2335 * @param {jQuery.Event} e Key press event
2336 * @fires click
2337 * @return {undefined/boolean} False to prevent default if event is handled
2338 */
2339 OO.ui.mixin.ButtonElement.prototype.onKeyPress = function ( e ) {
2340 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
2341 if ( this.emit( 'click' ) ) {
2342 return false;
2343 }
2344 }
2345 };
2346
2347 /**
2348 * Check if button has a frame.
2349 *
2350 * @return {boolean} Button is framed
2351 */
2352 OO.ui.mixin.ButtonElement.prototype.isFramed = function () {
2353 return this.framed;
2354 };
2355
2356 /**
2357 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
2358 *
2359 * @param {boolean} [framed] Make button framed, omit to toggle
2360 * @chainable
2361 * @return {OO.ui.Element} The element, for chaining
2362 */
2363 OO.ui.mixin.ButtonElement.prototype.toggleFramed = function ( framed ) {
2364 framed = framed === undefined ? !this.framed : !!framed;
2365 if ( framed !== this.framed ) {
2366 this.framed = framed;
2367 this.$element
2368 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
2369 .toggleClass( 'oo-ui-buttonElement-framed', framed );
2370 this.updateThemeClasses();
2371 }
2372
2373 return this;
2374 };
2375
2376 /**
2377 * Set the button's active state.
2378 *
2379 * The active state can be set on:
2380 *
2381 * - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected
2382 * - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on
2383 * - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page
2384 *
2385 * @protected
2386 * @param {boolean} value Make button active
2387 * @chainable
2388 * @return {OO.ui.Element} The element, for chaining
2389 */
2390 OO.ui.mixin.ButtonElement.prototype.setActive = function ( value ) {
2391 this.active = !!value;
2392 this.$element.toggleClass( 'oo-ui-buttonElement-active', this.active );
2393 this.updateThemeClasses();
2394 return this;
2395 };
2396
2397 /**
2398 * Check if the button is active
2399 *
2400 * @protected
2401 * @return {boolean} The button is active
2402 */
2403 OO.ui.mixin.ButtonElement.prototype.isActive = function () {
2404 return this.active;
2405 };
2406
2407 /**
2408 * Any OOUI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
2409 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
2410 * items from the group is done through the interface the class provides.
2411 * For more information, please see the [OOUI documentation on MediaWiki] [1].
2412 *
2413 * [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Groups
2414 *
2415 * @abstract
2416 * @mixins OO.EmitterList
2417 * @class
2418 *
2419 * @constructor
2420 * @param {Object} [config] Configuration options
2421 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
2422 * is omitted, the group element will use a generated `<div>`.
2423 */
2424 OO.ui.mixin.GroupElement = function OoUiMixinGroupElement( config ) {
2425 // Configuration initialization
2426 config = config || {};
2427
2428 // Mixin constructors
2429 OO.EmitterList.call( this, config );
2430
2431 // Properties
2432 this.$group = null;
2433
2434 // Initialization
2435 this.setGroupElement( config.$group || $( '<div>' ) );
2436 };
2437
2438 /* Setup */
2439
2440 OO.mixinClass( OO.ui.mixin.GroupElement, OO.EmitterList );
2441
2442 /* Events */
2443
2444 /**
2445 * @event change
2446 *
2447 * A change event is emitted when the set of selected items changes.
2448 *
2449 * @param {OO.ui.Element[]} items Items currently in the group
2450 */
2451
2452 /* Methods */
2453
2454 /**
2455 * Set the group element.
2456 *
2457 * If an element is already set, items will be moved to the new element.
2458 *
2459 * @param {jQuery} $group Element to use as group
2460 */
2461 OO.ui.mixin.GroupElement.prototype.setGroupElement = function ( $group ) {
2462 var i, len;
2463
2464 this.$group = $group;
2465 for ( i = 0, len = this.items.length; i < len; i++ ) {
2466 this.$group.append( this.items[ i ].$element );
2467 }
2468 };
2469
2470 /**
2471 * Find an item by its data.
2472 *
2473 * Only the first item with matching data will be returned. To return all matching items,
2474 * use the #findItemsFromData method.
2475 *
2476 * @param {Object} data Item data to search for
2477 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2478 */
2479 OO.ui.mixin.GroupElement.prototype.findItemFromData = function ( data ) {
2480 var i, len, item,
2481 hash = OO.getHash( data );
2482
2483 for ( i = 0, len = this.items.length; i < len; i++ ) {
2484 item = this.items[ i ];
2485 if ( hash === OO.getHash( item.getData() ) ) {
2486 return item;
2487 }
2488 }
2489
2490 return null;
2491 };
2492
2493 /**
2494 * Find items by their data.
2495 *
2496 * All items with matching data will be returned. To return only the first match, use the #findItemFromData method instead.
2497 *
2498 * @param {Object} data Item data to search for
2499 * @return {OO.ui.Element[]} Items with equivalent data
2500 */
2501 OO.ui.mixin.GroupElement.prototype.findItemsFromData = function ( data ) {
2502 var i, len, item,
2503 hash = OO.getHash( data ),
2504 items = [];
2505
2506 for ( i = 0, len = this.items.length; i < len; i++ ) {
2507 item = this.items[ i ];
2508 if ( hash === OO.getHash( item.getData() ) ) {
2509 items.push( item );
2510 }
2511 }
2512
2513 return items;
2514 };
2515
2516 /**
2517 * Add items to the group.
2518 *
2519 * Items will be added to the end of the group array unless the optional `index` parameter specifies
2520 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
2521 *
2522 * @param {OO.ui.Element[]} items An array of items to add to the group
2523 * @param {number} [index] Index of the insertion point
2524 * @chainable
2525 * @return {OO.ui.Element} The element, for chaining
2526 */
2527 OO.ui.mixin.GroupElement.prototype.addItems = function ( items, index ) {
2528
2529 if ( items.length === 0 ) {
2530 return this;
2531 }
2532
2533 // Mixin method
2534 OO.EmitterList.prototype.addItems.call( this, items, index );
2535
2536 this.emit( 'change', this.getItems() );
2537 return this;
2538 };
2539
2540 /**
2541 * @inheritdoc
2542 */
2543 OO.ui.mixin.GroupElement.prototype.moveItem = function ( items, newIndex ) {
2544 // insertItemElements expects this.items to not have been modified yet, so call before the mixin
2545 this.insertItemElements( items, newIndex );
2546
2547 // Mixin method
2548 newIndex = OO.EmitterList.prototype.moveItem.call( this, items, newIndex );
2549
2550 return newIndex;
2551 };
2552
2553 /**
2554 * @inheritdoc
2555 */
2556 OO.ui.mixin.GroupElement.prototype.insertItem = function ( item, index ) {
2557 item.setElementGroup( this );
2558 this.insertItemElements( item, index );
2559
2560 // Mixin method
2561 index = OO.EmitterList.prototype.insertItem.call( this, item, index );
2562
2563 return index;
2564 };
2565
2566 /**
2567 * Insert elements into the group
2568 *
2569 * @private
2570 * @param {OO.ui.Element} itemWidget Item to insert
2571 * @param {number} index Insertion index
2572 */
2573 OO.ui.mixin.GroupElement.prototype.insertItemElements = function ( itemWidget, index ) {
2574 if ( index === undefined || index < 0 || index >= this.items.length ) {
2575 this.$group.append( itemWidget.$element );
2576 } else if ( index === 0 ) {
2577 this.$group.prepend( itemWidget.$element );
2578 } else {
2579 this.items[ index ].$element.before( itemWidget.$element );
2580 }
2581 };
2582
2583 /**
2584 * Remove the specified items from a group.
2585 *
2586 * Removed items are detached (not removed) from the DOM so that they may be reused.
2587 * To remove all items from a group, you may wish to use the #clearItems method instead.
2588 *
2589 * @param {OO.ui.Element[]} items An array of items to remove
2590 * @chainable
2591 * @return {OO.ui.Element} The element, for chaining
2592 */
2593 OO.ui.mixin.GroupElement.prototype.removeItems = function ( items ) {
2594 var i, len, item, index;
2595
2596 if ( items.length === 0 ) {
2597 return this;
2598 }
2599
2600 // Remove specific items elements
2601 for ( i = 0, len = items.length; i < len; i++ ) {
2602 item = items[ i ];
2603 index = this.items.indexOf( item );
2604 if ( index !== -1 ) {
2605 item.setElementGroup( null );
2606 item.$element.detach();
2607 }
2608 }
2609
2610 // Mixin method
2611 OO.EmitterList.prototype.removeItems.call( this, items );
2612
2613 this.emit( 'change', this.getItems() );
2614 return this;
2615 };
2616
2617 /**
2618 * Clear all items from the group.
2619 *
2620 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2621 * To remove only a subset of items from a group, use the #removeItems method.
2622 *
2623 * @chainable
2624 * @return {OO.ui.Element} The element, for chaining
2625 */
2626 OO.ui.mixin.GroupElement.prototype.clearItems = function () {
2627 var i, len;
2628
2629 // Remove all item elements
2630 for ( i = 0, len = this.items.length; i < len; i++ ) {
2631 this.items[ i ].setElementGroup( null );
2632 this.items[ i ].$element.detach();
2633 }
2634
2635 // Mixin method
2636 OO.EmitterList.prototype.clearItems.call( this );
2637
2638 this.emit( 'change', this.getItems() );
2639 return this;
2640 };
2641
2642 /**
2643 * LabelElement is often mixed into other classes to generate a label, which
2644 * helps identify the function of an interface element.
2645 * See the [OOUI documentation on MediaWiki] [1] for more information.
2646 *
2647 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
2648 *
2649 * @abstract
2650 * @class
2651 *
2652 * @constructor
2653 * @param {Object} [config] Configuration options
2654 * @cfg {jQuery} [$label] The label element created by the class. If this
2655 * configuration is omitted, the label element will use a generated `<span>`.
2656 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
2657 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
2658 * in the future. See the [OOUI documentation on MediaWiki] [2] for examples.
2659 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
2660 * @cfg {boolean} [invisibleLabel] Whether the label should be visually hidden (but still accessible
2661 * to screen-readers).
2662 */
2663 OO.ui.mixin.LabelElement = function OoUiMixinLabelElement( config ) {
2664 // Configuration initialization
2665 config = config || {};
2666
2667 // Properties
2668 this.$label = null;
2669 this.label = null;
2670 this.invisibleLabel = null;
2671
2672 // Initialization
2673 this.setLabel( config.label || this.constructor.static.label );
2674 this.setLabelElement( config.$label || $( '<span>' ) );
2675 this.setInvisibleLabel( config.invisibleLabel );
2676 };
2677
2678 /* Setup */
2679
2680 OO.initClass( OO.ui.mixin.LabelElement );
2681
2682 /* Events */
2683
2684 /**
2685 * @event labelChange
2686 * @param {string} value
2687 */
2688
2689 /* Static Properties */
2690
2691 /**
2692 * The label text. The label can be specified as a plaintext string, a function that will
2693 * produce a string in the future, or `null` for no label. The static value will
2694 * be overridden if a label is specified with the #label config option.
2695 *
2696 * @static
2697 * @inheritable
2698 * @property {string|Function|null}
2699 */
2700 OO.ui.mixin.LabelElement.static.label = null;
2701
2702 /* Static methods */
2703
2704 /**
2705 * Highlight the first occurrence of the query in the given text
2706 *
2707 * @param {string} text Text
2708 * @param {string} query Query to find
2709 * @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
2710 * @return {jQuery} Text with the first match of the query
2711 * sub-string wrapped in highlighted span
2712 */
2713 OO.ui.mixin.LabelElement.static.highlightQuery = function ( text, query, compare ) {
2714 var i, tLen, qLen,
2715 offset = -1,
2716 $result = $( '<span>' );
2717
2718 if ( compare ) {
2719 tLen = text.length;
2720 qLen = query.length;
2721 for ( i = 0; offset === -1 && i <= tLen - qLen; i++ ) {
2722 if ( compare( query, text.slice( i, i + qLen ) ) === 0 ) {
2723 offset = i;
2724 }
2725 }
2726 } else {
2727 offset = text.toLowerCase().indexOf( query.toLowerCase() );
2728 }
2729
2730 if ( !query.length || offset === -1 ) {
2731 $result.text( text );
2732 } else {
2733 $result.append(
2734 document.createTextNode( text.slice( 0, offset ) ),
2735 $( '<span>' )
2736 .addClass( 'oo-ui-labelElement-label-highlight' )
2737 .text( text.slice( offset, offset + query.length ) ),
2738 document.createTextNode( text.slice( offset + query.length ) )
2739 );
2740 }
2741 return $result.contents();
2742 };
2743
2744 /* Methods */
2745
2746 /**
2747 * Set the label element.
2748 *
2749 * If an element is already set, it will be cleaned up before setting up the new element.
2750 *
2751 * @param {jQuery} $label Element to use as label
2752 */
2753 OO.ui.mixin.LabelElement.prototype.setLabelElement = function ( $label ) {
2754 if ( this.$label ) {
2755 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
2756 }
2757
2758 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
2759 this.setLabelContent( this.label );
2760 };
2761
2762 /**
2763 * Set the label.
2764 *
2765 * An empty string will result in the label being hidden. A string containing only whitespace will
2766 * be converted to a single `&nbsp;`.
2767 *
2768 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
2769 * text; or null for no label
2770 * @chainable
2771 * @return {OO.ui.Element} The element, for chaining
2772 */
2773 OO.ui.mixin.LabelElement.prototype.setLabel = function ( label ) {
2774 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
2775 label = ( ( typeof label === 'string' || label instanceof $ ) && label.length ) || ( label instanceof OO.ui.HtmlSnippet && label.toString().length ) ? label : null;
2776
2777 if ( this.label !== label ) {
2778 if ( this.$label ) {
2779 this.setLabelContent( label );
2780 }
2781 this.label = label;
2782 this.emit( 'labelChange' );
2783 }
2784
2785 this.$element.toggleClass( 'oo-ui-labelElement', !!this.label && !this.invisibleLabel );
2786
2787 return this;
2788 };
2789
2790 /**
2791 * Set whether the label should be visually hidden (but still accessible to screen-readers).
2792 *
2793 * @param {boolean} invisibleLabel
2794 * @chainable
2795 * @return {OO.ui.Element} The element, for chaining
2796 */
2797 OO.ui.mixin.LabelElement.prototype.setInvisibleLabel = function ( invisibleLabel ) {
2798 invisibleLabel = !!invisibleLabel;
2799
2800 if ( this.invisibleLabel !== invisibleLabel ) {
2801 this.invisibleLabel = invisibleLabel;
2802 this.emit( 'labelChange' );
2803 }
2804
2805 this.$label.toggleClass( 'oo-ui-labelElement-invisible', this.invisibleLabel );
2806 // Pretend that there is no label, a lot of CSS has been written with this assumption
2807 this.$element.toggleClass( 'oo-ui-labelElement', !!this.label && !this.invisibleLabel );
2808
2809 return this;
2810 };
2811
2812 /**
2813 * Set the label as plain text with a highlighted query
2814 *
2815 * @param {string} text Text label to set
2816 * @param {string} query Substring of text to highlight
2817 * @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
2818 * @chainable
2819 * @return {OO.ui.Element} The element, for chaining
2820 */
2821 OO.ui.mixin.LabelElement.prototype.setHighlightedQuery = function ( text, query, compare ) {
2822 return this.setLabel( this.constructor.static.highlightQuery( text, query, compare ) );
2823 };
2824
2825 /**
2826 * Get the label.
2827 *
2828 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
2829 * text; or null for no label
2830 */
2831 OO.ui.mixin.LabelElement.prototype.getLabel = function () {
2832 return this.label;
2833 };
2834
2835 /**
2836 * Set the content of the label.
2837 *
2838 * Do not call this method until after the label element has been set by #setLabelElement.
2839 *
2840 * @private
2841 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
2842 * text; or null for no label
2843 */
2844 OO.ui.mixin.LabelElement.prototype.setLabelContent = function ( label ) {
2845 if ( typeof label === 'string' ) {
2846 if ( label.match( /^\s*$/ ) ) {
2847 // Convert whitespace only string to a single non-breaking space
2848 this.$label.html( '&nbsp;' );
2849 } else {
2850 this.$label.text( label );
2851 }
2852 } else if ( label instanceof OO.ui.HtmlSnippet ) {
2853 this.$label.html( label.toString() );
2854 } else if ( label instanceof $ ) {
2855 this.$label.empty().append( label );
2856 } else {
2857 this.$label.empty();
2858 }
2859 };
2860
2861 /**
2862 * IconElement is often mixed into other classes to generate an icon.
2863 * Icons are graphics, about the size of normal text. They are used to aid the user
2864 * in locating a control or to convey information in a space-efficient way. See the
2865 * [OOUI documentation on MediaWiki] [1] for a list of icons
2866 * included in the library.
2867 *
2868 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
2869 *
2870 * @abstract
2871 * @class
2872 *
2873 * @constructor
2874 * @param {Object} [config] Configuration options
2875 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2876 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2877 * the icon element be set to an existing icon instead of the one generated by this class, set a
2878 * value using a jQuery selection. For example:
2879 *
2880 * // Use a <div> tag instead of a <span>
2881 * $icon: $( '<div>' )
2882 * // Use an existing icon element instead of the one generated by the class
2883 * $icon: this.$element
2884 * // Use an icon element from a child widget
2885 * $icon: this.childwidget.$element
2886 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
2887 * symbolic names. A map is used for i18n purposes and contains a `default` icon
2888 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
2889 * by the user's language.
2890 *
2891 * Example of an i18n map:
2892 *
2893 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2894 * See the [OOUI documentation on MediaWiki] [2] for a list of icons included in the library.
2895 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
2896 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
2897 * text. The icon title is displayed when users move the mouse over the icon.
2898 */
2899 OO.ui.mixin.IconElement = function OoUiMixinIconElement( config ) {
2900 // Configuration initialization
2901 config = config || {};
2902
2903 // Properties
2904 this.$icon = null;
2905 this.icon = null;
2906 this.iconTitle = null;
2907
2908 // `iconTitle`s are deprecated since 0.30.0
2909 if ( config.iconTitle !== undefined ) {
2910 OO.ui.warnDeprecation( 'IconElement: Widgets with iconTitle set are deprecated, use title instead. See T76638 for details.' );
2911 }
2912
2913 // Initialization
2914 this.setIcon( config.icon || this.constructor.static.icon );
2915 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
2916 this.setIconElement( config.$icon || $( '<span>' ) );
2917 };
2918
2919 /* Setup */
2920
2921 OO.initClass( OO.ui.mixin.IconElement );
2922
2923 /* Static Properties */
2924
2925 /**
2926 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
2927 * for i18n purposes and contains a `default` icon name and additional names keyed by
2928 * language code. The `default` name is used when no icon is keyed by the user's language.
2929 *
2930 * Example of an i18n map:
2931 *
2932 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2933 *
2934 * Note: the static property will be overridden if the #icon configuration is used.
2935 *
2936 * @static
2937 * @inheritable
2938 * @property {Object|string}
2939 */
2940 OO.ui.mixin.IconElement.static.icon = null;
2941
2942 /**
2943 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2944 * function that returns title text, or `null` for no title.
2945 *
2946 * The static property will be overridden if the #iconTitle configuration is used.
2947 *
2948 * @static
2949 * @inheritable
2950 * @property {string|Function|null}
2951 */
2952 OO.ui.mixin.IconElement.static.iconTitle = null;
2953
2954 /* Methods */
2955
2956 /**
2957 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2958 * applies to the specified icon element instead of the one created by the class. If an icon
2959 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2960 * and mixin methods will no longer affect the element.
2961 *
2962 * @param {jQuery} $icon Element to use as icon
2963 */
2964 OO.ui.mixin.IconElement.prototype.setIconElement = function ( $icon ) {
2965 if ( this.$icon ) {
2966 this.$icon
2967 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
2968 .removeAttr( 'title' );
2969 }
2970
2971 this.$icon = $icon
2972 .addClass( 'oo-ui-iconElement-icon' )
2973 .toggleClass( 'oo-ui-iconElement-noIcon', !this.icon )
2974 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
2975 if ( this.iconTitle !== null ) {
2976 this.$icon.attr( 'title', this.iconTitle );
2977 }
2978
2979 this.updateThemeClasses();
2980 };
2981
2982 /**
2983 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
2984 * The icon parameter can also be set to a map of icon names. See the #icon config setting
2985 * for an example.
2986 *
2987 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
2988 * by language code, or `null` to remove the icon.
2989 * @chainable
2990 * @return {OO.ui.Element} The element, for chaining
2991 */
2992 OO.ui.mixin.IconElement.prototype.setIcon = function ( icon ) {
2993 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
2994 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
2995
2996 if ( this.icon !== icon ) {
2997 if ( this.$icon ) {
2998 if ( this.icon !== null ) {
2999 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
3000 }
3001 if ( icon !== null ) {
3002 this.$icon.addClass( 'oo-ui-icon-' + icon );
3003 }
3004 }
3005 this.icon = icon;
3006 }
3007
3008 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
3009 if ( this.$icon ) {
3010 this.$icon.toggleClass( 'oo-ui-iconElement-noIcon', !this.icon );
3011 }
3012 this.updateThemeClasses();
3013
3014 return this;
3015 };
3016
3017 /**
3018 * Set the icon title. Use `null` to remove the title.
3019 *
3020 * @param {string|Function|null} iconTitle A text string used as the icon title,
3021 * a function that returns title text, or `null` for no title.
3022 * @chainable
3023 * @return {OO.ui.Element} The element, for chaining
3024 * @deprecated
3025 */
3026 OO.ui.mixin.IconElement.prototype.setIconTitle = function ( iconTitle ) {
3027 iconTitle =
3028 ( typeof iconTitle === 'function' || ( typeof iconTitle === 'string' && iconTitle.length ) ) ?
3029 OO.ui.resolveMsg( iconTitle ) : null;
3030
3031 if ( this.iconTitle !== iconTitle ) {
3032 this.iconTitle = iconTitle;
3033 if ( this.$icon ) {
3034 if ( this.iconTitle !== null ) {
3035 this.$icon.attr( 'title', iconTitle );
3036 } else {
3037 this.$icon.removeAttr( 'title' );
3038 }
3039 }
3040 }
3041
3042 // `setIconTitle is deprecated since 0.30.0
3043 if ( iconTitle !== null ) {
3044 // Avoid a warning when this is called from the constructor with no iconTitle set
3045 OO.ui.warnDeprecation( 'IconElement: setIconTitle is deprecated, use setTitle of TitledElement instead. See T76638 for details.' );
3046 }
3047
3048 return this;
3049 };
3050
3051 /**
3052 * Get the symbolic name of the icon.
3053 *
3054 * @return {string} Icon name
3055 */
3056 OO.ui.mixin.IconElement.prototype.getIcon = function () {
3057 return this.icon;
3058 };
3059
3060 /**
3061 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
3062 *
3063 * @return {string} Icon title text
3064 */
3065 OO.ui.mixin.IconElement.prototype.getIconTitle = function () {
3066 return this.iconTitle;
3067 };
3068
3069 /**
3070 * IndicatorElement is often mixed into other classes to generate an indicator.
3071 * Indicators are small graphics that are generally used in two ways:
3072 *
3073 * - To draw attention to the status of an item. For example, an indicator might be
3074 * used to show that an item in a list has errors that need to be resolved.
3075 * - To clarify the function of a control that acts in an exceptional way (a button
3076 * that opens a menu instead of performing an action directly, for example).
3077 *
3078 * For a list of indicators included in the library, please see the
3079 * [OOUI documentation on MediaWiki] [1].
3080 *
3081 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3082 *
3083 * @abstract
3084 * @class
3085 *
3086 * @constructor
3087 * @param {Object} [config] Configuration options
3088 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
3089 * configuration is omitted, the indicator element will use a generated `<span>`.
3090 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3091 * See the [OOUI documentation on MediaWiki][2] for a list of indicators included
3092 * in the library.
3093 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3094 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
3095 * or a function that returns title text. The indicator title is displayed when users move
3096 * the mouse over the indicator.
3097 */
3098 OO.ui.mixin.IndicatorElement = function OoUiMixinIndicatorElement( config ) {
3099 // Configuration initialization
3100 config = config || {};
3101
3102 // Properties
3103 this.$indicator = null;
3104 this.indicator = null;
3105 this.indicatorTitle = null;
3106
3107 // `indicatorTitle`s are deprecated since 0.30.0
3108 if ( config.indicatorTitle !== undefined ) {
3109 OO.ui.warnDeprecation( 'IndicatorElement: Widgets with indicatorTitle set are deprecated, use title instead. See T76638 for details.' );
3110 }
3111
3112 // Initialization
3113 this.setIndicator( config.indicator || this.constructor.static.indicator );
3114 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
3115 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
3116 };
3117
3118 /* Setup */
3119
3120 OO.initClass( OO.ui.mixin.IndicatorElement );
3121
3122 /* Static Properties */
3123
3124 /**
3125 * Symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3126 * The static property will be overridden if the #indicator configuration is used.
3127 *
3128 * @static
3129 * @inheritable
3130 * @property {string|null}
3131 */
3132 OO.ui.mixin.IndicatorElement.static.indicator = null;
3133
3134 /**
3135 * A text string used as the indicator title, a function that returns title text, or `null`
3136 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
3137 *
3138 * @static
3139 * @inheritable
3140 * @property {string|Function|null}
3141 */
3142 OO.ui.mixin.IndicatorElement.static.indicatorTitle = null;
3143
3144 /* Methods */
3145
3146 /**
3147 * Set the indicator element.
3148 *
3149 * If an element is already set, it will be cleaned up before setting up the new element.
3150 *
3151 * @param {jQuery} $indicator Element to use as indicator
3152 */
3153 OO.ui.mixin.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
3154 if ( this.$indicator ) {
3155 this.$indicator
3156 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
3157 .removeAttr( 'title' );
3158 }
3159
3160 this.$indicator = $indicator
3161 .addClass( 'oo-ui-indicatorElement-indicator' )
3162 .toggleClass( 'oo-ui-indicatorElement-noIndicator', !this.indicator )
3163 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
3164 if ( this.indicatorTitle !== null ) {
3165 this.$indicator.attr( 'title', this.indicatorTitle );
3166 }
3167
3168 this.updateThemeClasses();
3169 };
3170
3171 /**
3172 * Set the indicator by its symbolic name: ‘clear’, ‘down’, ‘required’, ‘search’, ‘up’. Use `null` to remove the indicator.
3173 *
3174 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
3175 * @chainable
3176 * @return {OO.ui.Element} The element, for chaining
3177 */
3178 OO.ui.mixin.IndicatorElement.prototype.setIndicator = function ( indicator ) {
3179 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
3180
3181 if ( this.indicator !== indicator ) {
3182 if ( this.$indicator ) {
3183 if ( this.indicator !== null ) {
3184 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
3185 }
3186 if ( indicator !== null ) {
3187 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
3188 }
3189 }
3190 this.indicator = indicator;
3191 }
3192
3193 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
3194 if ( this.$indicator ) {
3195 this.$indicator.toggleClass( 'oo-ui-indicatorElement-noIndicator', !this.indicator );
3196 }
3197 this.updateThemeClasses();
3198
3199 return this;
3200 };
3201
3202 /**
3203 * Set the indicator title.
3204 *
3205 * The title is displayed when a user moves the mouse over the indicator.
3206 *
3207 * @param {string|Function|null} indicatorTitle Indicator title text, a function that returns text, or
3208 * `null` for no indicator title
3209 * @chainable
3210 * @return {OO.ui.Element} The element, for chaining
3211 * @deprecated
3212 */
3213 OO.ui.mixin.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
3214 indicatorTitle =
3215 ( typeof indicatorTitle === 'function' || ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ) ?
3216 OO.ui.resolveMsg( indicatorTitle ) : null;
3217
3218 if ( this.indicatorTitle !== indicatorTitle ) {
3219 this.indicatorTitle = indicatorTitle;
3220 if ( this.$indicator ) {
3221 if ( this.indicatorTitle !== null ) {
3222 this.$indicator.attr( 'title', indicatorTitle );
3223 } else {
3224 this.$indicator.removeAttr( 'title' );
3225 }
3226 }
3227 }
3228
3229 // `setIndicatorTitle is deprecated since 0.30.0
3230 if ( indicatorTitle !== null ) {
3231 // Avoid a warning when this is called from the constructor with no indicatorTitle set
3232 OO.ui.warnDeprecation( 'IndicatorElement: setIndicatorTitle is deprecated, use setTitle of TitledElement instead. See T76638 for details.' );
3233 }
3234
3235 return this;
3236 };
3237
3238 /**
3239 * Get the symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3240 *
3241 * @return {string} Symbolic name of indicator
3242 */
3243 OO.ui.mixin.IndicatorElement.prototype.getIndicator = function () {
3244 return this.indicator;
3245 };
3246
3247 /**
3248 * Get the indicator title.
3249 *
3250 * The title is displayed when a user moves the mouse over the indicator.
3251 *
3252 * @return {string} Indicator title text
3253 */
3254 OO.ui.mixin.IndicatorElement.prototype.getIndicatorTitle = function () {
3255 return this.indicatorTitle;
3256 };
3257
3258 /**
3259 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
3260 * additional functionality to an element created by another class. The class provides
3261 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
3262 * which are used to customize the look and feel of a widget to better describe its
3263 * importance and functionality.
3264 *
3265 * The library currently contains the following styling flags for general use:
3266 *
3267 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
3268 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
3269 *
3270 * The flags affect the appearance of the buttons:
3271 *
3272 * @example
3273 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
3274 * var button1 = new OO.ui.ButtonWidget( {
3275 * label: 'Progressive',
3276 * flags: 'progressive'
3277 * } ),
3278 * button2 = new OO.ui.ButtonWidget( {
3279 * label: 'Destructive',
3280 * flags: 'destructive'
3281 * } );
3282 * $( document.body ).append( button1.$element, button2.$element );
3283 *
3284 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
3285 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
3286 *
3287 * [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
3288 *
3289 * @abstract
3290 * @class
3291 *
3292 * @constructor
3293 * @param {Object} [config] Configuration options
3294 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'progressive' or 'primary') to apply.
3295 * Please see the [OOUI documentation on MediaWiki] [2] for more information about available flags.
3296 * [2]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
3297 * @cfg {jQuery} [$flagged] The flagged element. By default,
3298 * the flagged functionality is applied to the element created by the class ($element).
3299 * If a different element is specified, the flagged functionality will be applied to it instead.
3300 */
3301 OO.ui.mixin.FlaggedElement = function OoUiMixinFlaggedElement( config ) {
3302 // Configuration initialization
3303 config = config || {};
3304
3305 // Properties
3306 this.flags = {};
3307 this.$flagged = null;
3308
3309 // Initialization
3310 this.setFlags( config.flags );
3311 this.setFlaggedElement( config.$flagged || this.$element );
3312 };
3313
3314 /* Events */
3315
3316 /**
3317 * @event flag
3318 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
3319 * parameter contains the name of each modified flag and indicates whether it was
3320 * added or removed.
3321 *
3322 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
3323 * that the flag was added, `false` that the flag was removed.
3324 */
3325
3326 /* Methods */
3327
3328 /**
3329 * Set the flagged element.
3330 *
3331 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
3332 * If an element is already set, the method will remove the mixin’s effect on that element.
3333 *
3334 * @param {jQuery} $flagged Element that should be flagged
3335 */
3336 OO.ui.mixin.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
3337 var classNames = Object.keys( this.flags ).map( function ( flag ) {
3338 return 'oo-ui-flaggedElement-' + flag;
3339 } );
3340
3341 if ( this.$flagged ) {
3342 this.$flagged.removeClass( classNames );
3343 }
3344
3345 this.$flagged = $flagged.addClass( classNames );
3346 };
3347
3348 /**
3349 * Check if the specified flag is set.
3350 *
3351 * @param {string} flag Name of flag
3352 * @return {boolean} The flag is set
3353 */
3354 OO.ui.mixin.FlaggedElement.prototype.hasFlag = function ( flag ) {
3355 // This may be called before the constructor, thus before this.flags is set
3356 return this.flags && ( flag in this.flags );
3357 };
3358
3359 /**
3360 * Get the names of all flags set.
3361 *
3362 * @return {string[]} Flag names
3363 */
3364 OO.ui.mixin.FlaggedElement.prototype.getFlags = function () {
3365 // This may be called before the constructor, thus before this.flags is set
3366 return Object.keys( this.flags || {} );
3367 };
3368
3369 /**
3370 * Clear all flags.
3371 *
3372 * @chainable
3373 * @return {OO.ui.Element} The element, for chaining
3374 * @fires flag
3375 */
3376 OO.ui.mixin.FlaggedElement.prototype.clearFlags = function () {
3377 var flag, className,
3378 changes = {},
3379 remove = [],
3380 classPrefix = 'oo-ui-flaggedElement-';
3381
3382 for ( flag in this.flags ) {
3383 className = classPrefix + flag;
3384 changes[ flag ] = false;
3385 delete this.flags[ flag ];
3386 remove.push( className );
3387 }
3388
3389 if ( this.$flagged ) {
3390 this.$flagged.removeClass( remove );
3391 }
3392
3393 this.updateThemeClasses();
3394 this.emit( 'flag', changes );
3395
3396 return this;
3397 };
3398
3399 /**
3400 * Add one or more flags.
3401 *
3402 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
3403 * or an object keyed by flag name with a boolean value that indicates whether the flag should
3404 * be added (`true`) or removed (`false`).
3405 * @chainable
3406 * @return {OO.ui.Element} The element, for chaining
3407 * @fires flag
3408 */
3409 OO.ui.mixin.FlaggedElement.prototype.setFlags = function ( flags ) {
3410 var i, len, flag, className,
3411 changes = {},
3412 add = [],
3413 remove = [],
3414 classPrefix = 'oo-ui-flaggedElement-';
3415
3416 if ( typeof flags === 'string' ) {
3417 className = classPrefix + flags;
3418 // Set
3419 if ( !this.flags[ flags ] ) {
3420 this.flags[ flags ] = true;
3421 add.push( className );
3422 }
3423 } else if ( Array.isArray( flags ) ) {
3424 for ( i = 0, len = flags.length; i < len; i++ ) {
3425 flag = flags[ i ];
3426 className = classPrefix + flag;
3427 // Set
3428 if ( !this.flags[ flag ] ) {
3429 changes[ flag ] = true;
3430 this.flags[ flag ] = true;
3431 add.push( className );
3432 }
3433 }
3434 } else if ( OO.isPlainObject( flags ) ) {
3435 for ( flag in flags ) {
3436 className = classPrefix + flag;
3437 if ( flags[ flag ] ) {
3438 // Set
3439 if ( !this.flags[ flag ] ) {
3440 changes[ flag ] = true;
3441 this.flags[ flag ] = true;
3442 add.push( className );
3443 }
3444 } else {
3445 // Remove
3446 if ( this.flags[ flag ] ) {
3447 changes[ flag ] = false;
3448 delete this.flags[ flag ];
3449 remove.push( className );
3450 }
3451 }
3452 }
3453 }
3454
3455 if ( this.$flagged ) {
3456 this.$flagged
3457 .addClass( add )
3458 .removeClass( remove );
3459 }
3460
3461 this.updateThemeClasses();
3462 this.emit( 'flag', changes );
3463
3464 return this;
3465 };
3466
3467 /**
3468 * TitledElement is mixed into other classes to provide a `title` attribute.
3469 * Titles are rendered by the browser and are made visible when the user moves
3470 * the mouse over the element. Titles are not visible on touch devices.
3471 *
3472 * @example
3473 * // TitledElement provides a `title` attribute to the
3474 * // ButtonWidget class.
3475 * var button = new OO.ui.ButtonWidget( {
3476 * label: 'Button with Title',
3477 * title: 'I am a button'
3478 * } );
3479 * $( document.body ).append( button.$element );
3480 *
3481 * @abstract
3482 * @class
3483 *
3484 * @constructor
3485 * @param {Object} [config] Configuration options
3486 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
3487 * If this config is omitted, the title functionality is applied to $element, the
3488 * element created by the class.
3489 * @cfg {string|Function} [title] The title text or a function that returns text. If
3490 * this config is omitted, the value of the {@link #static-title static title} property is used.
3491 */
3492 OO.ui.mixin.TitledElement = function OoUiMixinTitledElement( config ) {
3493 // Configuration initialization
3494 config = config || {};
3495
3496 // Properties
3497 this.$titled = null;
3498 this.title = null;
3499
3500 // Initialization
3501 this.setTitle( config.title !== undefined ? config.title : this.constructor.static.title );
3502 this.setTitledElement( config.$titled || this.$element );
3503 };
3504
3505 /* Setup */
3506
3507 OO.initClass( OO.ui.mixin.TitledElement );
3508
3509 /* Static Properties */
3510
3511 /**
3512 * The title text, a function that returns text, or `null` for no title. The value of the static property
3513 * is overridden if the #title config option is used.
3514 *
3515 * @static
3516 * @inheritable
3517 * @property {string|Function|null}
3518 */
3519 OO.ui.mixin.TitledElement.static.title = null;
3520
3521 /* Methods */
3522
3523 /**
3524 * Set the titled element.
3525 *
3526 * This method is used to retarget a TitledElement mixin so that its functionality applies to the specified element.
3527 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
3528 *
3529 * @param {jQuery} $titled Element that should use the 'titled' functionality
3530 */
3531 OO.ui.mixin.TitledElement.prototype.setTitledElement = function ( $titled ) {
3532 if ( this.$titled ) {
3533 this.$titled.removeAttr( 'title' );
3534 }
3535
3536 this.$titled = $titled;
3537 if ( this.title ) {
3538 this.updateTitle();
3539 }
3540 };
3541
3542 /**
3543 * Set title.
3544 *
3545 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
3546 * @chainable
3547 * @return {OO.ui.Element} The element, for chaining
3548 */
3549 OO.ui.mixin.TitledElement.prototype.setTitle = function ( title ) {
3550 title = typeof title === 'function' ? OO.ui.resolveMsg( title ) : title;
3551 title = ( typeof title === 'string' && title.length ) ? title : null;
3552
3553 if ( this.title !== title ) {
3554 this.title = title;
3555 this.updateTitle();
3556 }
3557
3558 return this;
3559 };
3560
3561 /**
3562 * Update the title attribute, in case of changes to title or accessKey.
3563 *
3564 * @protected
3565 * @chainable
3566 * @return {OO.ui.Element} The element, for chaining
3567 */
3568 OO.ui.mixin.TitledElement.prototype.updateTitle = function () {
3569 var title = this.getTitle();
3570 if ( this.$titled ) {
3571 if ( title !== null ) {
3572 // Only if this is an AccessKeyedElement
3573 if ( this.formatTitleWithAccessKey ) {
3574 title = this.formatTitleWithAccessKey( title );
3575 }
3576 this.$titled.attr( 'title', title );
3577 } else {
3578 this.$titled.removeAttr( 'title' );
3579 }
3580 }
3581 return this;
3582 };
3583
3584 /**
3585 * Get title.
3586 *
3587 * @return {string} Title string
3588 */
3589 OO.ui.mixin.TitledElement.prototype.getTitle = function () {
3590 return this.title;
3591 };
3592
3593 /**
3594 * AccessKeyedElement is mixed into other classes to provide an `accesskey` HTML attribute.
3595 * Accesskeys allow an user to go to a specific element by using
3596 * a shortcut combination of a browser specific keys + the key
3597 * set to the field.
3598 *
3599 * @example
3600 * // AccessKeyedElement provides an `accesskey` attribute to the
3601 * // ButtonWidget class.
3602 * var button = new OO.ui.ButtonWidget( {
3603 * label: 'Button with Accesskey',
3604 * accessKey: 'k'
3605 * } );
3606 * $( document.body ).append( button.$element );
3607 *
3608 * @abstract
3609 * @class
3610 *
3611 * @constructor
3612 * @param {Object} [config] Configuration options
3613 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3614 * If this config is omitted, the accesskey functionality is applied to $element, the
3615 * element created by the class.
3616 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3617 * this config is omitted, no accesskey will be added.
3618 */
3619 OO.ui.mixin.AccessKeyedElement = function OoUiMixinAccessKeyedElement( config ) {
3620 // Configuration initialization
3621 config = config || {};
3622
3623 // Properties
3624 this.$accessKeyed = null;
3625 this.accessKey = null;
3626
3627 // Initialization
3628 this.setAccessKey( config.accessKey || null );
3629 this.setAccessKeyedElement( config.$accessKeyed || this.$element );
3630
3631 // If this is also a TitledElement and it initialized before we did, we may have
3632 // to update the title with the access key
3633 if ( this.updateTitle ) {
3634 this.updateTitle();
3635 }
3636 };
3637
3638 /* Setup */
3639
3640 OO.initClass( OO.ui.mixin.AccessKeyedElement );
3641
3642 /* Static Properties */
3643
3644 /**
3645 * The access key, a function that returns a key, or `null` for no accesskey.
3646 *
3647 * @static
3648 * @inheritable
3649 * @property {string|Function|null}
3650 */
3651 OO.ui.mixin.AccessKeyedElement.static.accessKey = null;
3652
3653 /* Methods */
3654
3655 /**
3656 * Set the accesskeyed element.
3657 *
3658 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
3659 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
3660 *
3661 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyed' functionality
3662 */
3663 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKeyedElement = function ( $accessKeyed ) {
3664 if ( this.$accessKeyed ) {
3665 this.$accessKeyed.removeAttr( 'accesskey' );
3666 }
3667
3668 this.$accessKeyed = $accessKeyed;
3669 if ( this.accessKey ) {
3670 this.$accessKeyed.attr( 'accesskey', this.accessKey );
3671 }
3672 };
3673
3674 /**
3675 * Set accesskey.
3676 *
3677 * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no accesskey
3678 * @chainable
3679 * @return {OO.ui.Element} The element, for chaining
3680 */
3681 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKey = function ( accessKey ) {
3682 accessKey = typeof accessKey === 'string' ? OO.ui.resolveMsg( accessKey ) : null;
3683
3684 if ( this.accessKey !== accessKey ) {
3685 if ( this.$accessKeyed ) {
3686 if ( accessKey !== null ) {
3687 this.$accessKeyed.attr( 'accesskey', accessKey );
3688 } else {
3689 this.$accessKeyed.removeAttr( 'accesskey' );
3690 }
3691 }
3692 this.accessKey = accessKey;
3693
3694 // Only if this is a TitledElement
3695 if ( this.updateTitle ) {
3696 this.updateTitle();
3697 }
3698 }
3699
3700 return this;
3701 };
3702
3703 /**
3704 * Get accesskey.
3705 *
3706 * @return {string} accessKey string
3707 */
3708 OO.ui.mixin.AccessKeyedElement.prototype.getAccessKey = function () {
3709 return this.accessKey;
3710 };
3711
3712 /**
3713 * Add information about the access key to the element's tooltip label.
3714 * (This is only public for hacky usage in FieldLayout.)
3715 *
3716 * @param {string} title Tooltip label for `title` attribute
3717 * @return {string}
3718 */
3719 OO.ui.mixin.AccessKeyedElement.prototype.formatTitleWithAccessKey = function ( title ) {
3720 var accessKey;
3721
3722 if ( !this.$accessKeyed ) {
3723 // Not initialized yet; the constructor will call updateTitle() which will rerun this function
3724 return title;
3725 }
3726 // Use jquery.accessKeyLabel if available to show modifiers, otherwise just display the single key
3727 if ( $.fn.updateTooltipAccessKeys && $.fn.updateTooltipAccessKeys.getAccessKeyLabel ) {
3728 accessKey = $.fn.updateTooltipAccessKeys.getAccessKeyLabel( this.$accessKeyed[ 0 ] );
3729 } else {
3730 accessKey = this.getAccessKey();
3731 }
3732 if ( accessKey ) {
3733 title += ' [' + accessKey + ']';
3734 }
3735 return title;
3736 };
3737
3738 /**
3739 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3740 * feels, and functionality can be customized via the class’s configuration options
3741 * and methods. Please see the [OOUI documentation on MediaWiki] [1] for more information
3742 * and examples.
3743 *
3744 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches
3745 *
3746 * @example
3747 * // A button widget.
3748 * var button = new OO.ui.ButtonWidget( {
3749 * label: 'Button with Icon',
3750 * icon: 'trash',
3751 * title: 'Remove'
3752 * } );
3753 * $( document.body ).append( button.$element );
3754 *
3755 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3756 *
3757 * @class
3758 * @extends OO.ui.Widget
3759 * @mixins OO.ui.mixin.ButtonElement
3760 * @mixins OO.ui.mixin.IconElement
3761 * @mixins OO.ui.mixin.IndicatorElement
3762 * @mixins OO.ui.mixin.LabelElement
3763 * @mixins OO.ui.mixin.TitledElement
3764 * @mixins OO.ui.mixin.FlaggedElement
3765 * @mixins OO.ui.mixin.TabIndexedElement
3766 * @mixins OO.ui.mixin.AccessKeyedElement
3767 *
3768 * @constructor
3769 * @param {Object} [config] Configuration options
3770 * @cfg {boolean} [active=false] Whether button should be shown as active
3771 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3772 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3773 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3774 */
3775 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
3776 // Configuration initialization
3777 config = config || {};
3778
3779 // Parent constructor
3780 OO.ui.ButtonWidget.parent.call( this, config );
3781
3782 // Mixin constructors
3783 OO.ui.mixin.ButtonElement.call( this, config );
3784 OO.ui.mixin.IconElement.call( this, config );
3785 OO.ui.mixin.IndicatorElement.call( this, config );
3786 OO.ui.mixin.LabelElement.call( this, config );
3787 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
3788 OO.ui.mixin.FlaggedElement.call( this, config );
3789 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
3790 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$button } ) );
3791
3792 // Properties
3793 this.href = null;
3794 this.target = null;
3795 this.noFollow = false;
3796
3797 // Events
3798 this.connect( this, { disable: 'onDisable' } );
3799
3800 // Initialization
3801 this.$button.append( this.$icon, this.$label, this.$indicator );
3802 this.$element
3803 .addClass( 'oo-ui-buttonWidget' )
3804 .append( this.$button );
3805 this.setActive( config.active );
3806 this.setHref( config.href );
3807 this.setTarget( config.target );
3808 this.setNoFollow( config.noFollow );
3809 };
3810
3811 /* Setup */
3812
3813 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
3814 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.ButtonElement );
3815 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IconElement );
3816 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IndicatorElement );
3817 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.LabelElement );
3818 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TitledElement );
3819 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.FlaggedElement );
3820 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TabIndexedElement );
3821 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.AccessKeyedElement );
3822
3823 /* Static Properties */
3824
3825 /**
3826 * @static
3827 * @inheritdoc
3828 */
3829 OO.ui.ButtonWidget.static.cancelButtonMouseDownEvents = false;
3830
3831 /**
3832 * @static
3833 * @inheritdoc
3834 */
3835 OO.ui.ButtonWidget.static.tagName = 'span';
3836
3837 /* Methods */
3838
3839 /**
3840 * Get hyperlink location.
3841 *
3842 * @return {string} Hyperlink location
3843 */
3844 OO.ui.ButtonWidget.prototype.getHref = function () {
3845 return this.href;
3846 };
3847
3848 /**
3849 * Get hyperlink target.
3850 *
3851 * @return {string} Hyperlink target
3852 */
3853 OO.ui.ButtonWidget.prototype.getTarget = function () {
3854 return this.target;
3855 };
3856
3857 /**
3858 * Get search engine traversal hint.
3859 *
3860 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3861 */
3862 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
3863 return this.noFollow;
3864 };
3865
3866 /**
3867 * Set hyperlink location.
3868 *
3869 * @param {string|null} href Hyperlink location, null to remove
3870 * @chainable
3871 * @return {OO.ui.Widget} The widget, for chaining
3872 */
3873 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
3874 href = typeof href === 'string' ? href : null;
3875 if ( href !== null && !OO.ui.isSafeUrl( href ) ) {
3876 href = './' + href;
3877 }
3878
3879 if ( href !== this.href ) {
3880 this.href = href;
3881 this.updateHref();
3882 }
3883
3884 return this;
3885 };
3886
3887 /**
3888 * Update the `href` attribute, in case of changes to href or
3889 * disabled state.
3890 *
3891 * @private
3892 * @chainable
3893 * @return {OO.ui.Widget} The widget, for chaining
3894 */
3895 OO.ui.ButtonWidget.prototype.updateHref = function () {
3896 if ( this.href !== null && !this.isDisabled() ) {
3897 this.$button.attr( 'href', this.href );
3898 } else {
3899 this.$button.removeAttr( 'href' );
3900 }
3901
3902 return this;
3903 };
3904
3905 /**
3906 * Handle disable events.
3907 *
3908 * @private
3909 * @param {boolean} disabled Element is disabled
3910 */
3911 OO.ui.ButtonWidget.prototype.onDisable = function () {
3912 this.updateHref();
3913 };
3914
3915 /**
3916 * Set hyperlink target.
3917 *
3918 * @param {string|null} target Hyperlink target, null to remove
3919 * @return {OO.ui.Widget} The widget, for chaining
3920 */
3921 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
3922 target = typeof target === 'string' ? target : null;
3923
3924 if ( target !== this.target ) {
3925 this.target = target;
3926 if ( target !== null ) {
3927 this.$button.attr( 'target', target );
3928 } else {
3929 this.$button.removeAttr( 'target' );
3930 }
3931 }
3932
3933 return this;
3934 };
3935
3936 /**
3937 * Set search engine traversal hint.
3938 *
3939 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3940 * @return {OO.ui.Widget} The widget, for chaining
3941 */
3942 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
3943 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
3944
3945 if ( noFollow !== this.noFollow ) {
3946 this.noFollow = noFollow;
3947 if ( noFollow ) {
3948 this.$button.attr( 'rel', 'nofollow' );
3949 } else {
3950 this.$button.removeAttr( 'rel' );
3951 }
3952 }
3953
3954 return this;
3955 };
3956
3957 // Override method visibility hints from ButtonElement
3958 /**
3959 * @method setActive
3960 * @inheritdoc
3961 */
3962 /**
3963 * @method isActive
3964 * @inheritdoc
3965 */
3966
3967 /**
3968 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3969 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3970 * removed, and cleared from the group.
3971 *
3972 * @example
3973 * // A ButtonGroupWidget with two buttons.
3974 * var button1 = new OO.ui.PopupButtonWidget( {
3975 * label: 'Select a category',
3976 * icon: 'menu',
3977 * popup: {
3978 * $content: $( '<p>List of categories…</p>' ),
3979 * padded: true,
3980 * align: 'left'
3981 * }
3982 * } ),
3983 * button2 = new OO.ui.ButtonWidget( {
3984 * label: 'Add item'
3985 * } ),
3986 * buttonGroup = new OO.ui.ButtonGroupWidget( {
3987 * items: [ button1, button2 ]
3988 * } );
3989 * $( document.body ).append( buttonGroup.$element );
3990 *
3991 * @class
3992 * @extends OO.ui.Widget
3993 * @mixins OO.ui.mixin.GroupElement
3994 * @mixins OO.ui.mixin.TitledElement
3995 *
3996 * @constructor
3997 * @param {Object} [config] Configuration options
3998 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
3999 */
4000 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
4001 // Configuration initialization
4002 config = config || {};
4003
4004 // Parent constructor
4005 OO.ui.ButtonGroupWidget.parent.call( this, config );
4006
4007 // Mixin constructors
4008 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
4009 OO.ui.mixin.TitledElement.call( this, config );
4010
4011 // Initialization
4012 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
4013 if ( Array.isArray( config.items ) ) {
4014 this.addItems( config.items );
4015 }
4016 };
4017
4018 /* Setup */
4019
4020 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
4021 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.GroupElement );
4022 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.TitledElement );
4023
4024 /* Static Properties */
4025
4026 /**
4027 * @static
4028 * @inheritdoc
4029 */
4030 OO.ui.ButtonGroupWidget.static.tagName = 'span';
4031
4032 /* Methods */
4033
4034 /**
4035 * Focus the widget
4036 *
4037 * @chainable
4038 * @return {OO.ui.Widget} The widget, for chaining
4039 */
4040 OO.ui.ButtonGroupWidget.prototype.focus = function () {
4041 if ( !this.isDisabled() ) {
4042 if ( this.items[ 0 ] ) {
4043 this.items[ 0 ].focus();
4044 }
4045 }
4046 return this;
4047 };
4048
4049 /**
4050 * @inheritdoc
4051 */
4052 OO.ui.ButtonGroupWidget.prototype.simulateLabelClick = function () {
4053 this.focus();
4054 };
4055
4056 /**
4057 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
4058 * which creates a label that identifies the icon’s function. See the [OOUI documentation on MediaWiki] [1]
4059 * for a list of icons included in the library.
4060 *
4061 * @example
4062 * // An IconWidget with a label via LabelWidget.
4063 * var myIcon = new OO.ui.IconWidget( {
4064 * icon: 'help',
4065 * title: 'Help'
4066 * } ),
4067 * // Create a label.
4068 * iconLabel = new OO.ui.LabelWidget( {
4069 * label: 'Help'
4070 * } );
4071 * $( document.body ).append( myIcon.$element, iconLabel.$element );
4072 *
4073 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
4074 *
4075 * @class
4076 * @extends OO.ui.Widget
4077 * @mixins OO.ui.mixin.IconElement
4078 * @mixins OO.ui.mixin.TitledElement
4079 * @mixins OO.ui.mixin.LabelElement
4080 * @mixins OO.ui.mixin.FlaggedElement
4081 *
4082 * @constructor
4083 * @param {Object} [config] Configuration options
4084 */
4085 OO.ui.IconWidget = function OoUiIconWidget( config ) {
4086 // Configuration initialization
4087 config = config || {};
4088
4089 // Parent constructor
4090 OO.ui.IconWidget.parent.call( this, config );
4091
4092 // Mixin constructors
4093 OO.ui.mixin.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
4094 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
4095 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element, invisibleLabel: true } ) );
4096 OO.ui.mixin.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) );
4097
4098 // Initialization
4099 this.$element.addClass( 'oo-ui-iconWidget' );
4100 // Remove class added by LabelElement initialization. It causes unexpected CSS to apply when
4101 // nested in other widgets, because this widget used to not mix in LabelElement.
4102 this.$element.removeClass( 'oo-ui-labelElement-label' );
4103 };
4104
4105 /* Setup */
4106
4107 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
4108 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.IconElement );
4109 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.TitledElement );
4110 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.LabelElement );
4111 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.FlaggedElement );
4112
4113 /* Static Properties */
4114
4115 /**
4116 * @static
4117 * @inheritdoc
4118 */
4119 OO.ui.IconWidget.static.tagName = 'span';
4120
4121 /**
4122 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
4123 * attention to the status of an item or to clarify the function within a control. For a list of
4124 * indicators included in the library, please see the [OOUI documentation on MediaWiki][1].
4125 *
4126 * @example
4127 * // An indicator widget.
4128 * var indicator1 = new OO.ui.IndicatorWidget( {
4129 * indicator: 'required'
4130 * } ),
4131 * // Create a fieldset layout to add a label.
4132 * fieldset = new OO.ui.FieldsetLayout();
4133 * fieldset.addItems( [
4134 * new OO.ui.FieldLayout( indicator1, {
4135 * label: 'A required indicator:'
4136 * } )
4137 * ] );
4138 * $( document.body ).append( fieldset.$element );
4139 *
4140 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
4141 *
4142 * @class
4143 * @extends OO.ui.Widget
4144 * @mixins OO.ui.mixin.IndicatorElement
4145 * @mixins OO.ui.mixin.TitledElement
4146 * @mixins OO.ui.mixin.LabelElement
4147 *
4148 * @constructor
4149 * @param {Object} [config] Configuration options
4150 */
4151 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
4152 // Configuration initialization
4153 config = config || {};
4154
4155 // Parent constructor
4156 OO.ui.IndicatorWidget.parent.call( this, config );
4157
4158 // Mixin constructors
4159 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
4160 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
4161 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element, invisibleLabel: true } ) );
4162
4163 // Initialization
4164 this.$element.addClass( 'oo-ui-indicatorWidget' );
4165 // Remove class added by LabelElement initialization. It causes unexpected CSS to apply when
4166 // nested in other widgets, because this widget used to not mix in LabelElement.
4167 this.$element.removeClass( 'oo-ui-labelElement-label' );
4168 };
4169
4170 /* Setup */
4171
4172 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
4173 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.IndicatorElement );
4174 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.TitledElement );
4175 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.LabelElement );
4176
4177 /* Static Properties */
4178
4179 /**
4180 * @static
4181 * @inheritdoc
4182 */
4183 OO.ui.IndicatorWidget.static.tagName = 'span';
4184
4185 /**
4186 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
4187 * be configured with a `label` option that is set to a string, a label node, or a function:
4188 *
4189 * - String: a plaintext string
4190 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
4191 * label that includes a link or special styling, such as a gray color or additional graphical elements.
4192 * - Function: a function that will produce a string in the future. Functions are used
4193 * in cases where the value of the label is not currently defined.
4194 *
4195 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
4196 * will come into focus when the label is clicked.
4197 *
4198 * @example
4199 * // Two LabelWidgets.
4200 * var label1 = new OO.ui.LabelWidget( {
4201 * label: 'plaintext label'
4202 * } ),
4203 * label2 = new OO.ui.LabelWidget( {
4204 * label: $( '<a>' ).attr( 'href', 'default.html' ).text( 'jQuery label' )
4205 * } ),
4206 * // Create a fieldset layout with fields for each example.
4207 * fieldset = new OO.ui.FieldsetLayout();
4208 * fieldset.addItems( [
4209 * new OO.ui.FieldLayout( label1 ),
4210 * new OO.ui.FieldLayout( label2 )
4211 * ] );
4212 * $( document.body ).append( fieldset.$element );
4213 *
4214 * @class
4215 * @extends OO.ui.Widget
4216 * @mixins OO.ui.mixin.LabelElement
4217 * @mixins OO.ui.mixin.TitledElement
4218 *
4219 * @constructor
4220 * @param {Object} [config] Configuration options
4221 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
4222 * Clicking the label will focus the specified input field.
4223 */
4224 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
4225 // Configuration initialization
4226 config = config || {};
4227
4228 // Parent constructor
4229 OO.ui.LabelWidget.parent.call( this, config );
4230
4231 // Mixin constructors
4232 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
4233 OO.ui.mixin.TitledElement.call( this, config );
4234
4235 // Properties
4236 this.input = config.input;
4237
4238 // Initialization
4239 if ( this.input ) {
4240 if ( this.input.getInputId() ) {
4241 this.$element.attr( 'for', this.input.getInputId() );
4242 } else {
4243 this.$label.on( 'click', function () {
4244 this.input.simulateLabelClick();
4245 }.bind( this ) );
4246 }
4247 }
4248 this.$element.addClass( 'oo-ui-labelWidget' );
4249 };
4250
4251 /* Setup */
4252
4253 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
4254 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.LabelElement );
4255 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.TitledElement );
4256
4257 /* Static Properties */
4258
4259 /**
4260 * @static
4261 * @inheritdoc
4262 */
4263 OO.ui.LabelWidget.static.tagName = 'label';
4264
4265 /**
4266 * PendingElement is a mixin that is used to create elements that notify users that something is happening
4267 * and that they should wait before proceeding. The pending state is visually represented with a pending
4268 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
4269 * field of a {@link OO.ui.TextInputWidget text input widget}.
4270 *
4271 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
4272 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
4273 * in process dialogs.
4274 *
4275 * @example
4276 * function MessageDialog( config ) {
4277 * MessageDialog.parent.call( this, config );
4278 * }
4279 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
4280 *
4281 * MessageDialog.static.name = 'myMessageDialog';
4282 * MessageDialog.static.actions = [
4283 * { action: 'save', label: 'Done', flags: 'primary' },
4284 * { label: 'Cancel', flags: 'safe' }
4285 * ];
4286 *
4287 * MessageDialog.prototype.initialize = function () {
4288 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
4289 * this.content = new OO.ui.PanelLayout( { padded: true } );
4290 * 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>' );
4291 * this.$body.append( this.content.$element );
4292 * };
4293 * MessageDialog.prototype.getBodyHeight = function () {
4294 * return 100;
4295 * }
4296 * MessageDialog.prototype.getActionProcess = function ( action ) {
4297 * var dialog = this;
4298 * if ( action === 'save' ) {
4299 * dialog.getActions().get({actions: 'save'})[0].pushPending();
4300 * return new OO.ui.Process()
4301 * .next( 1000 )
4302 * .next( function () {
4303 * dialog.getActions().get({actions: 'save'})[0].popPending();
4304 * } );
4305 * }
4306 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
4307 * };
4308 *
4309 * var windowManager = new OO.ui.WindowManager();
4310 * $( document.body ).append( windowManager.$element );
4311 *
4312 * var dialog = new MessageDialog();
4313 * windowManager.addWindows( [ dialog ] );
4314 * windowManager.openWindow( dialog );
4315 *
4316 * @abstract
4317 * @class
4318 *
4319 * @constructor
4320 * @param {Object} [config] Configuration options
4321 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
4322 */
4323 OO.ui.mixin.PendingElement = function OoUiMixinPendingElement( config ) {
4324 // Configuration initialization
4325 config = config || {};
4326
4327 // Properties
4328 this.pending = 0;
4329 this.$pending = null;
4330
4331 // Initialisation
4332 this.setPendingElement( config.$pending || this.$element );
4333 };
4334
4335 /* Setup */
4336
4337 OO.initClass( OO.ui.mixin.PendingElement );
4338
4339 /* Methods */
4340
4341 /**
4342 * Set the pending element (and clean up any existing one).
4343 *
4344 * @param {jQuery} $pending The element to set to pending.
4345 */
4346 OO.ui.mixin.PendingElement.prototype.setPendingElement = function ( $pending ) {
4347 if ( this.$pending ) {
4348 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
4349 }
4350
4351 this.$pending = $pending;
4352 if ( this.pending > 0 ) {
4353 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
4354 }
4355 };
4356
4357 /**
4358 * Check if an element is pending.
4359 *
4360 * @return {boolean} Element is pending
4361 */
4362 OO.ui.mixin.PendingElement.prototype.isPending = function () {
4363 return !!this.pending;
4364 };
4365
4366 /**
4367 * Increase the pending counter. The pending state will remain active until the counter is zero
4368 * (i.e., the number of calls to #pushPending and #popPending is the same).
4369 *
4370 * @chainable
4371 * @return {OO.ui.Element} The element, for chaining
4372 */
4373 OO.ui.mixin.PendingElement.prototype.pushPending = function () {
4374 if ( this.pending === 0 ) {
4375 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
4376 this.updateThemeClasses();
4377 }
4378 this.pending++;
4379
4380 return this;
4381 };
4382
4383 /**
4384 * Decrease the pending counter. The pending state will remain active until the counter is zero
4385 * (i.e., the number of calls to #pushPending and #popPending is the same).
4386 *
4387 * @chainable
4388 * @return {OO.ui.Element} The element, for chaining
4389 */
4390 OO.ui.mixin.PendingElement.prototype.popPending = function () {
4391 if ( this.pending === 1 ) {
4392 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
4393 this.updateThemeClasses();
4394 }
4395 this.pending = Math.max( 0, this.pending - 1 );
4396
4397 return this;
4398 };
4399
4400 /**
4401 * Element that will stick adjacent to a specified container, even when it is inserted elsewhere
4402 * in the document (for example, in an OO.ui.Window's $overlay).
4403 *
4404 * The elements's position is automatically calculated and maintained when window is resized or the
4405 * page is scrolled. If you reposition the container manually, you have to call #position to make
4406 * sure the element is still placed correctly.
4407 *
4408 * As positioning is only possible when both the element and the container are attached to the DOM
4409 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
4410 * the #toggle method to display a floating popup, for example.
4411 *
4412 * @abstract
4413 * @class
4414 *
4415 * @constructor
4416 * @param {Object} [config] Configuration options
4417 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
4418 * @cfg {jQuery} [$floatableContainer] Node to position adjacent to
4419 * @cfg {string} [verticalPosition='below'] Where to position $floatable vertically:
4420 * 'below': Directly below $floatableContainer, aligning f's top edge with fC's bottom edge
4421 * 'above': Directly above $floatableContainer, aligning f's bottom edge with fC's top edge
4422 * 'top': Align the top edge with $floatableContainer's top edge
4423 * 'bottom': Align the bottom edge with $floatableContainer's bottom edge
4424 * 'center': Vertically align the center with $floatableContainer's center
4425 * @cfg {string} [horizontalPosition='start'] Where to position $floatable horizontally:
4426 * 'before': Directly before $floatableContainer, aligning f's end edge with fC's start edge
4427 * 'after': Directly after $floatableContainer, aligning f's start edge with fC's end edge
4428 * 'start': Align the start (left in LTR, right in RTL) edge with $floatableContainer's start edge
4429 * 'end': Align the end (right in LTR, left in RTL) edge with $floatableContainer's end edge
4430 * 'center': Horizontally align the center with $floatableContainer's center
4431 * @cfg {boolean} [hideWhenOutOfView=true] Whether to hide the floatable element if the container
4432 * is out of view
4433 */
4434 OO.ui.mixin.FloatableElement = function OoUiMixinFloatableElement( config ) {
4435 // Configuration initialization
4436 config = config || {};
4437
4438 // Properties
4439 this.$floatable = null;
4440 this.$floatableContainer = null;
4441 this.$floatableWindow = null;
4442 this.$floatableClosestScrollable = null;
4443 this.floatableOutOfView = false;
4444 this.onFloatableScrollHandler = this.position.bind( this );
4445 this.onFloatableWindowResizeHandler = this.position.bind( this );
4446
4447 // Initialization
4448 this.setFloatableContainer( config.$floatableContainer );
4449 this.setFloatableElement( config.$floatable || this.$element );
4450 this.setVerticalPosition( config.verticalPosition || 'below' );
4451 this.setHorizontalPosition( config.horizontalPosition || 'start' );
4452 this.hideWhenOutOfView = config.hideWhenOutOfView === undefined ? true : !!config.hideWhenOutOfView;
4453 };
4454
4455 /* Methods */
4456
4457 /**
4458 * Set floatable element.
4459 *
4460 * If an element is already set, it will be cleaned up before setting up the new element.
4461 *
4462 * @param {jQuery} $floatable Element to make floatable
4463 */
4464 OO.ui.mixin.FloatableElement.prototype.setFloatableElement = function ( $floatable ) {
4465 if ( this.$floatable ) {
4466 this.$floatable.removeClass( 'oo-ui-floatableElement-floatable' );
4467 this.$floatable.css( { left: '', top: '' } );
4468 }
4469
4470 this.$floatable = $floatable.addClass( 'oo-ui-floatableElement-floatable' );
4471 this.position();
4472 };
4473
4474 /**
4475 * Set floatable container.
4476 *
4477 * The element will be positioned relative to the specified container.
4478 *
4479 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
4480 */
4481 OO.ui.mixin.FloatableElement.prototype.setFloatableContainer = function ( $floatableContainer ) {
4482 this.$floatableContainer = $floatableContainer;
4483 if ( this.$floatable ) {
4484 this.position();
4485 }
4486 };
4487
4488 /**
4489 * Change how the element is positioned vertically.
4490 *
4491 * @param {string} position 'below', 'above', 'top', 'bottom' or 'center'
4492 */
4493 OO.ui.mixin.FloatableElement.prototype.setVerticalPosition = function ( position ) {
4494 if ( [ 'below', 'above', 'top', 'bottom', 'center' ].indexOf( position ) === -1 ) {
4495 throw new Error( 'Invalid value for vertical position: ' + position );
4496 }
4497 if ( this.verticalPosition !== position ) {
4498 this.verticalPosition = position;
4499 if ( this.$floatable ) {
4500 this.position();
4501 }
4502 }
4503 };
4504
4505 /**
4506 * Change how the element is positioned horizontally.
4507 *
4508 * @param {string} position 'before', 'after', 'start', 'end' or 'center'
4509 */
4510 OO.ui.mixin.FloatableElement.prototype.setHorizontalPosition = function ( position ) {
4511 if ( [ 'before', 'after', 'start', 'end', 'center' ].indexOf( position ) === -1 ) {
4512 throw new Error( 'Invalid value for horizontal position: ' + position );
4513 }
4514 if ( this.horizontalPosition !== position ) {
4515 this.horizontalPosition = position;
4516 if ( this.$floatable ) {
4517 this.position();
4518 }
4519 }
4520 };
4521
4522 /**
4523 * Toggle positioning.
4524 *
4525 * Do not turn positioning on until after the element is attached to the DOM and visible.
4526 *
4527 * @param {boolean} [positioning] Enable positioning, omit to toggle
4528 * @chainable
4529 * @return {OO.ui.Element} The element, for chaining
4530 */
4531 OO.ui.mixin.FloatableElement.prototype.togglePositioning = function ( positioning ) {
4532 var closestScrollableOfContainer;
4533
4534 if ( !this.$floatable || !this.$floatableContainer ) {
4535 return this;
4536 }
4537
4538 positioning = positioning === undefined ? !this.positioning : !!positioning;
4539
4540 if ( positioning && !this.warnedUnattached && !this.isElementAttached() ) {
4541 OO.ui.warnDeprecation( 'FloatableElement#togglePositioning: Before calling this method, the element must be attached to the DOM.' );
4542 this.warnedUnattached = true;
4543 }
4544
4545 if ( this.positioning !== positioning ) {
4546 this.positioning = positioning;
4547
4548 closestScrollableOfContainer = OO.ui.Element.static.getClosestScrollableContainer( this.$floatableContainer[ 0 ] );
4549 // If the scrollable is the root, we have to listen to scroll events
4550 // on the window because of browser inconsistencies.
4551 if ( $( closestScrollableOfContainer ).is( 'html, body' ) ) {
4552 closestScrollableOfContainer = OO.ui.Element.static.getWindow( closestScrollableOfContainer );
4553 }
4554
4555 if ( positioning ) {
4556 this.$floatableWindow = $( this.getElementWindow() );
4557 this.$floatableWindow.on( 'resize', this.onFloatableWindowResizeHandler );
4558
4559 this.$floatableClosestScrollable = $( closestScrollableOfContainer );
4560 this.$floatableClosestScrollable.on( 'scroll', this.onFloatableScrollHandler );
4561
4562 // Initial position after visible
4563 this.position();
4564 } else {
4565 if ( this.$floatableWindow ) {
4566 this.$floatableWindow.off( 'resize', this.onFloatableWindowResizeHandler );
4567 this.$floatableWindow = null;
4568 }
4569
4570 if ( this.$floatableClosestScrollable ) {
4571 this.$floatableClosestScrollable.off( 'scroll', this.onFloatableScrollHandler );
4572 this.$floatableClosestScrollable = null;
4573 }
4574
4575 this.$floatable.css( { left: '', right: '', top: '' } );
4576 }
4577 }
4578
4579 return this;
4580 };
4581
4582 /**
4583 * Check whether the bottom edge of the given element is within the viewport of the given container.
4584 *
4585 * @private
4586 * @param {jQuery} $element
4587 * @param {jQuery} $container
4588 * @return {boolean}
4589 */
4590 OO.ui.mixin.FloatableElement.prototype.isElementInViewport = function ( $element, $container ) {
4591 var elemRect, contRect, topEdgeInBounds, bottomEdgeInBounds, leftEdgeInBounds, rightEdgeInBounds,
4592 startEdgeInBounds, endEdgeInBounds, viewportSpacing,
4593 direction = $element.css( 'direction' );
4594
4595 elemRect = $element[ 0 ].getBoundingClientRect();
4596 if ( $container[ 0 ] === window ) {
4597 viewportSpacing = OO.ui.getViewportSpacing();
4598 contRect = {
4599 top: 0,
4600 left: 0,
4601 right: document.documentElement.clientWidth,
4602 bottom: document.documentElement.clientHeight
4603 };
4604 contRect.top += viewportSpacing.top;
4605 contRect.left += viewportSpacing.left;
4606 contRect.right -= viewportSpacing.right;
4607 contRect.bottom -= viewportSpacing.bottom;
4608 } else {
4609 contRect = $container[ 0 ].getBoundingClientRect();
4610 }
4611
4612 topEdgeInBounds = elemRect.top >= contRect.top && elemRect.top <= contRect.bottom;
4613 bottomEdgeInBounds = elemRect.bottom >= contRect.top && elemRect.bottom <= contRect.bottom;
4614 leftEdgeInBounds = elemRect.left >= contRect.left && elemRect.left <= contRect.right;
4615 rightEdgeInBounds = elemRect.right >= contRect.left && elemRect.right <= contRect.right;
4616 if ( direction === 'rtl' ) {
4617 startEdgeInBounds = rightEdgeInBounds;
4618 endEdgeInBounds = leftEdgeInBounds;
4619 } else {
4620 startEdgeInBounds = leftEdgeInBounds;
4621 endEdgeInBounds = rightEdgeInBounds;
4622 }
4623
4624 if ( this.verticalPosition === 'below' && !bottomEdgeInBounds ) {
4625 return false;
4626 }
4627 if ( this.verticalPosition === 'above' && !topEdgeInBounds ) {
4628 return false;
4629 }
4630 if ( this.horizontalPosition === 'before' && !startEdgeInBounds ) {
4631 return false;
4632 }
4633 if ( this.horizontalPosition === 'after' && !endEdgeInBounds ) {
4634 return false;
4635 }
4636
4637 // The other positioning values are all about being inside the container,
4638 // so in those cases all we care about is that any part of the container is visible.
4639 return elemRect.top <= contRect.bottom && elemRect.bottom >= contRect.top &&
4640 elemRect.left <= contRect.right && elemRect.right >= contRect.left;
4641 };
4642
4643 /**
4644 * Check if the floatable is hidden to the user because it was offscreen.
4645 *
4646 * @return {boolean} Floatable is out of view
4647 */
4648 OO.ui.mixin.FloatableElement.prototype.isFloatableOutOfView = function () {
4649 return this.floatableOutOfView;
4650 };
4651
4652 /**
4653 * Position the floatable below its container.
4654 *
4655 * This should only be done when both of them are attached to the DOM and visible.
4656 *
4657 * @chainable
4658 * @return {OO.ui.Element} The element, for chaining
4659 */
4660 OO.ui.mixin.FloatableElement.prototype.position = function () {
4661 if ( !this.positioning ) {
4662 return this;
4663 }
4664
4665 if ( !(
4666 // To continue, some things need to be true:
4667 // The element must actually be in the DOM
4668 this.isElementAttached() && (
4669 // The closest scrollable is the current window
4670 this.$floatableClosestScrollable[ 0 ] === this.getElementWindow() ||
4671 // OR is an element in the element's DOM
4672 $.contains( this.getElementDocument(), this.$floatableClosestScrollable[ 0 ] )
4673 )
4674 ) ) {
4675 // Abort early if important parts of the widget are no longer attached to the DOM
4676 return this;
4677 }
4678
4679 this.floatableOutOfView = this.hideWhenOutOfView && !this.isElementInViewport( this.$floatableContainer, this.$floatableClosestScrollable );
4680 if ( this.floatableOutOfView ) {
4681 this.$floatable.addClass( 'oo-ui-element-hidden' );
4682 return this;
4683 } else {
4684 this.$floatable.removeClass( 'oo-ui-element-hidden' );
4685 }
4686
4687 this.$floatable.css( this.computePosition() );
4688
4689 // We updated the position, so re-evaluate the clipping state.
4690 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
4691 // will not notice the need to update itself.)
4692 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
4693 // it not listen to the right events in the right places?
4694 if ( this.clip ) {
4695 this.clip();
4696 }
4697
4698 return this;
4699 };
4700
4701 /**
4702 * Compute how #$floatable should be positioned based on the position of #$floatableContainer
4703 * and the positioning settings. This is a helper for #position that shouldn't be called directly,
4704 * but may be overridden by subclasses if they want to change or add to the positioning logic.
4705 *
4706 * @return {Object} New position to apply with .css(). Keys are 'top', 'left', 'bottom' and 'right'.
4707 */
4708 OO.ui.mixin.FloatableElement.prototype.computePosition = function () {
4709 var isBody, scrollableX, scrollableY, containerPos,
4710 horizScrollbarHeight, vertScrollbarWidth, scrollTop, scrollLeft,
4711 newPos = { top: '', left: '', bottom: '', right: '' },
4712 direction = this.$floatableContainer.css( 'direction' ),
4713 $offsetParent = this.$floatable.offsetParent();
4714
4715 if ( $offsetParent.is( 'html' ) ) {
4716 // The innerHeight/Width and clientHeight/Width calculations don't work well on the
4717 // <html> element, but they do work on the <body>
4718 $offsetParent = $( $offsetParent[ 0 ].ownerDocument.body );
4719 }
4720 isBody = $offsetParent.is( 'body' );
4721 scrollableX = $offsetParent.css( 'overflow-x' ) === 'scroll' || $offsetParent.css( 'overflow-x' ) === 'auto';
4722 scrollableY = $offsetParent.css( 'overflow-y' ) === 'scroll' || $offsetParent.css( 'overflow-y' ) === 'auto';
4723
4724 vertScrollbarWidth = $offsetParent.innerWidth() - $offsetParent.prop( 'clientWidth' );
4725 horizScrollbarHeight = $offsetParent.innerHeight() - $offsetParent.prop( 'clientHeight' );
4726 // We don't need to compute and add scrollTop and scrollLeft if the scrollable container is the body,
4727 // or if it isn't scrollable
4728 scrollTop = scrollableY && !isBody ? $offsetParent.scrollTop() : 0;
4729 scrollLeft = scrollableX && !isBody ? OO.ui.Element.static.getScrollLeft( $offsetParent[ 0 ] ) : 0;
4730
4731 // Avoid passing the <body> to getRelativePosition(), because it won't return what we expect
4732 // if the <body> has a margin
4733 containerPos = isBody ?
4734 this.$floatableContainer.offset() :
4735 OO.ui.Element.static.getRelativePosition( this.$floatableContainer, $offsetParent );
4736 containerPos.bottom = containerPos.top + this.$floatableContainer.outerHeight();
4737 containerPos.right = containerPos.left + this.$floatableContainer.outerWidth();
4738 containerPos.start = direction === 'rtl' ? containerPos.right : containerPos.left;
4739 containerPos.end = direction === 'rtl' ? containerPos.left : containerPos.right;
4740
4741 if ( this.verticalPosition === 'below' ) {
4742 newPos.top = containerPos.bottom;
4743 } else if ( this.verticalPosition === 'above' ) {
4744 newPos.bottom = $offsetParent.outerHeight() - containerPos.top;
4745 } else if ( this.verticalPosition === 'top' ) {
4746 newPos.top = containerPos.top;
4747 } else if ( this.verticalPosition === 'bottom' ) {
4748 newPos.bottom = $offsetParent.outerHeight() - containerPos.bottom;
4749 } else if ( this.verticalPosition === 'center' ) {
4750 newPos.top = containerPos.top +
4751 ( this.$floatableContainer.height() - this.$floatable.height() ) / 2;
4752 }
4753
4754 if ( this.horizontalPosition === 'before' ) {
4755 newPos.end = containerPos.start;
4756 } else if ( this.horizontalPosition === 'after' ) {
4757 newPos.start = containerPos.end;
4758 } else if ( this.horizontalPosition === 'start' ) {
4759 newPos.start = containerPos.start;
4760 } else if ( this.horizontalPosition === 'end' ) {
4761 newPos.end = containerPos.end;
4762 } else if ( this.horizontalPosition === 'center' ) {
4763 newPos.left = containerPos.left +
4764 ( this.$floatableContainer.width() - this.$floatable.width() ) / 2;
4765 }
4766
4767 if ( newPos.start !== undefined ) {
4768 if ( direction === 'rtl' ) {
4769 newPos.right = ( isBody ? $( $offsetParent[ 0 ].ownerDocument.documentElement ) : $offsetParent ).outerWidth() - newPos.start;
4770 } else {
4771 newPos.left = newPos.start;
4772 }
4773 delete newPos.start;
4774 }
4775 if ( newPos.end !== undefined ) {
4776 if ( direction === 'rtl' ) {
4777 newPos.left = newPos.end;
4778 } else {
4779 newPos.right = ( isBody ? $( $offsetParent[ 0 ].ownerDocument.documentElement ) : $offsetParent ).outerWidth() - newPos.end;
4780 }
4781 delete newPos.end;
4782 }
4783
4784 // Account for scroll position
4785 if ( newPos.top !== '' ) {
4786 newPos.top += scrollTop;
4787 }
4788 if ( newPos.bottom !== '' ) {
4789 newPos.bottom -= scrollTop;
4790 }
4791 if ( newPos.left !== '' ) {
4792 newPos.left += scrollLeft;
4793 }
4794 if ( newPos.right !== '' ) {
4795 newPos.right -= scrollLeft;
4796 }
4797
4798 // Account for scrollbar gutter
4799 if ( newPos.bottom !== '' ) {
4800 newPos.bottom -= horizScrollbarHeight;
4801 }
4802 if ( direction === 'rtl' ) {
4803 if ( newPos.left !== '' ) {
4804 newPos.left -= vertScrollbarWidth;
4805 }
4806 } else {
4807 if ( newPos.right !== '' ) {
4808 newPos.right -= vertScrollbarWidth;
4809 }
4810 }
4811
4812 return newPos;
4813 };
4814
4815 /**
4816 * Element that can be automatically clipped to visible boundaries.
4817 *
4818 * Whenever the element's natural height changes, you have to call
4819 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
4820 * clipping correctly.
4821 *
4822 * The dimensions of #$clippableContainer will be compared to the boundaries of the
4823 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
4824 * then #$clippable will be given a fixed reduced height and/or width and will be made
4825 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
4826 * but you can build a static footer by setting #$clippableContainer to an element that contains
4827 * #$clippable and the footer.
4828 *
4829 * @abstract
4830 * @class
4831 *
4832 * @constructor
4833 * @param {Object} [config] Configuration options
4834 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
4835 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
4836 * omit to use #$clippable
4837 */
4838 OO.ui.mixin.ClippableElement = function OoUiMixinClippableElement( config ) {
4839 // Configuration initialization
4840 config = config || {};
4841
4842 // Properties
4843 this.$clippable = null;
4844 this.$clippableContainer = null;
4845 this.clipping = false;
4846 this.clippedHorizontally = false;
4847 this.clippedVertically = false;
4848 this.$clippableScrollableContainer = null;
4849 this.$clippableScroller = null;
4850 this.$clippableWindow = null;
4851 this.idealWidth = null;
4852 this.idealHeight = null;
4853 this.onClippableScrollHandler = this.clip.bind( this );
4854 this.onClippableWindowResizeHandler = this.clip.bind( this );
4855
4856 // Initialization
4857 if ( config.$clippableContainer ) {
4858 this.setClippableContainer( config.$clippableContainer );
4859 }
4860 this.setClippableElement( config.$clippable || this.$element );
4861 };
4862
4863 /* Methods */
4864
4865 /**
4866 * Set clippable element.
4867 *
4868 * If an element is already set, it will be cleaned up before setting up the new element.
4869 *
4870 * @param {jQuery} $clippable Element to make clippable
4871 */
4872 OO.ui.mixin.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
4873 if ( this.$clippable ) {
4874 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
4875 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
4876 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
4877 }
4878
4879 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
4880 this.clip();
4881 };
4882
4883 /**
4884 * Set clippable container.
4885 *
4886 * This is the container that will be measured when deciding whether to clip. When clipping,
4887 * #$clippable will be resized in order to keep the clippable container fully visible.
4888 *
4889 * If the clippable container is unset, #$clippable will be used.
4890 *
4891 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
4892 */
4893 OO.ui.mixin.ClippableElement.prototype.setClippableContainer = function ( $clippableContainer ) {
4894 this.$clippableContainer = $clippableContainer;
4895 if ( this.$clippable ) {
4896 this.clip();
4897 }
4898 };
4899
4900 /**
4901 * Toggle clipping.
4902 *
4903 * Do not turn clipping on until after the element is attached to the DOM and visible.
4904 *
4905 * @param {boolean} [clipping] Enable clipping, omit to toggle
4906 * @chainable
4907 * @return {OO.ui.Element} The element, for chaining
4908 */
4909 OO.ui.mixin.ClippableElement.prototype.toggleClipping = function ( clipping ) {
4910 clipping = clipping === undefined ? !this.clipping : !!clipping;
4911
4912 if ( clipping && !this.warnedUnattached && !this.isElementAttached() ) {
4913 OO.ui.warnDeprecation( 'ClippableElement#toggleClipping: Before calling this method, the element must be attached to the DOM.' );
4914 this.warnedUnattached = true;
4915 }
4916
4917 if ( this.clipping !== clipping ) {
4918 this.clipping = clipping;
4919 if ( clipping ) {
4920 this.$clippableScrollableContainer = $( this.getClosestScrollableElementContainer() );
4921 // If the clippable container is the root, we have to listen to scroll events and check
4922 // jQuery.scrollTop on the window because of browser inconsistencies
4923 this.$clippableScroller = this.$clippableScrollableContainer.is( 'html, body' ) ?
4924 $( OO.ui.Element.static.getWindow( this.$clippableScrollableContainer ) ) :
4925 this.$clippableScrollableContainer;
4926 this.$clippableScroller.on( 'scroll', this.onClippableScrollHandler );
4927 this.$clippableWindow = $( this.getElementWindow() )
4928 .on( 'resize', this.onClippableWindowResizeHandler );
4929 // Initial clip after visible
4930 this.clip();
4931 } else {
4932 this.$clippable.css( {
4933 width: '',
4934 height: '',
4935 maxWidth: '',
4936 maxHeight: '',
4937 overflowX: '',
4938 overflowY: ''
4939 } );
4940 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
4941
4942 this.$clippableScrollableContainer = null;
4943 this.$clippableScroller.off( 'scroll', this.onClippableScrollHandler );
4944 this.$clippableScroller = null;
4945 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
4946 this.$clippableWindow = null;
4947 }
4948 }
4949
4950 return this;
4951 };
4952
4953 /**
4954 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4955 *
4956 * @return {boolean} Element will be clipped to the visible area
4957 */
4958 OO.ui.mixin.ClippableElement.prototype.isClipping = function () {
4959 return this.clipping;
4960 };
4961
4962 /**
4963 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
4964 *
4965 * @return {boolean} Part of the element is being clipped
4966 */
4967 OO.ui.mixin.ClippableElement.prototype.isClipped = function () {
4968 return this.clippedHorizontally || this.clippedVertically;
4969 };
4970
4971 /**
4972 * Check if the right of the element is being clipped by the nearest scrollable container.
4973 *
4974 * @return {boolean} Part of the element is being clipped
4975 */
4976 OO.ui.mixin.ClippableElement.prototype.isClippedHorizontally = function () {
4977 return this.clippedHorizontally;
4978 };
4979
4980 /**
4981 * Check if the bottom of the element is being clipped by the nearest scrollable container.
4982 *
4983 * @return {boolean} Part of the element is being clipped
4984 */
4985 OO.ui.mixin.ClippableElement.prototype.isClippedVertically = function () {
4986 return this.clippedVertically;
4987 };
4988
4989 /**
4990 * Set the ideal size. These are the dimensions #$clippable will have when it's not being clipped.
4991 *
4992 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
4993 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
4994 */
4995 OO.ui.mixin.ClippableElement.prototype.setIdealSize = function ( width, height ) {
4996 this.idealWidth = width;
4997 this.idealHeight = height;
4998
4999 if ( !this.clipping ) {
5000 // Update dimensions
5001 this.$clippable.css( { width: width, height: height } );
5002 }
5003 // While clipping, idealWidth and idealHeight are not considered
5004 };
5005
5006 /**
5007 * Return the side of the clippable on which it is "anchored" (aligned to something else).
5008 * ClippableElement will clip the opposite side when reducing element's width.
5009 *
5010 * Classes that mix in ClippableElement should override this to return 'right' if their
5011 * clippable is absolutely positioned and using 'right: Npx' (and not using 'left').
5012 * If your class also mixes in FloatableElement, this is handled automatically.
5013 *
5014 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
5015 * always in pixels, even if they were unset or set to 'auto'.)
5016 *
5017 * When in doubt, 'left' (or 'right' in RTL) is a sane fallback.
5018 *
5019 * @return {string} 'left' or 'right'
5020 */
5021 OO.ui.mixin.ClippableElement.prototype.getHorizontalAnchorEdge = function () {
5022 if ( this.computePosition && this.positioning && this.computePosition().right !== '' ) {
5023 return 'right';
5024 }
5025 return 'left';
5026 };
5027
5028 /**
5029 * Return the side of the clippable on which it is "anchored" (aligned to something else).
5030 * ClippableElement will clip the opposite side when reducing element's width.
5031 *
5032 * Classes that mix in ClippableElement should override this to return 'bottom' if their
5033 * clippable is absolutely positioned and using 'bottom: Npx' (and not using 'top').
5034 * If your class also mixes in FloatableElement, this is handled automatically.
5035 *
5036 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
5037 * always in pixels, even if they were unset or set to 'auto'.)
5038 *
5039 * When in doubt, 'top' is a sane fallback.
5040 *
5041 * @return {string} 'top' or 'bottom'
5042 */
5043 OO.ui.mixin.ClippableElement.prototype.getVerticalAnchorEdge = function () {
5044 if ( this.computePosition && this.positioning && this.computePosition().bottom !== '' ) {
5045 return 'bottom';
5046 }
5047 return 'top';
5048 };
5049
5050 /**
5051 * Clip element to visible boundaries and allow scrolling when needed. You should call this method
5052 * when the element's natural height changes.
5053 *
5054 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
5055 * overlapped by, the visible area of the nearest scrollable container.
5056 *
5057 * Because calling clip() when the natural height changes isn't always possible, we also set
5058 * max-height when the element isn't being clipped. This means that if the element tries to grow
5059 * beyond the edge, something reasonable will happen before clip() is called.
5060 *
5061 * @chainable
5062 * @return {OO.ui.Element} The element, for chaining
5063 */
5064 OO.ui.mixin.ClippableElement.prototype.clip = function () {
5065 var extraHeight, extraWidth, viewportSpacing,
5066 desiredWidth, desiredHeight, allotedWidth, allotedHeight,
5067 naturalWidth, naturalHeight, clipWidth, clipHeight,
5068 $item, itemRect, $viewport, viewportRect, availableRect,
5069 direction, vertScrollbarWidth, horizScrollbarHeight,
5070 // Extra tolerance so that the sloppy code below doesn't result in results that are off
5071 // by one or two pixels. (And also so that we have space to display drop shadows.)
5072 // Chosen by fair dice roll.
5073 buffer = 7;
5074
5075 if ( !this.clipping ) {
5076 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
5077 return this;
5078 }
5079
5080 function rectIntersection( a, b ) {
5081 var out = {};
5082 out.top = Math.max( a.top, b.top );
5083 out.left = Math.max( a.left, b.left );
5084 out.bottom = Math.min( a.bottom, b.bottom );
5085 out.right = Math.min( a.right, b.right );
5086 return out;
5087 }
5088
5089 viewportSpacing = OO.ui.getViewportSpacing();
5090
5091 if ( this.$clippableScrollableContainer.is( 'html, body' ) ) {
5092 $viewport = $( this.$clippableScrollableContainer[ 0 ].ownerDocument.body );
5093 // Dimensions of the browser window, rather than the element!
5094 viewportRect = {
5095 top: 0,
5096 left: 0,
5097 right: document.documentElement.clientWidth,
5098 bottom: document.documentElement.clientHeight
5099 };
5100 viewportRect.top += viewportSpacing.top;
5101 viewportRect.left += viewportSpacing.left;
5102 viewportRect.right -= viewportSpacing.right;
5103 viewportRect.bottom -= viewportSpacing.bottom;
5104 } else {
5105 $viewport = this.$clippableScrollableContainer;
5106 viewportRect = $viewport[ 0 ].getBoundingClientRect();
5107 // Convert into a plain object
5108 viewportRect = $.extend( {}, viewportRect );
5109 }
5110
5111 // Account for scrollbar gutter
5112 direction = $viewport.css( 'direction' );
5113 vertScrollbarWidth = $viewport.innerWidth() - $viewport.prop( 'clientWidth' );
5114 horizScrollbarHeight = $viewport.innerHeight() - $viewport.prop( 'clientHeight' );
5115 viewportRect.bottom -= horizScrollbarHeight;
5116 if ( direction === 'rtl' ) {
5117 viewportRect.left += vertScrollbarWidth;
5118 } else {
5119 viewportRect.right -= vertScrollbarWidth;
5120 }
5121
5122 // Add arbitrary tolerance
5123 viewportRect.top += buffer;
5124 viewportRect.left += buffer;
5125 viewportRect.right -= buffer;
5126 viewportRect.bottom -= buffer;
5127
5128 $item = this.$clippableContainer || this.$clippable;
5129
5130 extraHeight = $item.outerHeight() - this.$clippable.outerHeight();
5131 extraWidth = $item.outerWidth() - this.$clippable.outerWidth();
5132
5133 itemRect = $item[ 0 ].getBoundingClientRect();
5134 // Convert into a plain object
5135 itemRect = $.extend( {}, itemRect );
5136
5137 // Item might already be clipped, so we can't just use its dimensions (in case we might need to
5138 // make it larger than before). Extend the rectangle to the maximum size we are allowed to take.
5139 if ( this.getHorizontalAnchorEdge() === 'right' ) {
5140 itemRect.left = viewportRect.left;
5141 } else {
5142 itemRect.right = viewportRect.right;
5143 }
5144 if ( this.getVerticalAnchorEdge() === 'bottom' ) {
5145 itemRect.top = viewportRect.top;
5146 } else {
5147 itemRect.bottom = viewportRect.bottom;
5148 }
5149
5150 availableRect = rectIntersection( viewportRect, itemRect );
5151
5152 desiredWidth = Math.max( 0, availableRect.right - availableRect.left );
5153 desiredHeight = Math.max( 0, availableRect.bottom - availableRect.top );
5154 // It should never be desirable to exceed the dimensions of the browser viewport... right?
5155 desiredWidth = Math.min( desiredWidth,
5156 document.documentElement.clientWidth - viewportSpacing.left - viewportSpacing.right );
5157 desiredHeight = Math.min( desiredHeight,
5158 document.documentElement.clientHeight - viewportSpacing.top - viewportSpacing.right );
5159 allotedWidth = Math.ceil( desiredWidth - extraWidth );
5160 allotedHeight = Math.ceil( desiredHeight - extraHeight );
5161 naturalWidth = this.$clippable.prop( 'scrollWidth' );
5162 naturalHeight = this.$clippable.prop( 'scrollHeight' );
5163 clipWidth = allotedWidth < naturalWidth;
5164 clipHeight = allotedHeight < naturalHeight;
5165
5166 if ( clipWidth ) {
5167 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. See T157672.
5168 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
5169 this.$clippable.css( 'overflowX', 'scroll' );
5170 // eslint-disable-next-line no-void
5171 void this.$clippable[ 0 ].offsetHeight; // Force reflow
5172 this.$clippable.css( {
5173 width: Math.max( 0, allotedWidth ),
5174 maxWidth: ''
5175 } );
5176 } else {
5177 this.$clippable.css( {
5178 overflowX: '',
5179 width: this.idealWidth || '',
5180 maxWidth: Math.max( 0, allotedWidth )
5181 } );
5182 }
5183 if ( clipHeight ) {
5184 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. See T157672.
5185 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
5186 this.$clippable.css( 'overflowY', 'scroll' );
5187 // eslint-disable-next-line no-void
5188 void this.$clippable[ 0 ].offsetHeight; // Force reflow
5189 this.$clippable.css( {
5190 height: Math.max( 0, allotedHeight ),
5191 maxHeight: ''
5192 } );
5193 } else {
5194 this.$clippable.css( {
5195 overflowY: '',
5196 height: this.idealHeight || '',
5197 maxHeight: Math.max( 0, allotedHeight )
5198 } );
5199 }
5200
5201 // If we stopped clipping in at least one of the dimensions
5202 if ( ( this.clippedHorizontally && !clipWidth ) || ( this.clippedVertically && !clipHeight ) ) {
5203 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
5204 }
5205
5206 this.clippedHorizontally = clipWidth;
5207 this.clippedVertically = clipHeight;
5208
5209 return this;
5210 };
5211
5212 /**
5213 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
5214 * By default, each popup has an anchor that points toward its origin.
5215 * Please see the [OOUI documentation on MediaWiki.org] [1] for more information and examples.
5216 *
5217 * Unlike most widgets, PopupWidget is initially hidden and must be shown by calling #toggle.
5218 *
5219 * @example
5220 * // A PopupWidget.
5221 * var popup = new OO.ui.PopupWidget( {
5222 * $content: $( '<p>Hi there!</p>' ),
5223 * padded: true,
5224 * width: 300
5225 * } );
5226 *
5227 * $( document.body ).append( popup.$element );
5228 * // To display the popup, toggle the visibility to 'true'.
5229 * popup.toggle( true );
5230 *
5231 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups
5232 *
5233 * @class
5234 * @extends OO.ui.Widget
5235 * @mixins OO.ui.mixin.LabelElement
5236 * @mixins OO.ui.mixin.ClippableElement
5237 * @mixins OO.ui.mixin.FloatableElement
5238 *
5239 * @constructor
5240 * @param {Object} [config] Configuration options
5241 * @cfg {number|null} [width=320] Width of popup in pixels. Pass `null` to use automatic width.
5242 * @cfg {number|null} [height=null] Height of popup in pixels. Pass `null` to use automatic height.
5243 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
5244 * @cfg {string} [position='below'] Where to position the popup relative to $floatableContainer
5245 * 'above': Put popup above $floatableContainer; anchor points down to the horizontal center
5246 * of $floatableContainer
5247 * 'below': Put popup below $floatableContainer; anchor points up to the horizontal center
5248 * of $floatableContainer
5249 * 'before': Put popup to the left (LTR) / right (RTL) of $floatableContainer; anchor points
5250 * endwards (right/left) to the vertical center of $floatableContainer
5251 * 'after': Put popup to the right (LTR) / left (RTL) of $floatableContainer; anchor points
5252 * startwards (left/right) to the vertical center of $floatableContainer
5253 * @cfg {string} [align='center'] How to align the popup to $floatableContainer
5254 * 'forwards': If position is above/below, move the popup as far endwards (right in LTR, left in RTL)
5255 * as possible while still keeping the anchor within the popup;
5256 * if position is before/after, move the popup as far downwards as possible.
5257 * 'backwards': If position is above/below, move the popup as far startwards (left in LTR, right in RTL)
5258 * as possible while still keeping the anchor within the popup;
5259 * if position in before/after, move the popup as far upwards as possible.
5260 * 'center': Horizontally (if position is above/below) or vertically (before/after) align the center
5261 * of the popup with the center of $floatableContainer.
5262 * 'force-left': Alias for 'forwards' in LTR and 'backwards' in RTL
5263 * 'force-right': Alias for 'backwards' in RTL and 'forwards' in LTR
5264 * @cfg {boolean} [autoFlip=true] Whether to automatically switch the popup's position between
5265 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5266 * desired direction to display the popup without clipping
5267 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
5268 * See the [OOUI docs on MediaWiki][3] for an example.
5269 * [3]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#containerExample
5270 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
5271 * @cfg {jQuery} [$content] Content to append to the popup's body
5272 * @cfg {jQuery} [$footer] Content to append to the popup's footer
5273 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
5274 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
5275 * This config option is only relevant if #autoClose is set to `true`. See the [OOUI documentation on MediaWiki][2]
5276 * for an example.
5277 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#autocloseExample
5278 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
5279 * button.
5280 * @cfg {boolean} [padded=false] Add padding to the popup's body
5281 */
5282 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
5283 // Configuration initialization
5284 config = config || {};
5285
5286 // Parent constructor
5287 OO.ui.PopupWidget.parent.call( this, config );
5288
5289 // Properties (must be set before ClippableElement constructor call)
5290 this.$body = $( '<div>' );
5291 this.$popup = $( '<div>' );
5292
5293 // Mixin constructors
5294 OO.ui.mixin.LabelElement.call( this, config );
5295 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, {
5296 $clippable: this.$body,
5297 $clippableContainer: this.$popup
5298 } ) );
5299 OO.ui.mixin.FloatableElement.call( this, config );
5300
5301 // Properties
5302 this.$anchor = $( '<div>' );
5303 // If undefined, will be computed lazily in computePosition()
5304 this.$container = config.$container;
5305 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
5306 this.autoClose = !!config.autoClose;
5307 this.transitionTimeout = null;
5308 this.anchored = false;
5309 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
5310 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
5311
5312 // Initialization
5313 this.setSize( config.width, config.height );
5314 this.toggleAnchor( config.anchor === undefined || config.anchor );
5315 this.setAlignment( config.align || 'center' );
5316 this.setPosition( config.position || 'below' );
5317 this.setAutoFlip( config.autoFlip === undefined || config.autoFlip );
5318 this.setAutoCloseIgnore( config.$autoCloseIgnore );
5319 this.$body.addClass( 'oo-ui-popupWidget-body' );
5320 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
5321 this.$popup
5322 .addClass( 'oo-ui-popupWidget-popup' )
5323 .append( this.$body );
5324 this.$element
5325 .addClass( 'oo-ui-popupWidget' )
5326 .append( this.$popup, this.$anchor );
5327 // Move content, which was added to #$element by OO.ui.Widget, to the body
5328 // FIXME This is gross, we should use '$body' or something for the config
5329 if ( config.$content instanceof $ ) {
5330 this.$body.append( config.$content );
5331 }
5332
5333 if ( config.padded ) {
5334 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
5335 }
5336
5337 if ( config.head ) {
5338 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
5339 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
5340 this.$head = $( '<div>' )
5341 .addClass( 'oo-ui-popupWidget-head' )
5342 .append( this.$label, this.closeButton.$element );
5343 this.$popup.prepend( this.$head );
5344 }
5345
5346 if ( config.$footer ) {
5347 this.$footer = $( '<div>' )
5348 .addClass( 'oo-ui-popupWidget-footer' )
5349 .append( config.$footer );
5350 this.$popup.append( this.$footer );
5351 }
5352
5353 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
5354 // that reference properties not initialized at that time of parent class construction
5355 // TODO: Find a better way to handle post-constructor setup
5356 this.visible = false;
5357 this.$element.addClass( 'oo-ui-element-hidden' );
5358 };
5359
5360 /* Setup */
5361
5362 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
5363 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.LabelElement );
5364 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.ClippableElement );
5365 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.FloatableElement );
5366
5367 /* Events */
5368
5369 /**
5370 * @event ready
5371 *
5372 * The popup is ready: it is visible and has been positioned and clipped.
5373 */
5374
5375 /* Methods */
5376
5377 /**
5378 * Handles document mouse down events.
5379 *
5380 * @private
5381 * @param {MouseEvent} e Mouse down event
5382 */
5383 OO.ui.PopupWidget.prototype.onDocumentMouseDown = function ( e ) {
5384 if (
5385 this.isVisible() &&
5386 !OO.ui.contains( this.$element.add( this.$autoCloseIgnore ).get(), e.target, true )
5387 ) {
5388 this.toggle( false );
5389 }
5390 };
5391
5392 // Deprecated alias since 0.28.3
5393 OO.ui.PopupWidget.prototype.onMouseDown = function () {
5394 OO.ui.warnDeprecation( 'onMouseDown is deprecated, use onDocumentMouseDown instead' );
5395 this.onDocumentMouseDown.apply( this, arguments );
5396 };
5397
5398 /**
5399 * Bind document mouse down listener.
5400 *
5401 * @private
5402 */
5403 OO.ui.PopupWidget.prototype.bindDocumentMouseDownListener = function () {
5404 // Capture clicks outside popup
5405 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
5406 // We add 'click' event because iOS safari needs to respond to this event.
5407 // We can't use 'touchstart' (as is usually the equivalent to 'mousedown') because
5408 // then it will trigger when scrolling. While iOS Safari has some reported behavior
5409 // of occasionally not emitting 'click' properly, that event seems to be the standard
5410 // that it should be emitting, so we add it to this and will operate the event handler
5411 // on whichever of these events was triggered first
5412 this.getElementDocument().addEventListener( 'click', this.onDocumentMouseDownHandler, true );
5413 };
5414
5415 // Deprecated alias since 0.28.3
5416 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
5417 OO.ui.warnDeprecation( 'bindMouseDownListener is deprecated, use bindDocumentMouseDownListener instead' );
5418 this.bindDocumentMouseDownListener.apply( this, arguments );
5419 };
5420
5421 /**
5422 * Handles close button click events.
5423 *
5424 * @private
5425 */
5426 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
5427 if ( this.isVisible() ) {
5428 this.toggle( false );
5429 }
5430 };
5431
5432 /**
5433 * Unbind document mouse down listener.
5434 *
5435 * @private
5436 */
5437 OO.ui.PopupWidget.prototype.unbindDocumentMouseDownListener = function () {
5438 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
5439 this.getElementDocument().removeEventListener( 'click', this.onDocumentMouseDownHandler, true );
5440 };
5441
5442 // Deprecated alias since 0.28.3
5443 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
5444 OO.ui.warnDeprecation( 'unbindMouseDownListener is deprecated, use unbindDocumentMouseDownListener instead' );
5445 this.unbindDocumentMouseDownListener.apply( this, arguments );
5446 };
5447
5448 /**
5449 * Handles document key down events.
5450 *
5451 * @private
5452 * @param {KeyboardEvent} e Key down event
5453 */
5454 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
5455 if (
5456 e.which === OO.ui.Keys.ESCAPE &&
5457 this.isVisible()
5458 ) {
5459 this.toggle( false );
5460 e.preventDefault();
5461 e.stopPropagation();
5462 }
5463 };
5464
5465 /**
5466 * Bind document key down listener.
5467 *
5468 * @private
5469 */
5470 OO.ui.PopupWidget.prototype.bindDocumentKeyDownListener = function () {
5471 this.getElementDocument().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
5472 };
5473
5474 // Deprecated alias since 0.28.3
5475 OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
5476 OO.ui.warnDeprecation( 'bindKeyDownListener is deprecated, use bindDocumentKeyDownListener instead' );
5477 this.bindDocumentKeyDownListener.apply( this, arguments );
5478 };
5479
5480 /**
5481 * Unbind document key down listener.
5482 *
5483 * @private
5484 */
5485 OO.ui.PopupWidget.prototype.unbindDocumentKeyDownListener = function () {
5486 this.getElementDocument().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
5487 };
5488
5489 // Deprecated alias since 0.28.3
5490 OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
5491 OO.ui.warnDeprecation( 'unbindKeyDownListener is deprecated, use unbindDocumentKeyDownListener instead' );
5492 this.unbindDocumentKeyDownListener.apply( this, arguments );
5493 };
5494
5495 /**
5496 * Show, hide, or toggle the visibility of the anchor.
5497 *
5498 * @param {boolean} [show] Show anchor, omit to toggle
5499 */
5500 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
5501 show = show === undefined ? !this.anchored : !!show;
5502
5503 if ( this.anchored !== show ) {
5504 if ( show ) {
5505 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
5506 this.$element.addClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge );
5507 } else {
5508 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
5509 this.$element.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge );
5510 }
5511 this.anchored = show;
5512 }
5513 };
5514
5515 /**
5516 * Change which edge the anchor appears on.
5517 *
5518 * @param {string} edge 'top', 'bottom', 'start' or 'end'
5519 */
5520 OO.ui.PopupWidget.prototype.setAnchorEdge = function ( edge ) {
5521 if ( [ 'top', 'bottom', 'start', 'end' ].indexOf( edge ) === -1 ) {
5522 throw new Error( 'Invalid value for edge: ' + edge );
5523 }
5524 if ( this.anchorEdge !== null ) {
5525 this.$element.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge );
5526 }
5527 this.anchorEdge = edge;
5528 if ( this.anchored ) {
5529 this.$element.addClass( 'oo-ui-popupWidget-anchored-' + edge );
5530 }
5531 };
5532
5533 /**
5534 * Check if the anchor is visible.
5535 *
5536 * @return {boolean} Anchor is visible
5537 */
5538 OO.ui.PopupWidget.prototype.hasAnchor = function () {
5539 return this.anchored;
5540 };
5541
5542 /**
5543 * Toggle visibility of the popup. The popup is initially hidden and must be shown by calling
5544 * `.toggle( true )` after its #$element is attached to the DOM.
5545 *
5546 * Do not show the popup while it is not attached to the DOM. The calculations required to display
5547 * it in the right place and with the right dimensions only work correctly while it is attached.
5548 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
5549 * strictly enforced, so currently it only generates a warning in the browser console.
5550 *
5551 * @fires ready
5552 * @inheritdoc
5553 */
5554 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
5555 var change, normalHeight, oppositeHeight, normalWidth, oppositeWidth;
5556 show = show === undefined ? !this.isVisible() : !!show;
5557
5558 change = show !== this.isVisible();
5559
5560 if ( show && !this.warnedUnattached && !this.isElementAttached() ) {
5561 OO.ui.warnDeprecation( 'PopupWidget#toggle: Before calling this method, the popup must be attached to the DOM.' );
5562 this.warnedUnattached = true;
5563 }
5564 if ( show && !this.$floatableContainer && this.isElementAttached() ) {
5565 // Fall back to the parent node if the floatableContainer is not set
5566 this.setFloatableContainer( this.$element.parent() );
5567 }
5568
5569 if ( change && show && this.autoFlip ) {
5570 // Reset auto-flipping before showing the popup again. It's possible we no longer need to flip
5571 // (e.g. if the user scrolled).
5572 this.isAutoFlipped = false;
5573 }
5574
5575 // Parent method
5576 OO.ui.PopupWidget.parent.prototype.toggle.call( this, show );
5577
5578 if ( change ) {
5579 this.togglePositioning( show && !!this.$floatableContainer );
5580
5581 if ( show ) {
5582 if ( this.autoClose ) {
5583 this.bindDocumentMouseDownListener();
5584 this.bindDocumentKeyDownListener();
5585 }
5586 this.updateDimensions();
5587 this.toggleClipping( true );
5588
5589 if ( this.autoFlip ) {
5590 if ( this.popupPosition === 'above' || this.popupPosition === 'below' ) {
5591 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5592 // If opening the popup in the normal direction causes it to be clipped, open
5593 // in the opposite one instead
5594 normalHeight = this.$element.height();
5595 this.isAutoFlipped = !this.isAutoFlipped;
5596 this.position();
5597 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5598 // If that also causes it to be clipped, open in whichever direction
5599 // we have more space
5600 oppositeHeight = this.$element.height();
5601 if ( oppositeHeight < normalHeight ) {
5602 this.isAutoFlipped = !this.isAutoFlipped;
5603 this.position();
5604 }
5605 }
5606 }
5607 }
5608 if ( this.popupPosition === 'before' || this.popupPosition === 'after' ) {
5609 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5610 // If opening the popup in the normal direction causes it to be clipped, open
5611 // in the opposite one instead
5612 normalWidth = this.$element.width();
5613 this.isAutoFlipped = !this.isAutoFlipped;
5614 // Due to T180173 horizontally clipped PopupWidgets have messed up dimensions,
5615 // which causes positioning to be off. Toggle clipping back and fort to work around.
5616 this.toggleClipping( false );
5617 this.position();
5618 this.toggleClipping( true );
5619 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5620 // If that also causes it to be clipped, open in whichever direction
5621 // we have more space
5622 oppositeWidth = this.$element.width();
5623 if ( oppositeWidth < normalWidth ) {
5624 this.isAutoFlipped = !this.isAutoFlipped;
5625 // Due to T180173 horizontally clipped PopupWidgets have messed up dimensions,
5626 // which causes positioning to be off. Toggle clipping back and fort to work around.
5627 this.toggleClipping( false );
5628 this.position();
5629 this.toggleClipping( true );
5630 }
5631 }
5632 }
5633 }
5634 }
5635
5636 this.emit( 'ready' );
5637 } else {
5638 this.toggleClipping( false );
5639 if ( this.autoClose ) {
5640 this.unbindDocumentMouseDownListener();
5641 this.unbindDocumentKeyDownListener();
5642 }
5643 }
5644 }
5645
5646 return this;
5647 };
5648
5649 /**
5650 * Set the size of the popup.
5651 *
5652 * Changing the size may also change the popup's position depending on the alignment.
5653 *
5654 * @param {number|null} [width=320] Width in pixels. Pass `null` to use automatic width.
5655 * @param {number|null} [height=null] Height in pixels. Pass `null` to use automatic height.
5656 * @param {boolean} [transition=false] Use a smooth transition
5657 * @chainable
5658 */
5659 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
5660 this.width = width !== undefined ? width : 320;
5661 this.height = height !== undefined ? height : null;
5662 if ( this.isVisible() ) {
5663 this.updateDimensions( transition );
5664 }
5665 };
5666
5667 /**
5668 * Update the size and position.
5669 *
5670 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
5671 * be called automatically.
5672 *
5673 * @param {boolean} [transition=false] Use a smooth transition
5674 * @chainable
5675 */
5676 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
5677 var widget = this;
5678
5679 // Prevent transition from being interrupted
5680 clearTimeout( this.transitionTimeout );
5681 if ( transition ) {
5682 // Enable transition
5683 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
5684 }
5685
5686 this.position();
5687
5688 if ( transition ) {
5689 // Prevent transitioning after transition is complete
5690 this.transitionTimeout = setTimeout( function () {
5691 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
5692 }, 200 );
5693 } else {
5694 // Prevent transitioning immediately
5695 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
5696 }
5697 };
5698
5699 /**
5700 * @inheritdoc
5701 */
5702 OO.ui.PopupWidget.prototype.computePosition = function () {
5703 var direction, align, vertical, start, end, near, far, sizeProp, popupSize, anchorSize, anchorPos,
5704 anchorOffset, anchorMargin, parentPosition, positionProp, positionAdjustment, floatablePos,
5705 offsetParentPos, containerPos, popupPosition, viewportSpacing,
5706 popupPos = {},
5707 anchorCss = { left: '', right: '', top: '', bottom: '' },
5708 popupPositionOppositeMap = {
5709 above: 'below',
5710 below: 'above',
5711 before: 'after',
5712 after: 'before'
5713 },
5714 alignMap = {
5715 ltr: {
5716 'force-left': 'backwards',
5717 'force-right': 'forwards'
5718 },
5719 rtl: {
5720 'force-left': 'forwards',
5721 'force-right': 'backwards'
5722 }
5723 },
5724 anchorEdgeMap = {
5725 above: 'bottom',
5726 below: 'top',
5727 before: 'end',
5728 after: 'start'
5729 },
5730 hPosMap = {
5731 forwards: 'start',
5732 center: 'center',
5733 backwards: this.anchored ? 'before' : 'end'
5734 },
5735 vPosMap = {
5736 forwards: 'top',
5737 center: 'center',
5738 backwards: 'bottom'
5739 };
5740
5741 if ( !this.$container ) {
5742 // Lazy-initialize $container if not specified in constructor
5743 this.$container = $( this.getClosestScrollableElementContainer() );
5744 }
5745 direction = this.$container.css( 'direction' );
5746
5747 // Set height and width before we do anything else, since it might cause our measurements
5748 // to change (e.g. due to scrollbars appearing or disappearing), and it also affects centering
5749 this.$popup.css( {
5750 width: this.width !== null ? this.width : 'auto',
5751 height: this.height !== null ? this.height : 'auto'
5752 } );
5753
5754 align = alignMap[ direction ][ this.align ] || this.align;
5755 popupPosition = this.popupPosition;
5756 if ( this.isAutoFlipped ) {
5757 popupPosition = popupPositionOppositeMap[ popupPosition ];
5758 }
5759
5760 // If the popup is positioned before or after, then the anchor positioning is vertical, otherwise horizontal
5761 vertical = popupPosition === 'before' || popupPosition === 'after';
5762 start = vertical ? 'top' : ( direction === 'rtl' ? 'right' : 'left' );
5763 end = vertical ? 'bottom' : ( direction === 'rtl' ? 'left' : 'right' );
5764 near = vertical ? 'top' : 'left';
5765 far = vertical ? 'bottom' : 'right';
5766 sizeProp = vertical ? 'Height' : 'Width';
5767 popupSize = vertical ? ( this.height || this.$popup.height() ) : ( this.width || this.$popup.width() );
5768
5769 this.setAnchorEdge( anchorEdgeMap[ popupPosition ] );
5770 this.horizontalPosition = vertical ? popupPosition : hPosMap[ align ];
5771 this.verticalPosition = vertical ? vPosMap[ align ] : popupPosition;
5772
5773 // Parent method
5774 parentPosition = OO.ui.mixin.FloatableElement.prototype.computePosition.call( this );
5775 // Find out which property FloatableElement used for positioning, and adjust that value
5776 positionProp = vertical ?
5777 ( parentPosition.top !== '' ? 'top' : 'bottom' ) :
5778 ( parentPosition.left !== '' ? 'left' : 'right' );
5779
5780 // Figure out where the near and far edges of the popup and $floatableContainer are
5781 floatablePos = this.$floatableContainer.offset();
5782 floatablePos[ far ] = floatablePos[ near ] + this.$floatableContainer[ 'outer' + sizeProp ]();
5783 // Measure where the offsetParent is and compute our position based on that and parentPosition
5784 offsetParentPos = this.$element.offsetParent()[ 0 ] === document.documentElement ?
5785 { top: 0, left: 0 } :
5786 this.$element.offsetParent().offset();
5787
5788 if ( positionProp === near ) {
5789 popupPos[ near ] = offsetParentPos[ near ] + parentPosition[ near ];
5790 popupPos[ far ] = popupPos[ near ] + popupSize;
5791 } else {
5792 popupPos[ far ] = offsetParentPos[ near ] +
5793 this.$element.offsetParent()[ 'inner' + sizeProp ]() - parentPosition[ far ];
5794 popupPos[ near ] = popupPos[ far ] - popupSize;
5795 }
5796
5797 if ( this.anchored ) {
5798 // Position the anchor (which is positioned relative to the popup) to point to $floatableContainer
5799 anchorPos = ( floatablePos[ start ] + floatablePos[ end ] ) / 2;
5800 anchorOffset = ( start === far ? -1 : 1 ) * ( anchorPos - popupPos[ start ] );
5801
5802 // If the anchor is less than 2*anchorSize from either edge, move the popup to make more space
5803 // this.$anchor.width()/height() returns 0 because of the CSS trickery we use, so use scrollWidth/Height
5804 anchorSize = this.$anchor[ 0 ][ 'scroll' + sizeProp ];
5805 anchorMargin = parseFloat( this.$anchor.css( 'margin-' + start ) );
5806 if ( anchorOffset + anchorMargin < 2 * anchorSize ) {
5807 // Not enough space for the anchor on the start side; pull the popup startwards
5808 positionAdjustment = ( positionProp === start ? -1 : 1 ) *
5809 ( 2 * anchorSize - ( anchorOffset + anchorMargin ) );
5810 } else if ( anchorOffset + anchorMargin > popupSize - 2 * anchorSize ) {
5811 // Not enough space for the anchor on the end side; pull the popup endwards
5812 positionAdjustment = ( positionProp === end ? -1 : 1 ) *
5813 ( anchorOffset + anchorMargin - ( popupSize - 2 * anchorSize ) );
5814 } else {
5815 positionAdjustment = 0;
5816 }
5817 } else {
5818 positionAdjustment = 0;
5819 }
5820
5821 // Check if the popup will go beyond the edge of this.$container
5822 containerPos = this.$container[ 0 ] === document.documentElement ?
5823 { top: 0, left: 0 } :
5824 this.$container.offset();
5825 containerPos[ far ] = containerPos[ near ] + this.$container[ 'inner' + sizeProp ]();
5826 if ( this.$container[ 0 ] === document.documentElement ) {
5827 viewportSpacing = OO.ui.getViewportSpacing();
5828 containerPos[ near ] += viewportSpacing[ near ];
5829 containerPos[ far ] -= viewportSpacing[ far ];
5830 }
5831 // Take into account how much the popup will move because of the adjustments we're going to make
5832 popupPos[ near ] += ( positionProp === near ? 1 : -1 ) * positionAdjustment;
5833 popupPos[ far ] += ( positionProp === near ? 1 : -1 ) * positionAdjustment;
5834 if ( containerPos[ near ] + this.containerPadding > popupPos[ near ] ) {
5835 // Popup goes beyond the near (left/top) edge, move it to the right/bottom
5836 positionAdjustment += ( positionProp === near ? 1 : -1 ) *
5837 ( containerPos[ near ] + this.containerPadding - popupPos[ near ] );
5838 } else if ( containerPos[ far ] - this.containerPadding < popupPos[ far ] ) {
5839 // Popup goes beyond the far (right/bottom) edge, move it to the left/top
5840 positionAdjustment += ( positionProp === far ? 1 : -1 ) *
5841 ( popupPos[ far ] - ( containerPos[ far ] - this.containerPadding ) );
5842 }
5843
5844 if ( this.anchored ) {
5845 // Adjust anchorOffset for positionAdjustment
5846 anchorOffset += ( positionProp === start ? -1 : 1 ) * positionAdjustment;
5847
5848 // Position the anchor
5849 anchorCss[ start ] = anchorOffset;
5850 this.$anchor.css( anchorCss );
5851 }
5852
5853 // Move the popup if needed
5854 parentPosition[ positionProp ] += positionAdjustment;
5855
5856 return parentPosition;
5857 };
5858
5859 /**
5860 * Set popup alignment
5861 *
5862 * @param {string} [align=center] Alignment of the popup, `center`, `force-left`, `force-right`,
5863 * `backwards` or `forwards`.
5864 */
5865 OO.ui.PopupWidget.prototype.setAlignment = function ( align ) {
5866 // Validate alignment
5867 if ( [ 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align ) > -1 ) {
5868 this.align = align;
5869 } else {
5870 this.align = 'center';
5871 }
5872 this.position();
5873 };
5874
5875 /**
5876 * Get popup alignment
5877 *
5878 * @return {string} Alignment of the popup, `center`, `force-left`, `force-right`,
5879 * `backwards` or `forwards`.
5880 */
5881 OO.ui.PopupWidget.prototype.getAlignment = function () {
5882 return this.align;
5883 };
5884
5885 /**
5886 * Change the positioning of the popup.
5887 *
5888 * @param {string} position 'above', 'below', 'before' or 'after'
5889 */
5890 OO.ui.PopupWidget.prototype.setPosition = function ( position ) {
5891 if ( [ 'above', 'below', 'before', 'after' ].indexOf( position ) === -1 ) {
5892 position = 'below';
5893 }
5894 this.popupPosition = position;
5895 this.position();
5896 };
5897
5898 /**
5899 * Get popup positioning.
5900 *
5901 * @return {string} 'above', 'below', 'before' or 'after'
5902 */
5903 OO.ui.PopupWidget.prototype.getPosition = function () {
5904 return this.popupPosition;
5905 };
5906
5907 /**
5908 * Set popup auto-flipping.
5909 *
5910 * @param {boolean} autoFlip Whether to automatically switch the popup's position between
5911 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5912 * desired direction to display the popup without clipping
5913 */
5914 OO.ui.PopupWidget.prototype.setAutoFlip = function ( autoFlip ) {
5915 autoFlip = !!autoFlip;
5916
5917 if ( this.autoFlip !== autoFlip ) {
5918 this.autoFlip = autoFlip;
5919 }
5920 };
5921
5922 /**
5923 * Set which elements will not close the popup when clicked.
5924 *
5925 * For auto-closing popups, clicks on these elements will not cause the popup to auto-close.
5926 *
5927 * @param {jQuery} $autoCloseIgnore Elements to ignore for auto-closing
5928 */
5929 OO.ui.PopupWidget.prototype.setAutoCloseIgnore = function ( $autoCloseIgnore ) {
5930 this.$autoCloseIgnore = $autoCloseIgnore;
5931 };
5932
5933 /**
5934 * Get an ID of the body element, this can be used as the
5935 * `aria-describedby` attribute for an input field.
5936 *
5937 * @return {string} The ID of the body element
5938 */
5939 OO.ui.PopupWidget.prototype.getBodyId = function () {
5940 var id = this.$body.attr( 'id' );
5941 if ( id === undefined ) {
5942 id = OO.ui.generateElementId();
5943 this.$body.attr( 'id', id );
5944 }
5945 return id;
5946 };
5947
5948 /**
5949 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5950 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5951 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5952 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5953 *
5954 * @abstract
5955 * @class
5956 *
5957 * @constructor
5958 * @param {Object} [config] Configuration options
5959 * @cfg {Object} [popup] Configuration to pass to popup
5960 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5961 */
5962 OO.ui.mixin.PopupElement = function OoUiMixinPopupElement( config ) {
5963 // Configuration initialization
5964 config = config || {};
5965
5966 // Properties
5967 this.popup = new OO.ui.PopupWidget( $.extend(
5968 {
5969 autoClose: true,
5970 $floatableContainer: this.$element
5971 },
5972 config.popup,
5973 {
5974 $autoCloseIgnore: this.$element.add( config.popup && config.popup.$autoCloseIgnore )
5975 }
5976 ) );
5977 };
5978
5979 /* Methods */
5980
5981 /**
5982 * Get popup.
5983 *
5984 * @return {OO.ui.PopupWidget} Popup widget
5985 */
5986 OO.ui.mixin.PopupElement.prototype.getPopup = function () {
5987 return this.popup;
5988 };
5989
5990 /**
5991 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
5992 * which is used to display additional information or options.
5993 *
5994 * @example
5995 * // A PopupButtonWidget.
5996 * var popupButton = new OO.ui.PopupButtonWidget( {
5997 * label: 'Popup button with options',
5998 * icon: 'menu',
5999 * popup: {
6000 * $content: $( '<p>Additional options here.</p>' ),
6001 * padded: true,
6002 * align: 'force-left'
6003 * }
6004 * } );
6005 * // Append the button to the DOM.
6006 * $( document.body ).append( popupButton.$element );
6007 *
6008 * @class
6009 * @extends OO.ui.ButtonWidget
6010 * @mixins OO.ui.mixin.PopupElement
6011 *
6012 * @constructor
6013 * @param {Object} [config] Configuration options
6014 * @cfg {jQuery} [$overlay] Render the popup into a separate layer. This configuration is useful in cases where
6015 * the expanded popup is larger than its containing `<div>`. The specified overlay layer is usually on top of the
6016 * containing `<div>` and has a larger area. By default, the popup uses relative positioning.
6017 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
6018 */
6019 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
6020 // Configuration initialization
6021 config = config || {};
6022
6023 // Parent constructor
6024 OO.ui.PopupButtonWidget.parent.call( this, config );
6025
6026 // Mixin constructors
6027 OO.ui.mixin.PopupElement.call( this, config );
6028
6029 // Properties
6030 this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
6031
6032 // Events
6033 this.connect( this, { click: 'onAction' } );
6034
6035 // Initialization
6036 this.$element
6037 .addClass( 'oo-ui-popupButtonWidget' );
6038 this.popup.$element
6039 .addClass( 'oo-ui-popupButtonWidget-popup' )
6040 .toggleClass( 'oo-ui-popupButtonWidget-framed-popup', this.isFramed() )
6041 .toggleClass( 'oo-ui-popupButtonWidget-frameless-popup', !this.isFramed() );
6042 this.$overlay.append( this.popup.$element );
6043 };
6044
6045 /* Setup */
6046
6047 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
6048 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.mixin.PopupElement );
6049
6050 /* Methods */
6051
6052 /**
6053 * Handle the button action being triggered.
6054 *
6055 * @private
6056 */
6057 OO.ui.PopupButtonWidget.prototype.onAction = function () {
6058 this.popup.toggle();
6059 };
6060
6061 /**
6062 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
6063 *
6064 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
6065 *
6066 * @private
6067 * @abstract
6068 * @class
6069 * @mixins OO.ui.mixin.GroupElement
6070 *
6071 * @constructor
6072 * @param {Object} [config] Configuration options
6073 */
6074 OO.ui.mixin.GroupWidget = function OoUiMixinGroupWidget( config ) {
6075 // Mixin constructors
6076 OO.ui.mixin.GroupElement.call( this, config );
6077 };
6078
6079 /* Setup */
6080
6081 OO.mixinClass( OO.ui.mixin.GroupWidget, OO.ui.mixin.GroupElement );
6082
6083 /* Methods */
6084
6085 /**
6086 * Set the disabled state of the widget.
6087 *
6088 * This will also update the disabled state of child widgets.
6089 *
6090 * @param {boolean} disabled Disable widget
6091 * @chainable
6092 * @return {OO.ui.Widget} The widget, for chaining
6093 */
6094 OO.ui.mixin.GroupWidget.prototype.setDisabled = function ( disabled ) {
6095 var i, len;
6096
6097 // Parent method
6098 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
6099 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
6100
6101 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
6102 if ( this.items ) {
6103 for ( i = 0, len = this.items.length; i < len; i++ ) {
6104 this.items[ i ].updateDisabled();
6105 }
6106 }
6107
6108 return this;
6109 };
6110
6111 /**
6112 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
6113 *
6114 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
6115 * allows bidirectional communication.
6116 *
6117 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
6118 *
6119 * @private
6120 * @abstract
6121 * @class
6122 *
6123 * @constructor
6124 */
6125 OO.ui.mixin.ItemWidget = function OoUiMixinItemWidget() {
6126 //
6127 };
6128
6129 /* Methods */
6130
6131 /**
6132 * Check if widget is disabled.
6133 *
6134 * Checks parent if present, making disabled state inheritable.
6135 *
6136 * @return {boolean} Widget is disabled
6137 */
6138 OO.ui.mixin.ItemWidget.prototype.isDisabled = function () {
6139 return this.disabled ||
6140 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
6141 };
6142
6143 /**
6144 * Set group element is in.
6145 *
6146 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
6147 * @chainable
6148 * @return {OO.ui.Widget} The widget, for chaining
6149 */
6150 OO.ui.mixin.ItemWidget.prototype.setElementGroup = function ( group ) {
6151 // Parent method
6152 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
6153 OO.ui.Element.prototype.setElementGroup.call( this, group );
6154
6155 // Initialize item disabled states
6156 this.updateDisabled();
6157
6158 return this;
6159 };
6160
6161 /**
6162 * OptionWidgets are special elements that can be selected and configured with data. The
6163 * data is often unique for each option, but it does not have to be. OptionWidgets are used
6164 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
6165 * and examples, please see the [OOUI documentation on MediaWiki][1].
6166 *
6167 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6168 *
6169 * @class
6170 * @extends OO.ui.Widget
6171 * @mixins OO.ui.mixin.ItemWidget
6172 * @mixins OO.ui.mixin.LabelElement
6173 * @mixins OO.ui.mixin.FlaggedElement
6174 * @mixins OO.ui.mixin.AccessKeyedElement
6175 * @mixins OO.ui.mixin.TitledElement
6176 *
6177 * @constructor
6178 * @param {Object} [config] Configuration options
6179 */
6180 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
6181 // Configuration initialization
6182 config = config || {};
6183
6184 // Parent constructor
6185 OO.ui.OptionWidget.parent.call( this, config );
6186
6187 // Mixin constructors
6188 OO.ui.mixin.ItemWidget.call( this );
6189 OO.ui.mixin.LabelElement.call( this, config );
6190 OO.ui.mixin.FlaggedElement.call( this, config );
6191 OO.ui.mixin.AccessKeyedElement.call( this, config );
6192 OO.ui.mixin.TitledElement.call( this, config );
6193
6194 // Properties
6195 this.selected = false;
6196 this.highlighted = false;
6197 this.pressed = false;
6198
6199 // Initialization
6200 this.$element
6201 .data( 'oo-ui-optionWidget', this )
6202 // Allow programmatic focussing (and by accesskey), but not tabbing
6203 .attr( 'tabindex', '-1' )
6204 .attr( 'role', 'option' )
6205 .attr( 'aria-selected', 'false' )
6206 .addClass( 'oo-ui-optionWidget' )
6207 .append( this.$label );
6208 };
6209
6210 /* Setup */
6211
6212 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
6213 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.ItemWidget );
6214 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.LabelElement );
6215 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.FlaggedElement );
6216 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.AccessKeyedElement );
6217 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.TitledElement );
6218
6219 /* Static Properties */
6220
6221 /**
6222 * Whether this option can be selected. See #setSelected.
6223 *
6224 * @static
6225 * @inheritable
6226 * @property {boolean}
6227 */
6228 OO.ui.OptionWidget.static.selectable = true;
6229
6230 /**
6231 * Whether this option can be highlighted. See #setHighlighted.
6232 *
6233 * @static
6234 * @inheritable
6235 * @property {boolean}
6236 */
6237 OO.ui.OptionWidget.static.highlightable = true;
6238
6239 /**
6240 * Whether this option can be pressed. See #setPressed.
6241 *
6242 * @static
6243 * @inheritable
6244 * @property {boolean}
6245 */
6246 OO.ui.OptionWidget.static.pressable = true;
6247
6248 /**
6249 * Whether this option will be scrolled into view when it is selected.
6250 *
6251 * @static
6252 * @inheritable
6253 * @property {boolean}
6254 */
6255 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
6256
6257 /* Methods */
6258
6259 /**
6260 * Check if the option can be selected.
6261 *
6262 * @return {boolean} Item is selectable
6263 */
6264 OO.ui.OptionWidget.prototype.isSelectable = function () {
6265 return this.constructor.static.selectable && !this.disabled && this.isVisible();
6266 };
6267
6268 /**
6269 * Check if the option can be highlighted. A highlight indicates that the option
6270 * may be selected when a user presses enter or clicks. Disabled items cannot
6271 * be highlighted.
6272 *
6273 * @return {boolean} Item is highlightable
6274 */
6275 OO.ui.OptionWidget.prototype.isHighlightable = function () {
6276 return this.constructor.static.highlightable && !this.disabled && this.isVisible();
6277 };
6278
6279 /**
6280 * Check if the option can be pressed. The pressed state occurs when a user mouses
6281 * down on an item, but has not yet let go of the mouse.
6282 *
6283 * @return {boolean} Item is pressable
6284 */
6285 OO.ui.OptionWidget.prototype.isPressable = function () {
6286 return this.constructor.static.pressable && !this.disabled && this.isVisible();
6287 };
6288
6289 /**
6290 * Check if the option is selected.
6291 *
6292 * @return {boolean} Item is selected
6293 */
6294 OO.ui.OptionWidget.prototype.isSelected = function () {
6295 return this.selected;
6296 };
6297
6298 /**
6299 * Check if the option is highlighted. A highlight indicates that the
6300 * item may be selected when a user presses enter or clicks.
6301 *
6302 * @return {boolean} Item is highlighted
6303 */
6304 OO.ui.OptionWidget.prototype.isHighlighted = function () {
6305 return this.highlighted;
6306 };
6307
6308 /**
6309 * Check if the option is pressed. The pressed state occurs when a user mouses
6310 * down on an item, but has not yet let go of the mouse. The item may appear
6311 * selected, but it will not be selected until the user releases the mouse.
6312 *
6313 * @return {boolean} Item is pressed
6314 */
6315 OO.ui.OptionWidget.prototype.isPressed = function () {
6316 return this.pressed;
6317 };
6318
6319 /**
6320 * Set the option’s selected state. In general, all modifications to the selection
6321 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
6322 * method instead of this method.
6323 *
6324 * @param {boolean} [state=false] Select option
6325 * @chainable
6326 * @return {OO.ui.Widget} The widget, for chaining
6327 */
6328 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
6329 if ( this.constructor.static.selectable ) {
6330 this.selected = !!state;
6331 this.$element
6332 .toggleClass( 'oo-ui-optionWidget-selected', state )
6333 .attr( 'aria-selected', state.toString() );
6334 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
6335 this.scrollElementIntoView();
6336 }
6337 this.updateThemeClasses();
6338 }
6339 return this;
6340 };
6341
6342 /**
6343 * Set the option’s highlighted state. In general, all programmatic
6344 * modifications to the highlight should be handled by the
6345 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
6346 * method instead of this method.
6347 *
6348 * @param {boolean} [state=false] Highlight option
6349 * @chainable
6350 * @return {OO.ui.Widget} The widget, for chaining
6351 */
6352 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
6353 if ( this.constructor.static.highlightable ) {
6354 this.highlighted = !!state;
6355 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
6356 this.updateThemeClasses();
6357 }
6358 return this;
6359 };
6360
6361 /**
6362 * Set the option’s pressed state. In general, all
6363 * programmatic modifications to the pressed state should be handled by the
6364 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
6365 * method instead of this method.
6366 *
6367 * @param {boolean} [state=false] Press option
6368 * @chainable
6369 * @return {OO.ui.Widget} The widget, for chaining
6370 */
6371 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
6372 if ( this.constructor.static.pressable ) {
6373 this.pressed = !!state;
6374 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
6375 this.updateThemeClasses();
6376 }
6377 return this;
6378 };
6379
6380 /**
6381 * Get text to match search strings against.
6382 *
6383 * The default implementation returns the label text, but subclasses
6384 * can override this to provide more complex behavior.
6385 *
6386 * @return {string|boolean} String to match search string against
6387 */
6388 OO.ui.OptionWidget.prototype.getMatchText = function () {
6389 var label = this.getLabel();
6390 return typeof label === 'string' ? label : this.$label.text();
6391 };
6392
6393 /**
6394 * A SelectWidget is of a generic selection of options. The OOUI library contains several types of
6395 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
6396 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
6397 * menu selects}.
6398 *
6399 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
6400 * information, please see the [OOUI documentation on MediaWiki][1].
6401 *
6402 * @example
6403 * // A select widget with three options.
6404 * var select = new OO.ui.SelectWidget( {
6405 * items: [
6406 * new OO.ui.OptionWidget( {
6407 * data: 'a',
6408 * label: 'Option One',
6409 * } ),
6410 * new OO.ui.OptionWidget( {
6411 * data: 'b',
6412 * label: 'Option Two',
6413 * } ),
6414 * new OO.ui.OptionWidget( {
6415 * data: 'c',
6416 * label: 'Option Three',
6417 * } )
6418 * ]
6419 * } );
6420 * $( document.body ).append( select.$element );
6421 *
6422 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6423 *
6424 * @abstract
6425 * @class
6426 * @extends OO.ui.Widget
6427 * @mixins OO.ui.mixin.GroupWidget
6428 *
6429 * @constructor
6430 * @param {Object} [config] Configuration options
6431 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
6432 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
6433 * the [OOUI documentation on MediaWiki] [2] for examples.
6434 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6435 */
6436 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
6437 // Configuration initialization
6438 config = config || {};
6439
6440 // Parent constructor
6441 OO.ui.SelectWidget.parent.call( this, config );
6442
6443 // Mixin constructors
6444 OO.ui.mixin.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
6445
6446 // Properties
6447 this.pressed = false;
6448 this.selecting = null;
6449 this.onDocumentMouseUpHandler = this.onDocumentMouseUp.bind( this );
6450 this.onDocumentMouseMoveHandler = this.onDocumentMouseMove.bind( this );
6451 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
6452 this.onDocumentKeyPressHandler = this.onDocumentKeyPress.bind( this );
6453 this.keyPressBuffer = '';
6454 this.keyPressBufferTimer = null;
6455 this.blockMouseOverEvents = 0;
6456
6457 // Events
6458 this.connect( this, {
6459 toggle: 'onToggle'
6460 } );
6461 this.$element.on( {
6462 focusin: this.onFocus.bind( this ),
6463 mousedown: this.onMouseDown.bind( this ),
6464 mouseover: this.onMouseOver.bind( this ),
6465 mouseleave: this.onMouseLeave.bind( this )
6466 } );
6467
6468 // Initialization
6469 this.$element
6470 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
6471 .attr( 'role', 'listbox' );
6472 this.setFocusOwner( this.$element );
6473 if ( Array.isArray( config.items ) ) {
6474 this.addItems( config.items );
6475 }
6476 };
6477
6478 /* Setup */
6479
6480 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
6481 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupWidget );
6482
6483 /* Events */
6484
6485 /**
6486 * @event highlight
6487 *
6488 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
6489 *
6490 * @param {OO.ui.OptionWidget|null} item Highlighted item
6491 */
6492
6493 /**
6494 * @event press
6495 *
6496 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
6497 * pressed state of an option.
6498 *
6499 * @param {OO.ui.OptionWidget|null} item Pressed item
6500 */
6501
6502 /**
6503 * @event select
6504 *
6505 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
6506 *
6507 * @param {OO.ui.OptionWidget|null} item Selected item
6508 */
6509
6510 /**
6511 * @event choose
6512 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
6513 * @param {OO.ui.OptionWidget} item Chosen item
6514 */
6515
6516 /**
6517 * @event add
6518 *
6519 * An `add` event is emitted when options are added to the select with the #addItems method.
6520 *
6521 * @param {OO.ui.OptionWidget[]} items Added items
6522 * @param {number} index Index of insertion point
6523 */
6524
6525 /**
6526 * @event remove
6527 *
6528 * A `remove` event is emitted when options are removed from the select with the #clearItems
6529 * or #removeItems methods.
6530 *
6531 * @param {OO.ui.OptionWidget[]} items Removed items
6532 */
6533
6534 /* Methods */
6535
6536 /**
6537 * Handle focus events
6538 *
6539 * @private
6540 * @param {jQuery.Event} event
6541 */
6542 OO.ui.SelectWidget.prototype.onFocus = function ( event ) {
6543 var item;
6544 if ( event.target === this.$element[ 0 ] ) {
6545 // This widget was focussed, e.g. by the user tabbing to it.
6546 // The styles for focus state depend on one of the items being selected.
6547 if ( !this.findSelectedItem() ) {
6548 item = this.findFirstSelectableItem();
6549 }
6550 } else {
6551 if ( event.target.tabIndex === -1 ) {
6552 // One of the options got focussed (and the event bubbled up here).
6553 // They can't be tabbed to, but they can be activated using accesskeys.
6554 // OptionWidgets and focusable UI elements inside them have tabindex="-1" set.
6555 item = this.findTargetItem( event );
6556 } else {
6557 // There is something actually user-focusable in one of the labels of the options, and the
6558 // user focussed it (e.g. by tabbing to it). Do nothing (especially, don't change the focus).
6559 return;
6560 }
6561 }
6562
6563 if ( item ) {
6564 if ( item.constructor.static.highlightable ) {
6565 this.highlightItem( item );
6566 } else {
6567 this.selectItem( item );
6568 }
6569 }
6570
6571 if ( event.target !== this.$element[ 0 ] ) {
6572 this.$focusOwner.trigger( 'focus' );
6573 }
6574 };
6575
6576 /**
6577 * Handle mouse down events.
6578 *
6579 * @private
6580 * @param {jQuery.Event} e Mouse down event
6581 * @return {undefined/boolean} False to prevent default if event is handled
6582 */
6583 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
6584 var item;
6585
6586 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
6587 this.togglePressed( true );
6588 item = this.findTargetItem( e );
6589 if ( item && item.isSelectable() ) {
6590 this.pressItem( item );
6591 this.selecting = item;
6592 this.getElementDocument().addEventListener( 'mouseup', this.onDocumentMouseUpHandler, true );
6593 this.getElementDocument().addEventListener( 'mousemove', this.onDocumentMouseMoveHandler, true );
6594 }
6595 }
6596 return false;
6597 };
6598
6599 /**
6600 * Handle document mouse up events.
6601 *
6602 * @private
6603 * @param {MouseEvent} e Mouse up event
6604 * @return {undefined/boolean} False to prevent default if event is handled
6605 */
6606 OO.ui.SelectWidget.prototype.onDocumentMouseUp = function ( e ) {
6607 var item;
6608
6609 this.togglePressed( false );
6610 if ( !this.selecting ) {
6611 item = this.findTargetItem( e );
6612 if ( item && item.isSelectable() ) {
6613 this.selecting = item;
6614 }
6615 }
6616 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT && this.selecting ) {
6617 this.pressItem( null );
6618 this.chooseItem( this.selecting );
6619 this.selecting = null;
6620 }
6621
6622 this.getElementDocument().removeEventListener( 'mouseup', this.onDocumentMouseUpHandler, true );
6623 this.getElementDocument().removeEventListener( 'mousemove', this.onDocumentMouseMoveHandler, true );
6624
6625 return false;
6626 };
6627
6628 // Deprecated alias since 0.28.3
6629 OO.ui.SelectWidget.prototype.onMouseUp = function () {
6630 OO.ui.warnDeprecation( 'onMouseUp is deprecated, use onDocumentMouseUp instead' );
6631 this.onDocumentMouseUp.apply( this, arguments );
6632 };
6633
6634 /**
6635 * Handle document mouse move events.
6636 *
6637 * @private
6638 * @param {MouseEvent} e Mouse move event
6639 */
6640 OO.ui.SelectWidget.prototype.onDocumentMouseMove = function ( e ) {
6641 var item;
6642
6643 if ( !this.isDisabled() && this.pressed ) {
6644 item = this.findTargetItem( e );
6645 if ( item && item !== this.selecting && item.isSelectable() ) {
6646 this.pressItem( item );
6647 this.selecting = item;
6648 }
6649 }
6650 };
6651
6652 // Deprecated alias since 0.28.3
6653 OO.ui.SelectWidget.prototype.onMouseMove = function () {
6654 OO.ui.warnDeprecation( 'onMouseMove is deprecated, use onDocumentMouseMove instead' );
6655 this.onDocumentMouseMove.apply( this, arguments );
6656 };
6657
6658 /**
6659 * Handle mouse over events.
6660 *
6661 * @private
6662 * @param {jQuery.Event} e Mouse over event
6663 * @return {undefined/boolean} False to prevent default if event is handled
6664 */
6665 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
6666 var item;
6667 if ( this.blockMouseOverEvents ) {
6668 return;
6669 }
6670 if ( !this.isDisabled() ) {
6671 item = this.findTargetItem( e );
6672 this.highlightItem( item && item.isHighlightable() ? item : null );
6673 }
6674 return false;
6675 };
6676
6677 /**
6678 * Handle mouse leave events.
6679 *
6680 * @private
6681 * @param {jQuery.Event} e Mouse over event
6682 * @return {undefined/boolean} False to prevent default if event is handled
6683 */
6684 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
6685 if ( !this.isDisabled() ) {
6686 this.highlightItem( null );
6687 }
6688 return false;
6689 };
6690
6691 /**
6692 * Handle document key down events.
6693 *
6694 * @protected
6695 * @param {KeyboardEvent} e Key down event
6696 */
6697 OO.ui.SelectWidget.prototype.onDocumentKeyDown = function ( e ) {
6698 var nextItem,
6699 handled = false,
6700 currentItem = this.findHighlightedItem() || this.findSelectedItem();
6701
6702 if ( !this.isDisabled() && this.isVisible() ) {
6703 switch ( e.keyCode ) {
6704 case OO.ui.Keys.ENTER:
6705 if ( currentItem && currentItem.constructor.static.highlightable ) {
6706 // Was only highlighted, now let's select it. No-op if already selected.
6707 this.chooseItem( currentItem );
6708 handled = true;
6709 }
6710 break;
6711 case OO.ui.Keys.UP:
6712 case OO.ui.Keys.LEFT:
6713 this.clearKeyPressBuffer();
6714 nextItem = this.findRelativeSelectableItem( currentItem, -1 );
6715 handled = true;
6716 break;
6717 case OO.ui.Keys.DOWN:
6718 case OO.ui.Keys.RIGHT:
6719 this.clearKeyPressBuffer();
6720 nextItem = this.findRelativeSelectableItem( currentItem, 1 );
6721 handled = true;
6722 break;
6723 case OO.ui.Keys.ESCAPE:
6724 case OO.ui.Keys.TAB:
6725 if ( currentItem && currentItem.constructor.static.highlightable ) {
6726 currentItem.setHighlighted( false );
6727 }
6728 this.unbindDocumentKeyDownListener();
6729 this.unbindDocumentKeyPressListener();
6730 // Don't prevent tabbing away / defocusing
6731 handled = false;
6732 break;
6733 }
6734
6735 if ( nextItem ) {
6736 if ( nextItem.constructor.static.highlightable ) {
6737 this.highlightItem( nextItem );
6738 } else {
6739 this.chooseItem( nextItem );
6740 }
6741 this.scrollItemIntoView( nextItem );
6742 }
6743
6744 if ( handled ) {
6745 e.preventDefault();
6746 e.stopPropagation();
6747 }
6748 }
6749 };
6750
6751 // Deprecated alias since 0.28.3
6752 OO.ui.SelectWidget.prototype.onKeyDown = function () {
6753 OO.ui.warnDeprecation( 'onKeyDown is deprecated, use onDocumentKeyDown instead' );
6754 this.onDocumentKeyDown.apply( this, arguments );
6755 };
6756
6757 /**
6758 * Bind document key down listener.
6759 *
6760 * @protected
6761 */
6762 OO.ui.SelectWidget.prototype.bindDocumentKeyDownListener = function () {
6763 this.getElementDocument().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
6764 };
6765
6766 // Deprecated alias since 0.28.3
6767 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
6768 OO.ui.warnDeprecation( 'bindKeyDownListener is deprecated, use bindDocumentKeyDownListener instead' );
6769 this.bindDocumentKeyDownListener.apply( this, arguments );
6770 };
6771
6772 /**
6773 * Unbind document key down listener.
6774 *
6775 * @protected
6776 */
6777 OO.ui.SelectWidget.prototype.unbindDocumentKeyDownListener = function () {
6778 this.getElementDocument().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
6779 };
6780
6781 // Deprecated alias since 0.28.3
6782 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
6783 OO.ui.warnDeprecation( 'unbindKeyDownListener is deprecated, use unbindDocumentKeyDownListener instead' );
6784 this.unbindDocumentKeyDownListener.apply( this, arguments );
6785 };
6786
6787 /**
6788 * Scroll item into view, preventing spurious mouse highlight actions from happening.
6789 *
6790 * @param {OO.ui.OptionWidget} item Item to scroll into view
6791 */
6792 OO.ui.SelectWidget.prototype.scrollItemIntoView = function ( item ) {
6793 var widget = this;
6794 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling
6795 // and around 100-150 ms after it is finished.
6796 this.blockMouseOverEvents++;
6797 item.scrollElementIntoView().done( function () {
6798 setTimeout( function () {
6799 widget.blockMouseOverEvents--;
6800 }, 200 );
6801 } );
6802 };
6803
6804 /**
6805 * Clear the key-press buffer
6806 *
6807 * @protected
6808 */
6809 OO.ui.SelectWidget.prototype.clearKeyPressBuffer = function () {
6810 if ( this.keyPressBufferTimer ) {
6811 clearTimeout( this.keyPressBufferTimer );
6812 this.keyPressBufferTimer = null;
6813 }
6814 this.keyPressBuffer = '';
6815 };
6816
6817 /**
6818 * Handle key press events.
6819 *
6820 * @protected
6821 * @param {KeyboardEvent} e Key press event
6822 * @return {undefined/boolean} False to prevent default if event is handled
6823 */
6824 OO.ui.SelectWidget.prototype.onDocumentKeyPress = function ( e ) {
6825 var c, filter, item;
6826
6827 if ( !e.charCode ) {
6828 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.keyPressBuffer !== '' ) {
6829 this.keyPressBuffer = this.keyPressBuffer.substr( 0, this.keyPressBuffer.length - 1 );
6830 return false;
6831 }
6832 return;
6833 }
6834 // eslint-disable-next-line no-restricted-properties
6835 if ( String.fromCodePoint ) {
6836 // eslint-disable-next-line no-restricted-properties
6837 c = String.fromCodePoint( e.charCode );
6838 } else {
6839 c = String.fromCharCode( e.charCode );
6840 }
6841
6842 if ( this.keyPressBufferTimer ) {
6843 clearTimeout( this.keyPressBufferTimer );
6844 }
6845 this.keyPressBufferTimer = setTimeout( this.clearKeyPressBuffer.bind( this ), 1500 );
6846
6847 item = this.findHighlightedItem() || this.findSelectedItem();
6848
6849 if ( this.keyPressBuffer === c ) {
6850 // Common (if weird) special case: typing "xxxx" will cycle through all
6851 // the items beginning with "x".
6852 if ( item ) {
6853 item = this.findRelativeSelectableItem( item, 1 );
6854 }
6855 } else {
6856 this.keyPressBuffer += c;
6857 }
6858
6859 filter = this.getItemMatcher( this.keyPressBuffer, false );
6860 if ( !item || !filter( item ) ) {
6861 item = this.findRelativeSelectableItem( item, 1, filter );
6862 }
6863 if ( item ) {
6864 if ( this.isVisible() && item.constructor.static.highlightable ) {
6865 this.highlightItem( item );
6866 } else {
6867 this.chooseItem( item );
6868 }
6869 this.scrollItemIntoView( item );
6870 }
6871
6872 e.preventDefault();
6873 e.stopPropagation();
6874 };
6875
6876 // Deprecated alias since 0.28.3
6877 OO.ui.SelectWidget.prototype.onKeyPress = function () {
6878 OO.ui.warnDeprecation( 'onKeyPress is deprecated, use onDocumentKeyPress instead' );
6879 this.onDocumentKeyPress.apply( this, arguments );
6880 };
6881
6882 /**
6883 * Get a matcher for the specific string
6884 *
6885 * @protected
6886 * @param {string} s String to match against items
6887 * @param {boolean} [exact=false] Only accept exact matches
6888 * @return {Function} function ( OO.ui.OptionWidget ) => boolean
6889 */
6890 OO.ui.SelectWidget.prototype.getItemMatcher = function ( s, exact ) {
6891 var re;
6892
6893 // eslint-disable-next-line no-restricted-properties
6894 if ( s.normalize ) {
6895 // eslint-disable-next-line no-restricted-properties
6896 s = s.normalize();
6897 }
6898 s = exact ? s.trim() : s.replace( /^\s+/, '' );
6899 re = '^\\s*' + s.replace( /([\\{}()|.?*+\-^$[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
6900 if ( exact ) {
6901 re += '\\s*$';
6902 }
6903 re = new RegExp( re, 'i' );
6904 return function ( item ) {
6905 var matchText = item.getMatchText();
6906 // eslint-disable-next-line no-restricted-properties
6907 if ( matchText.normalize ) {
6908 // eslint-disable-next-line no-restricted-properties
6909 matchText = matchText.normalize();
6910 }
6911 return re.test( matchText );
6912 };
6913 };
6914
6915 /**
6916 * Bind document key press listener.
6917 *
6918 * @protected
6919 */
6920 OO.ui.SelectWidget.prototype.bindDocumentKeyPressListener = function () {
6921 this.getElementDocument().addEventListener( 'keypress', this.onDocumentKeyPressHandler, true );
6922 };
6923
6924 // Deprecated alias since 0.28.3
6925 OO.ui.SelectWidget.prototype.bindKeyPressListener = function () {
6926 OO.ui.warnDeprecation( 'bindKeyPressListener is deprecated, use bindDocumentKeyPressListener instead' );
6927 this.bindDocumentKeyPressListener.apply( this, arguments );
6928 };
6929
6930 /**
6931 * Unbind document key down listener.
6932 *
6933 * If you override this, be sure to call this.clearKeyPressBuffer() from your
6934 * implementation.
6935 *
6936 * @protected
6937 */
6938 OO.ui.SelectWidget.prototype.unbindDocumentKeyPressListener = function () {
6939 this.getElementDocument().removeEventListener( 'keypress', this.onDocumentKeyPressHandler, true );
6940 this.clearKeyPressBuffer();
6941 };
6942
6943 // Deprecated alias since 0.28.3
6944 OO.ui.SelectWidget.prototype.unbindKeyPressListener = function () {
6945 OO.ui.warnDeprecation( 'unbindKeyPressListener is deprecated, use unbindDocumentKeyPressListener instead' );
6946 this.unbindDocumentKeyPressListener.apply( this, arguments );
6947 };
6948
6949 /**
6950 * Visibility change handler
6951 *
6952 * @protected
6953 * @param {boolean} visible
6954 */
6955 OO.ui.SelectWidget.prototype.onToggle = function ( visible ) {
6956 if ( !visible ) {
6957 this.clearKeyPressBuffer();
6958 }
6959 };
6960
6961 /**
6962 * Get the closest item to a jQuery.Event.
6963 *
6964 * @private
6965 * @param {jQuery.Event} e
6966 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
6967 */
6968 OO.ui.SelectWidget.prototype.findTargetItem = function ( e ) {
6969 var $option = $( e.target ).closest( '.oo-ui-optionWidget' );
6970 if ( !$option.closest( '.oo-ui-selectWidget' ).is( this.$element ) ) {
6971 return null;
6972 }
6973 return $option.data( 'oo-ui-optionWidget' ) || null;
6974 };
6975
6976 /**
6977 * Find selected item.
6978 *
6979 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
6980 */
6981 OO.ui.SelectWidget.prototype.findSelectedItem = function () {
6982 var i, len;
6983
6984 for ( i = 0, len = this.items.length; i < len; i++ ) {
6985 if ( this.items[ i ].isSelected() ) {
6986 return this.items[ i ];
6987 }
6988 }
6989 return null;
6990 };
6991
6992 /**
6993 * Find highlighted item.
6994 *
6995 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
6996 */
6997 OO.ui.SelectWidget.prototype.findHighlightedItem = function () {
6998 var i, len;
6999
7000 for ( i = 0, len = this.items.length; i < len; i++ ) {
7001 if ( this.items[ i ].isHighlighted() ) {
7002 return this.items[ i ];
7003 }
7004 }
7005 return null;
7006 };
7007
7008 /**
7009 * Toggle pressed state.
7010 *
7011 * Press is a state that occurs when a user mouses down on an item, but
7012 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
7013 * until the user releases the mouse.
7014 *
7015 * @param {boolean} pressed An option is being pressed
7016 */
7017 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
7018 if ( pressed === undefined ) {
7019 pressed = !this.pressed;
7020 }
7021 if ( pressed !== this.pressed ) {
7022 this.$element
7023 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
7024 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
7025 this.pressed = pressed;
7026 }
7027 };
7028
7029 /**
7030 * Highlight an option. If the `item` param is omitted, no options will be highlighted
7031 * and any existing highlight will be removed. The highlight is mutually exclusive.
7032 *
7033 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
7034 * @fires highlight
7035 * @chainable
7036 * @return {OO.ui.Widget} The widget, for chaining
7037 */
7038 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
7039 var i, len, highlighted,
7040 changed = false;
7041
7042 for ( i = 0, len = this.items.length; i < len; i++ ) {
7043 highlighted = this.items[ i ] === item;
7044 if ( this.items[ i ].isHighlighted() !== highlighted ) {
7045 this.items[ i ].setHighlighted( highlighted );
7046 changed = true;
7047 }
7048 }
7049 if ( changed ) {
7050 if ( item ) {
7051 this.$focusOwner.attr( 'aria-activedescendant', item.getElementId() );
7052 } else {
7053 this.$focusOwner.removeAttr( 'aria-activedescendant' );
7054 }
7055 this.emit( 'highlight', item );
7056 }
7057
7058 return this;
7059 };
7060
7061 /**
7062 * Fetch an item by its label.
7063 *
7064 * @param {string} label Label of the item to select.
7065 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
7066 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
7067 */
7068 OO.ui.SelectWidget.prototype.getItemFromLabel = function ( label, prefix ) {
7069 var i, item, found,
7070 len = this.items.length,
7071 filter = this.getItemMatcher( label, true );
7072
7073 for ( i = 0; i < len; i++ ) {
7074 item = this.items[ i ];
7075 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
7076 return item;
7077 }
7078 }
7079
7080 if ( prefix ) {
7081 found = null;
7082 filter = this.getItemMatcher( label, false );
7083 for ( i = 0; i < len; i++ ) {
7084 item = this.items[ i ];
7085 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
7086 if ( found ) {
7087 return null;
7088 }
7089 found = item;
7090 }
7091 }
7092 if ( found ) {
7093 return found;
7094 }
7095 }
7096
7097 return null;
7098 };
7099
7100 /**
7101 * Programmatically select an option by its label. If the item does not exist,
7102 * all options will be deselected.
7103 *
7104 * @param {string} [label] Label of the item to select.
7105 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
7106 * @fires select
7107 * @chainable
7108 * @return {OO.ui.Widget} The widget, for chaining
7109 */
7110 OO.ui.SelectWidget.prototype.selectItemByLabel = function ( label, prefix ) {
7111 var itemFromLabel = this.getItemFromLabel( label, !!prefix );
7112 if ( label === undefined || !itemFromLabel ) {
7113 return this.selectItem();
7114 }
7115 return this.selectItem( itemFromLabel );
7116 };
7117
7118 /**
7119 * Programmatically select an option by its data. If the `data` parameter is omitted,
7120 * or if the item does not exist, all options will be deselected.
7121 *
7122 * @param {Object|string} [data] Value of the item to select, omit to deselect all
7123 * @fires select
7124 * @chainable
7125 * @return {OO.ui.Widget} The widget, for chaining
7126 */
7127 OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) {
7128 var itemFromData = this.findItemFromData( data );
7129 if ( data === undefined || !itemFromData ) {
7130 return this.selectItem();
7131 }
7132 return this.selectItem( itemFromData );
7133 };
7134
7135 /**
7136 * Programmatically select an option by its reference. If the `item` parameter is omitted,
7137 * all options will be deselected.
7138 *
7139 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
7140 * @fires select
7141 * @chainable
7142 * @return {OO.ui.Widget} The widget, for chaining
7143 */
7144 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
7145 var i, len, selected,
7146 changed = false;
7147
7148 for ( i = 0, len = this.items.length; i < len; i++ ) {
7149 selected = this.items[ i ] === item;
7150 if ( this.items[ i ].isSelected() !== selected ) {
7151 this.items[ i ].setSelected( selected );
7152 changed = true;
7153 }
7154 }
7155 if ( changed ) {
7156 if ( item && !item.constructor.static.highlightable ) {
7157 if ( item ) {
7158 this.$focusOwner.attr( 'aria-activedescendant', item.getElementId() );
7159 } else {
7160 this.$focusOwner.removeAttr( 'aria-activedescendant' );
7161 }
7162 }
7163 this.emit( 'select', item );
7164 }
7165
7166 return this;
7167 };
7168
7169 /**
7170 * Press an item.
7171 *
7172 * Press is a state that occurs when a user mouses down on an item, but has not
7173 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
7174 * releases the mouse.
7175 *
7176 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
7177 * @fires press
7178 * @chainable
7179 * @return {OO.ui.Widget} The widget, for chaining
7180 */
7181 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
7182 var i, len, pressed,
7183 changed = false;
7184
7185 for ( i = 0, len = this.items.length; i < len; i++ ) {
7186 pressed = this.items[ i ] === item;
7187 if ( this.items[ i ].isPressed() !== pressed ) {
7188 this.items[ i ].setPressed( pressed );
7189 changed = true;
7190 }
7191 }
7192 if ( changed ) {
7193 this.emit( 'press', item );
7194 }
7195
7196 return this;
7197 };
7198
7199 /**
7200 * Choose an item.
7201 *
7202 * Note that ‘choose’ should never be modified programmatically. A user can choose
7203 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
7204 * use the #selectItem method.
7205 *
7206 * This method is identical to #selectItem, but may vary in subclasses that take additional action
7207 * when users choose an item with the keyboard or mouse.
7208 *
7209 * @param {OO.ui.OptionWidget} item Item to choose
7210 * @fires choose
7211 * @chainable
7212 * @return {OO.ui.Widget} The widget, for chaining
7213 */
7214 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
7215 if ( item ) {
7216 this.selectItem( item );
7217 this.emit( 'choose', item );
7218 }
7219
7220 return this;
7221 };
7222
7223 /**
7224 * Find an option by its position relative to the specified item (or to the start of the option array,
7225 * if item is `null`). The direction in which to search through the option array is specified with a
7226 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
7227 * `null` if there are no options in the array.
7228 *
7229 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
7230 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
7231 * @param {Function} [filter] Only consider items for which this function returns
7232 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
7233 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
7234 */
7235 OO.ui.SelectWidget.prototype.findRelativeSelectableItem = function ( item, direction, filter ) {
7236 var currentIndex, nextIndex, i,
7237 increase = direction > 0 ? 1 : -1,
7238 len = this.items.length;
7239
7240 if ( item instanceof OO.ui.OptionWidget ) {
7241 currentIndex = this.items.indexOf( item );
7242 nextIndex = ( currentIndex + increase + len ) % len;
7243 } else {
7244 // If no item is selected and moving forward, start at the beginning.
7245 // If moving backward, start at the end.
7246 nextIndex = direction > 0 ? 0 : len - 1;
7247 }
7248
7249 for ( i = 0; i < len; i++ ) {
7250 item = this.items[ nextIndex ];
7251 if (
7252 item instanceof OO.ui.OptionWidget && item.isSelectable() &&
7253 ( !filter || filter( item ) )
7254 ) {
7255 return item;
7256 }
7257 nextIndex = ( nextIndex + increase + len ) % len;
7258 }
7259 return null;
7260 };
7261
7262 /**
7263 * Find the next selectable item or `null` if there are no selectable items.
7264 * Disabled options and menu-section markers and breaks are not selectable.
7265 *
7266 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
7267 */
7268 OO.ui.SelectWidget.prototype.findFirstSelectableItem = function () {
7269 return this.findRelativeSelectableItem( null, 1 );
7270 };
7271
7272 /**
7273 * Add an array of options to the select. Optionally, an index number can be used to
7274 * specify an insertion point.
7275 *
7276 * @param {OO.ui.OptionWidget[]} items Items to add
7277 * @param {number} [index] Index to insert items after
7278 * @fires add
7279 * @chainable
7280 * @return {OO.ui.Widget} The widget, for chaining
7281 */
7282 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
7283 // Mixin method
7284 OO.ui.mixin.GroupWidget.prototype.addItems.call( this, items, index );
7285
7286 // Always provide an index, even if it was omitted
7287 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
7288
7289 return this;
7290 };
7291
7292 /**
7293 * Remove the specified array of options from the select. Options will be detached
7294 * from the DOM, not removed, so they can be reused later. To remove all options from
7295 * the select, you may wish to use the #clearItems method instead.
7296 *
7297 * @param {OO.ui.OptionWidget[]} items Items to remove
7298 * @fires remove
7299 * @chainable
7300 * @return {OO.ui.Widget} The widget, for chaining
7301 */
7302 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
7303 var i, len, item;
7304
7305 // Deselect items being removed
7306 for ( i = 0, len = items.length; i < len; i++ ) {
7307 item = items[ i ];
7308 if ( item.isSelected() ) {
7309 this.selectItem( null );
7310 }
7311 }
7312
7313 // Mixin method
7314 OO.ui.mixin.GroupWidget.prototype.removeItems.call( this, items );
7315
7316 this.emit( 'remove', items );
7317
7318 return this;
7319 };
7320
7321 /**
7322 * Clear all options from the select. Options will be detached from the DOM, not removed,
7323 * so that they can be reused later. To remove a subset of options from the select, use
7324 * the #removeItems method.
7325 *
7326 * @fires remove
7327 * @chainable
7328 * @return {OO.ui.Widget} The widget, for chaining
7329 */
7330 OO.ui.SelectWidget.prototype.clearItems = function () {
7331 var items = this.items.slice();
7332
7333 // Mixin method
7334 OO.ui.mixin.GroupWidget.prototype.clearItems.call( this );
7335
7336 // Clear selection
7337 this.selectItem( null );
7338
7339 this.emit( 'remove', items );
7340
7341 return this;
7342 };
7343
7344 /**
7345 * Set the DOM element which has focus while the user is interacting with this SelectWidget.
7346 *
7347 * This is used to set `aria-activedescendant` and `aria-expanded` on it.
7348 *
7349 * @protected
7350 * @param {jQuery} $focusOwner
7351 */
7352 OO.ui.SelectWidget.prototype.setFocusOwner = function ( $focusOwner ) {
7353 this.$focusOwner = $focusOwner;
7354 };
7355
7356 /**
7357 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
7358 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
7359 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
7360 * options. For more information about options and selects, please see the
7361 * [OOUI documentation on MediaWiki][1].
7362 *
7363 * @example
7364 * // Decorated options in a select widget.
7365 * var select = new OO.ui.SelectWidget( {
7366 * items: [
7367 * new OO.ui.DecoratedOptionWidget( {
7368 * data: 'a',
7369 * label: 'Option with icon',
7370 * icon: 'help'
7371 * } ),
7372 * new OO.ui.DecoratedOptionWidget( {
7373 * data: 'b',
7374 * label: 'Option with indicator',
7375 * indicator: 'next'
7376 * } )
7377 * ]
7378 * } );
7379 * $( document.body ).append( select.$element );
7380 *
7381 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7382 *
7383 * @class
7384 * @extends OO.ui.OptionWidget
7385 * @mixins OO.ui.mixin.IconElement
7386 * @mixins OO.ui.mixin.IndicatorElement
7387 *
7388 * @constructor
7389 * @param {Object} [config] Configuration options
7390 */
7391 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
7392 // Parent constructor
7393 OO.ui.DecoratedOptionWidget.parent.call( this, config );
7394
7395 // Mixin constructors
7396 OO.ui.mixin.IconElement.call( this, config );
7397 OO.ui.mixin.IndicatorElement.call( this, config );
7398
7399 // Initialization
7400 this.$element
7401 .addClass( 'oo-ui-decoratedOptionWidget' )
7402 .prepend( this.$icon )
7403 .append( this.$indicator );
7404 };
7405
7406 /* Setup */
7407
7408 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
7409 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IconElement );
7410 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IndicatorElement );
7411
7412 /**
7413 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
7414 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
7415 * the [OOUI documentation on MediaWiki] [1] for more information.
7416 *
7417 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
7418 *
7419 * @class
7420 * @extends OO.ui.DecoratedOptionWidget
7421 *
7422 * @constructor
7423 * @param {Object} [config] Configuration options
7424 */
7425 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
7426 // Parent constructor
7427 OO.ui.MenuOptionWidget.parent.call( this, config );
7428
7429 // Properties
7430 this.checkIcon = new OO.ui.IconWidget( {
7431 icon: 'check',
7432 classes: [ 'oo-ui-menuOptionWidget-checkIcon' ]
7433 } );
7434
7435 // Initialization
7436 this.$element
7437 .prepend( this.checkIcon.$element )
7438 .addClass( 'oo-ui-menuOptionWidget' );
7439 };
7440
7441 /* Setup */
7442
7443 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
7444
7445 /* Static Properties */
7446
7447 /**
7448 * @static
7449 * @inheritdoc
7450 */
7451 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
7452
7453 /**
7454 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
7455 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
7456 *
7457 * @example
7458 * var dropdown = new OO.ui.DropdownWidget( {
7459 * menu: {
7460 * items: [
7461 * new OO.ui.MenuSectionOptionWidget( {
7462 * label: 'Dogs'
7463 * } ),
7464 * new OO.ui.MenuOptionWidget( {
7465 * data: 'corgi',
7466 * label: 'Welsh Corgi'
7467 * } ),
7468 * new OO.ui.MenuOptionWidget( {
7469 * data: 'poodle',
7470 * label: 'Standard Poodle'
7471 * } ),
7472 * new OO.ui.MenuSectionOptionWidget( {
7473 * label: 'Cats'
7474 * } ),
7475 * new OO.ui.MenuOptionWidget( {
7476 * data: 'lion',
7477 * label: 'Lion'
7478 * } )
7479 * ]
7480 * }
7481 * } );
7482 * $( document.body ).append( dropdown.$element );
7483 *
7484 * @class
7485 * @extends OO.ui.DecoratedOptionWidget
7486 *
7487 * @constructor
7488 * @param {Object} [config] Configuration options
7489 */
7490 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
7491 // Parent constructor
7492 OO.ui.MenuSectionOptionWidget.parent.call( this, config );
7493
7494 // Initialization
7495 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' )
7496 .removeAttr( 'role aria-selected' );
7497 };
7498
7499 /* Setup */
7500
7501 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
7502
7503 /* Static Properties */
7504
7505 /**
7506 * @static
7507 * @inheritdoc
7508 */
7509 OO.ui.MenuSectionOptionWidget.static.selectable = false;
7510
7511 /**
7512 * @static
7513 * @inheritdoc
7514 */
7515 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
7516
7517 /**
7518 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
7519 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
7520 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
7521 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
7522 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
7523 * and customized to be opened, closed, and displayed as needed.
7524 *
7525 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
7526 * mouse outside the menu.
7527 *
7528 * Menus also have support for keyboard interaction:
7529 *
7530 * - Enter/Return key: choose and select a menu option
7531 * - Up-arrow key: highlight the previous menu option
7532 * - Down-arrow key: highlight the next menu option
7533 * - Esc key: hide the menu
7534 *
7535 * Unlike most widgets, MenuSelectWidget is initially hidden and must be shown by calling #toggle.
7536 *
7537 * Please see the [OOUI documentation on MediaWiki][1] for more information.
7538 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7539 *
7540 * @class
7541 * @extends OO.ui.SelectWidget
7542 * @mixins OO.ui.mixin.ClippableElement
7543 * @mixins OO.ui.mixin.FloatableElement
7544 *
7545 * @constructor
7546 * @param {Object} [config] Configuration options
7547 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
7548 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
7549 * and {@link OO.ui.mixin.LookupElement LookupElement}
7550 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
7551 * the text the user types. This config is used by {@link OO.ui.TagMultiselectWidget TagMultiselectWidget}
7552 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
7553 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
7554 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
7555 * that button, unless the button (or its parent widget) is passed in here.
7556 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
7557 * @cfg {jQuery} [$autoCloseIgnore] If these elements are clicked, don't auto-hide the menu.
7558 * @cfg {boolean} [hideOnChoose=true] Hide the menu when the user chooses an option.
7559 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
7560 * @cfg {boolean} [highlightOnFilter] Highlight the first result when filtering
7561 * @param {number|string} [width] Width of the menu as a number of pixels or CSS string with unit suffix,
7562 * used by {@link OO.ui.mixin.ClippableElement ClippableElement}
7563 */
7564 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
7565 // Configuration initialization
7566 config = config || {};
7567
7568 // Parent constructor
7569 OO.ui.MenuSelectWidget.parent.call( this, config );
7570
7571 // Mixin constructors
7572 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
7573 OO.ui.mixin.FloatableElement.call( this, config );
7574
7575 // Initial vertical positions other than 'center' will result in
7576 // the menu being flipped if there is not enough space in the container.
7577 // Store the original position so we know what to reset to.
7578 this.originalVerticalPosition = this.verticalPosition;
7579
7580 // Properties
7581 this.autoHide = config.autoHide === undefined || !!config.autoHide;
7582 this.hideOnChoose = config.hideOnChoose === undefined || !!config.hideOnChoose;
7583 this.filterFromInput = !!config.filterFromInput;
7584 this.$input = config.$input ? config.$input : config.input ? config.input.$input : null;
7585 this.$widget = config.widget ? config.widget.$element : null;
7586 this.$autoCloseIgnore = config.$autoCloseIgnore || $( [] );
7587 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
7588 this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 );
7589 this.highlightOnFilter = !!config.highlightOnFilter;
7590 this.width = config.width;
7591
7592 // Initialization
7593 this.$element.addClass( 'oo-ui-menuSelectWidget' );
7594 if ( config.widget ) {
7595 this.setFocusOwner( config.widget.$tabIndexed );
7596 }
7597
7598 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
7599 // that reference properties not initialized at that time of parent class construction
7600 // TODO: Find a better way to handle post-constructor setup
7601 this.visible = false;
7602 this.$element.addClass( 'oo-ui-element-hidden' );
7603 this.$focusOwner.attr( 'aria-expanded', 'false' );
7604 };
7605
7606 /* Setup */
7607
7608 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
7609 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement );
7610 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.FloatableElement );
7611
7612 /* Events */
7613
7614 /**
7615 * @event ready
7616 *
7617 * The menu is ready: it is visible and has been positioned and clipped.
7618 */
7619
7620 /* Static properties */
7621
7622 /**
7623 * Positions to flip to if there isn't room in the container for the
7624 * menu in a specific direction.
7625 *
7626 * @property {Object.<string,string>}
7627 */
7628 OO.ui.MenuSelectWidget.static.flippedPositions = {
7629 below: 'above',
7630 above: 'below',
7631 top: 'bottom',
7632 bottom: 'top'
7633 };
7634
7635 /* Methods */
7636
7637 /**
7638 * Handles document mouse down events.
7639 *
7640 * @protected
7641 * @param {MouseEvent} e Mouse down event
7642 */
7643 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
7644 if (
7645 this.isVisible() &&
7646 !OO.ui.contains(
7647 this.$element.add( this.$widget ).add( this.$autoCloseIgnore ).get(),
7648 e.target,
7649 true
7650 )
7651 ) {
7652 this.toggle( false );
7653 }
7654 };
7655
7656 /**
7657 * @inheritdoc
7658 */
7659 OO.ui.MenuSelectWidget.prototype.onDocumentKeyDown = function ( e ) {
7660 var currentItem = this.findHighlightedItem() || this.findSelectedItem();
7661
7662 if ( !this.isDisabled() && this.isVisible() ) {
7663 switch ( e.keyCode ) {
7664 case OO.ui.Keys.LEFT:
7665 case OO.ui.Keys.RIGHT:
7666 // Do nothing if a text field is associated, arrow keys will be handled natively
7667 if ( !this.$input ) {
7668 OO.ui.MenuSelectWidget.parent.prototype.onDocumentKeyDown.call( this, e );
7669 }
7670 break;
7671 case OO.ui.Keys.ESCAPE:
7672 case OO.ui.Keys.TAB:
7673 if ( currentItem ) {
7674 currentItem.setHighlighted( false );
7675 }
7676 this.toggle( false );
7677 // Don't prevent tabbing away, prevent defocusing
7678 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
7679 e.preventDefault();
7680 e.stopPropagation();
7681 }
7682 break;
7683 default:
7684 OO.ui.MenuSelectWidget.parent.prototype.onDocumentKeyDown.call( this, e );
7685 return;
7686 }
7687 }
7688 };
7689
7690 /**
7691 * Update menu item visibility and clipping after input changes (if filterFromInput is enabled)
7692 * or after items were added/removed (always).
7693 *
7694 * @protected
7695 */
7696 OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () {
7697 var i, item, items, visible, section, sectionEmpty, filter, exactFilter,
7698 anyVisible = false,
7699 len = this.items.length,
7700 showAll = !this.isVisible(),
7701 exactMatch = false;
7702
7703 if ( this.$input && this.filterFromInput ) {
7704 filter = showAll ? null : this.getItemMatcher( this.$input.val() );
7705 exactFilter = this.getItemMatcher( this.$input.val(), true );
7706 // Hide non-matching options, and also hide section headers if all options
7707 // in their section are hidden.
7708 for ( i = 0; i < len; i++ ) {
7709 item = this.items[ i ];
7710 if ( item instanceof OO.ui.MenuSectionOptionWidget ) {
7711 if ( section ) {
7712 // If the previous section was empty, hide its header
7713 section.toggle( showAll || !sectionEmpty );
7714 }
7715 section = item;
7716 sectionEmpty = true;
7717 } else if ( item instanceof OO.ui.OptionWidget ) {
7718 visible = showAll || filter( item );
7719 exactMatch = exactMatch || exactFilter( item );
7720 anyVisible = anyVisible || visible;
7721 sectionEmpty = sectionEmpty && !visible;
7722 item.toggle( visible );
7723 }
7724 }
7725 // Process the final section
7726 if ( section ) {
7727 section.toggle( showAll || !sectionEmpty );
7728 }
7729
7730 if ( anyVisible && this.items.length && !exactMatch ) {
7731 this.scrollItemIntoView( this.items[ 0 ] );
7732 }
7733
7734 if ( !anyVisible ) {
7735 this.highlightItem( null );
7736 }
7737
7738 this.$element.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible );
7739
7740 if ( this.highlightOnFilter ) {
7741 // Highlight the first item on the list
7742 item = null;
7743 items = this.getItems();
7744 for ( i = 0; i < items.length; i++ ) {
7745 if ( items[ i ].isVisible() ) {
7746 item = items[ i ];
7747 break;
7748 }
7749 }
7750 this.highlightItem( item );
7751 }
7752
7753 }
7754
7755 // Reevaluate clipping
7756 this.clip();
7757 };
7758
7759 /**
7760 * @inheritdoc
7761 */
7762 OO.ui.MenuSelectWidget.prototype.bindDocumentKeyDownListener = function () {
7763 if ( this.$input ) {
7764 this.$input.on( 'keydown', this.onDocumentKeyDownHandler );
7765 } else {
7766 OO.ui.MenuSelectWidget.parent.prototype.bindDocumentKeyDownListener.call( this );
7767 }
7768 };
7769
7770 /**
7771 * @inheritdoc
7772 */
7773 OO.ui.MenuSelectWidget.prototype.unbindDocumentKeyDownListener = function () {
7774 if ( this.$input ) {
7775 this.$input.off( 'keydown', this.onDocumentKeyDownHandler );
7776 } else {
7777 OO.ui.MenuSelectWidget.parent.prototype.unbindDocumentKeyDownListener.call( this );
7778 }
7779 };
7780
7781 /**
7782 * @inheritdoc
7783 */
7784 OO.ui.MenuSelectWidget.prototype.bindDocumentKeyPressListener = function () {
7785 if ( this.$input ) {
7786 if ( this.filterFromInput ) {
7787 this.$input.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
7788 this.updateItemVisibility();
7789 }
7790 } else {
7791 OO.ui.MenuSelectWidget.parent.prototype.bindDocumentKeyPressListener.call( this );
7792 }
7793 };
7794
7795 /**
7796 * @inheritdoc
7797 */
7798 OO.ui.MenuSelectWidget.prototype.unbindDocumentKeyPressListener = function () {
7799 if ( this.$input ) {
7800 if ( this.filterFromInput ) {
7801 this.$input.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
7802 this.updateItemVisibility();
7803 }
7804 } else {
7805 OO.ui.MenuSelectWidget.parent.prototype.unbindDocumentKeyPressListener.call( this );
7806 }
7807 };
7808
7809 /**
7810 * Choose an item.
7811 *
7812 * When a user chooses an item, the menu is closed, unless the hideOnChoose config option is set to false.
7813 *
7814 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
7815 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
7816 *
7817 * @param {OO.ui.OptionWidget} item Item to choose
7818 * @chainable
7819 * @return {OO.ui.Widget} The widget, for chaining
7820 */
7821 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
7822 OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item );
7823 if ( this.hideOnChoose ) {
7824 this.toggle( false );
7825 }
7826 return this;
7827 };
7828
7829 /**
7830 * @inheritdoc
7831 */
7832 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
7833 // Parent method
7834 OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index );
7835
7836 this.updateItemVisibility();
7837
7838 return this;
7839 };
7840
7841 /**
7842 * @inheritdoc
7843 */
7844 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
7845 // Parent method
7846 OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items );
7847
7848 this.updateItemVisibility();
7849
7850 return this;
7851 };
7852
7853 /**
7854 * @inheritdoc
7855 */
7856 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
7857 // Parent method
7858 OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this );
7859
7860 this.updateItemVisibility();
7861
7862 return this;
7863 };
7864
7865 /**
7866 * Toggle visibility of the menu. The menu is initially hidden and must be shown by calling
7867 * `.toggle( true )` after its #$element is attached to the DOM.
7868 *
7869 * Do not show the menu while it is not attached to the DOM. The calculations required to display
7870 * it in the right place and with the right dimensions only work correctly while it is attached.
7871 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
7872 * strictly enforced, so currently it only generates a warning in the browser console.
7873 *
7874 * @fires ready
7875 * @inheritdoc
7876 */
7877 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
7878 var change, originalHeight, flippedHeight;
7879
7880 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
7881 change = visible !== this.isVisible();
7882
7883 if ( visible && !this.warnedUnattached && !this.isElementAttached() ) {
7884 OO.ui.warnDeprecation( 'MenuSelectWidget#toggle: Before calling this method, the menu must be attached to the DOM.' );
7885 this.warnedUnattached = true;
7886 }
7887
7888 if ( change && visible ) {
7889 // Reset position before showing the popup again. It's possible we no longer need to flip
7890 // (e.g. if the user scrolled).
7891 this.setVerticalPosition( this.originalVerticalPosition );
7892 }
7893
7894 // Parent method
7895 OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible );
7896
7897 if ( change ) {
7898 if ( visible ) {
7899
7900 if ( this.width ) {
7901 this.setIdealSize( this.width );
7902 } else if ( this.$floatableContainer ) {
7903 this.$clippable.css( 'width', 'auto' );
7904 this.setIdealSize(
7905 this.$floatableContainer[ 0 ].offsetWidth > this.$clippable[ 0 ].offsetWidth ?
7906 // Dropdown is smaller than handle so expand to width
7907 this.$floatableContainer[ 0 ].offsetWidth :
7908 // Dropdown is larger than handle so auto size
7909 'auto'
7910 );
7911 this.$clippable.css( 'width', '' );
7912 }
7913
7914 this.togglePositioning( !!this.$floatableContainer );
7915 this.toggleClipping( true );
7916
7917 this.bindDocumentKeyDownListener();
7918 this.bindDocumentKeyPressListener();
7919
7920 if (
7921 ( this.isClippedVertically() || this.isFloatableOutOfView() ) &&
7922 this.originalVerticalPosition !== 'center'
7923 ) {
7924 // If opening the menu in one direction causes it to be clipped, flip it
7925 originalHeight = this.$element.height();
7926 this.setVerticalPosition(
7927 this.constructor.static.flippedPositions[ this.originalVerticalPosition ]
7928 );
7929 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
7930 // If flipping also causes it to be clipped, open in whichever direction
7931 // we have more space
7932 flippedHeight = this.$element.height();
7933 if ( originalHeight > flippedHeight ) {
7934 this.setVerticalPosition( this.originalVerticalPosition );
7935 }
7936 }
7937 }
7938 // Note that we do not flip the menu's opening direction if the clipping changes
7939 // later (e.g. after the user scrolls), that seems like it would be annoying
7940
7941 this.$focusOwner.attr( 'aria-expanded', 'true' );
7942
7943 if ( this.findSelectedItem() ) {
7944 this.$focusOwner.attr( 'aria-activedescendant', this.findSelectedItem().getElementId() );
7945 this.findSelectedItem().scrollElementIntoView( { duration: 0 } );
7946 }
7947
7948 // Auto-hide
7949 if ( this.autoHide ) {
7950 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
7951 }
7952
7953 this.emit( 'ready' );
7954 } else {
7955 this.$focusOwner.removeAttr( 'aria-activedescendant' );
7956 this.unbindDocumentKeyDownListener();
7957 this.unbindDocumentKeyPressListener();
7958 this.$focusOwner.attr( 'aria-expanded', 'false' );
7959 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
7960 this.togglePositioning( false );
7961 this.toggleClipping( false );
7962 }
7963 }
7964
7965 return this;
7966 };
7967
7968 /**
7969 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
7970 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
7971 * users can interact with it.
7972 *
7973 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7974 * OO.ui.DropdownInputWidget instead.
7975 *
7976 * @example
7977 * // A DropdownWidget with a menu that contains three options.
7978 * var dropDown = new OO.ui.DropdownWidget( {
7979 * label: 'Dropdown menu: Select a menu option',
7980 * menu: {
7981 * items: [
7982 * new OO.ui.MenuOptionWidget( {
7983 * data: 'a',
7984 * label: 'First'
7985 * } ),
7986 * new OO.ui.MenuOptionWidget( {
7987 * data: 'b',
7988 * label: 'Second'
7989 * } ),
7990 * new OO.ui.MenuOptionWidget( {
7991 * data: 'c',
7992 * label: 'Third'
7993 * } )
7994 * ]
7995 * }
7996 * } );
7997 *
7998 * $( document.body ).append( dropDown.$element );
7999 *
8000 * dropDown.getMenu().selectItemByData( 'b' );
8001 *
8002 * dropDown.getMenu().findSelectedItem().getData(); // Returns 'b'.
8003 *
8004 * For more information, please see the [OOUI documentation on MediaWiki] [1].
8005 *
8006 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
8007 *
8008 * @class
8009 * @extends OO.ui.Widget
8010 * @mixins OO.ui.mixin.IconElement
8011 * @mixins OO.ui.mixin.IndicatorElement
8012 * @mixins OO.ui.mixin.LabelElement
8013 * @mixins OO.ui.mixin.TitledElement
8014 * @mixins OO.ui.mixin.TabIndexedElement
8015 *
8016 * @constructor
8017 * @param {Object} [config] Configuration options
8018 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.MenuSelectWidget menu select widget}
8019 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
8020 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
8021 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
8022 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
8023 */
8024 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
8025 // Configuration initialization
8026 config = $.extend( { indicator: 'down' }, config );
8027
8028 // Parent constructor
8029 OO.ui.DropdownWidget.parent.call( this, config );
8030
8031 // Properties (must be set before TabIndexedElement constructor call)
8032 this.$handle = $( '<button>' );
8033 this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
8034
8035 // Mixin constructors
8036 OO.ui.mixin.IconElement.call( this, config );
8037 OO.ui.mixin.IndicatorElement.call( this, config );
8038 OO.ui.mixin.LabelElement.call( this, config );
8039 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
8040 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
8041
8042 // Properties
8043 this.menu = new OO.ui.MenuSelectWidget( $.extend( {
8044 widget: this,
8045 $floatableContainer: this.$element
8046 }, config.menu ) );
8047
8048 // Events
8049 this.$handle.on( {
8050 click: this.onClick.bind( this ),
8051 keydown: this.onKeyDown.bind( this ),
8052 // Hack? Handle type-to-search when menu is not expanded and not handling its own events
8053 keypress: this.menu.onDocumentKeyPressHandler,
8054 blur: this.menu.clearKeyPressBuffer.bind( this.menu )
8055 } );
8056 this.menu.connect( this, {
8057 select: 'onMenuSelect',
8058 toggle: 'onMenuToggle'
8059 } );
8060
8061 // Initialization
8062 this.$handle
8063 .addClass( 'oo-ui-dropdownWidget-handle' )
8064 .attr( {
8065 type: 'button',
8066 'aria-owns': this.menu.getElementId(),
8067 'aria-haspopup': 'listbox'
8068 } )
8069 .append( this.$icon, this.$label, this.$indicator );
8070 this.$element
8071 .addClass( 'oo-ui-dropdownWidget' )
8072 .append( this.$handle );
8073 this.$overlay.append( this.menu.$element );
8074 };
8075
8076 /* Setup */
8077
8078 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
8079 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IconElement );
8080 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IndicatorElement );
8081 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.LabelElement );
8082 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TitledElement );
8083 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TabIndexedElement );
8084
8085 /* Methods */
8086
8087 /**
8088 * Get the menu.
8089 *
8090 * @return {OO.ui.MenuSelectWidget} Menu of widget
8091 */
8092 OO.ui.DropdownWidget.prototype.getMenu = function () {
8093 return this.menu;
8094 };
8095
8096 /**
8097 * Handles menu select events.
8098 *
8099 * @private
8100 * @param {OO.ui.MenuOptionWidget} item Selected menu item
8101 */
8102 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
8103 var selectedLabel;
8104
8105 if ( !item ) {
8106 this.setLabel( null );
8107 return;
8108 }
8109
8110 selectedLabel = item.getLabel();
8111
8112 // If the label is a DOM element, clone it, because setLabel will append() it
8113 if ( selectedLabel instanceof $ ) {
8114 selectedLabel = selectedLabel.clone();
8115 }
8116
8117 this.setLabel( selectedLabel );
8118 };
8119
8120 /**
8121 * Handle menu toggle events.
8122 *
8123 * @private
8124 * @param {boolean} isVisible Open state of the menu
8125 */
8126 OO.ui.DropdownWidget.prototype.onMenuToggle = function ( isVisible ) {
8127 this.$element.toggleClass( 'oo-ui-dropdownWidget-open', isVisible );
8128 };
8129
8130 /**
8131 * Handle mouse click events.
8132 *
8133 * @private
8134 * @param {jQuery.Event} e Mouse click event
8135 * @return {undefined/boolean} False to prevent default if event is handled
8136 */
8137 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
8138 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
8139 this.menu.toggle();
8140 }
8141 return false;
8142 };
8143
8144 /**
8145 * Handle key down events.
8146 *
8147 * @private
8148 * @param {jQuery.Event} e Key down event
8149 * @return {undefined/boolean} False to prevent default if event is handled
8150 */
8151 OO.ui.DropdownWidget.prototype.onKeyDown = function ( e ) {
8152 if (
8153 !this.isDisabled() &&
8154 (
8155 e.which === OO.ui.Keys.ENTER ||
8156 (
8157 e.which === OO.ui.Keys.SPACE &&
8158 // Avoid conflicts with type-to-search, see SelectWidget#onKeyPress.
8159 // Space only closes the menu is the user is not typing to search.
8160 this.menu.keyPressBuffer === ''
8161 ) ||
8162 (
8163 !this.menu.isVisible() &&
8164 (
8165 e.which === OO.ui.Keys.UP ||
8166 e.which === OO.ui.Keys.DOWN
8167 )
8168 )
8169 )
8170 ) {
8171 this.menu.toggle();
8172 return false;
8173 }
8174 };
8175
8176 /**
8177 * RadioOptionWidget is an option widget that looks like a radio button.
8178 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
8179 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8180 *
8181 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8182 *
8183 * @class
8184 * @extends OO.ui.OptionWidget
8185 *
8186 * @constructor
8187 * @param {Object} [config] Configuration options
8188 */
8189 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
8190 // Configuration initialization
8191 config = config || {};
8192
8193 // Properties (must be done before parent constructor which calls #setDisabled)
8194 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
8195
8196 // Parent constructor
8197 OO.ui.RadioOptionWidget.parent.call( this, config );
8198
8199 // Initialization
8200 // Remove implicit role, we're handling it ourselves
8201 this.radio.$input.attr( 'role', 'presentation' );
8202 this.$element
8203 .addClass( 'oo-ui-radioOptionWidget' )
8204 .attr( 'role', 'radio' )
8205 .attr( 'aria-checked', 'false' )
8206 .removeAttr( 'aria-selected' )
8207 .prepend( this.radio.$element );
8208 };
8209
8210 /* Setup */
8211
8212 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
8213
8214 /* Static Properties */
8215
8216 /**
8217 * @static
8218 * @inheritdoc
8219 */
8220 OO.ui.RadioOptionWidget.static.highlightable = false;
8221
8222 /**
8223 * @static
8224 * @inheritdoc
8225 */
8226 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
8227
8228 /**
8229 * @static
8230 * @inheritdoc
8231 */
8232 OO.ui.RadioOptionWidget.static.pressable = false;
8233
8234 /**
8235 * @static
8236 * @inheritdoc
8237 */
8238 OO.ui.RadioOptionWidget.static.tagName = 'label';
8239
8240 /* Methods */
8241
8242 /**
8243 * @inheritdoc
8244 */
8245 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
8246 OO.ui.RadioOptionWidget.parent.prototype.setSelected.call( this, state );
8247
8248 this.radio.setSelected( state );
8249 this.$element
8250 .attr( 'aria-checked', state.toString() )
8251 .removeAttr( 'aria-selected' );
8252
8253 return this;
8254 };
8255
8256 /**
8257 * @inheritdoc
8258 */
8259 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
8260 OO.ui.RadioOptionWidget.parent.prototype.setDisabled.call( this, disabled );
8261
8262 this.radio.setDisabled( this.isDisabled() );
8263
8264 return this;
8265 };
8266
8267 /**
8268 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
8269 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
8270 * an interface for adding, removing and selecting options.
8271 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8272 *
8273 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8274 * OO.ui.RadioSelectInputWidget instead.
8275 *
8276 * @example
8277 * // A RadioSelectWidget with RadioOptions.
8278 * var option1 = new OO.ui.RadioOptionWidget( {
8279 * data: 'a',
8280 * label: 'Selected radio option'
8281 * } ),
8282 * option2 = new OO.ui.RadioOptionWidget( {
8283 * data: 'b',
8284 * label: 'Unselected radio option'
8285 * } );
8286 * radioSelect = new OO.ui.RadioSelectWidget( {
8287 * items: [ option1, option2 ]
8288 * } );
8289 *
8290 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
8291 * radioSelect.selectItem( option1 );
8292 *
8293 * $( document.body ).append( radioSelect.$element );
8294 *
8295 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8296
8297 *
8298 * @class
8299 * @extends OO.ui.SelectWidget
8300 * @mixins OO.ui.mixin.TabIndexedElement
8301 *
8302 * @constructor
8303 * @param {Object} [config] Configuration options
8304 */
8305 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
8306 // Parent constructor
8307 OO.ui.RadioSelectWidget.parent.call( this, config );
8308
8309 // Mixin constructors
8310 OO.ui.mixin.TabIndexedElement.call( this, config );
8311
8312 // Events
8313 this.$element.on( {
8314 focus: this.bindDocumentKeyDownListener.bind( this ),
8315 blur: this.unbindDocumentKeyDownListener.bind( this )
8316 } );
8317
8318 // Initialization
8319 this.$element
8320 .addClass( 'oo-ui-radioSelectWidget' )
8321 .attr( 'role', 'radiogroup' );
8322 };
8323
8324 /* Setup */
8325
8326 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
8327 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.mixin.TabIndexedElement );
8328
8329 /**
8330 * MultioptionWidgets are special elements that can be selected and configured with data. The
8331 * data is often unique for each option, but it does not have to be. MultioptionWidgets are used
8332 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
8333 * and examples, please see the [OOUI documentation on MediaWiki][1].
8334 *
8335 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8336 *
8337 * @class
8338 * @extends OO.ui.Widget
8339 * @mixins OO.ui.mixin.ItemWidget
8340 * @mixins OO.ui.mixin.LabelElement
8341 * @mixins OO.ui.mixin.TitledElement
8342 *
8343 * @constructor
8344 * @param {Object} [config] Configuration options
8345 * @cfg {boolean} [selected=false] Whether the option is initially selected
8346 */
8347 OO.ui.MultioptionWidget = function OoUiMultioptionWidget( config ) {
8348 // Configuration initialization
8349 config = config || {};
8350
8351 // Parent constructor
8352 OO.ui.MultioptionWidget.parent.call( this, config );
8353
8354 // Mixin constructors
8355 OO.ui.mixin.ItemWidget.call( this );
8356 OO.ui.mixin.LabelElement.call( this, config );
8357 OO.ui.mixin.TitledElement.call( this, config );
8358
8359 // Properties
8360 this.selected = null;
8361
8362 // Initialization
8363 this.$element
8364 .addClass( 'oo-ui-multioptionWidget' )
8365 .append( this.$label );
8366 this.setSelected( config.selected );
8367 };
8368
8369 /* Setup */
8370
8371 OO.inheritClass( OO.ui.MultioptionWidget, OO.ui.Widget );
8372 OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.ItemWidget );
8373 OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.LabelElement );
8374 OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.TitledElement );
8375
8376 /* Events */
8377
8378 /**
8379 * @event change
8380 *
8381 * A change event is emitted when the selected state of the option changes.
8382 *
8383 * @param {boolean} selected Whether the option is now selected
8384 */
8385
8386 /* Methods */
8387
8388 /**
8389 * Check if the option is selected.
8390 *
8391 * @return {boolean} Item is selected
8392 */
8393 OO.ui.MultioptionWidget.prototype.isSelected = function () {
8394 return this.selected;
8395 };
8396
8397 /**
8398 * Set the option’s selected state. In general, all modifications to the selection
8399 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
8400 * method instead of this method.
8401 *
8402 * @param {boolean} [state=false] Select option
8403 * @chainable
8404 * @return {OO.ui.Widget} The widget, for chaining
8405 */
8406 OO.ui.MultioptionWidget.prototype.setSelected = function ( state ) {
8407 state = !!state;
8408 if ( this.selected !== state ) {
8409 this.selected = state;
8410 this.emit( 'change', state );
8411 this.$element.toggleClass( 'oo-ui-multioptionWidget-selected', state );
8412 }
8413 return this;
8414 };
8415
8416 /**
8417 * MultiselectWidget allows selecting multiple options from a list.
8418 *
8419 * For more information about menus and options, please see the [OOUI documentation on MediaWiki][1].
8420 *
8421 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
8422 *
8423 * @class
8424 * @abstract
8425 * @extends OO.ui.Widget
8426 * @mixins OO.ui.mixin.GroupWidget
8427 * @mixins OO.ui.mixin.TitledElement
8428 *
8429 * @constructor
8430 * @param {Object} [config] Configuration options
8431 * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
8432 */
8433 OO.ui.MultiselectWidget = function OoUiMultiselectWidget( config ) {
8434 // Parent constructor
8435 OO.ui.MultiselectWidget.parent.call( this, config );
8436
8437 // Configuration initialization
8438 config = config || {};
8439
8440 // Mixin constructors
8441 OO.ui.mixin.GroupWidget.call( this, config );
8442 OO.ui.mixin.TitledElement.call( this, config );
8443
8444 // Events
8445 this.aggregate( { change: 'select' } );
8446 // This is mostly for compatibility with TagMultiselectWidget... normally, 'change' is emitted
8447 // by GroupElement only when items are added/removed
8448 this.connect( this, { select: [ 'emit', 'change' ] } );
8449
8450 // Initialization
8451 if ( config.items ) {
8452 this.addItems( config.items );
8453 }
8454 this.$group.addClass( 'oo-ui-multiselectWidget-group' );
8455 this.$element.addClass( 'oo-ui-multiselectWidget' )
8456 .append( this.$group );
8457 };
8458
8459 /* Setup */
8460
8461 OO.inheritClass( OO.ui.MultiselectWidget, OO.ui.Widget );
8462 OO.mixinClass( OO.ui.MultiselectWidget, OO.ui.mixin.GroupWidget );
8463 OO.mixinClass( OO.ui.MultiselectWidget, OO.ui.mixin.TitledElement );
8464
8465 /* Events */
8466
8467 /**
8468 * @event change
8469 *
8470 * A change event is emitted when the set of items changes, or an item is selected or deselected.
8471 */
8472
8473 /**
8474 * @event select
8475 *
8476 * A select event is emitted when an item is selected or deselected.
8477 */
8478
8479 /* Methods */
8480
8481 /**
8482 * Find options that are selected.
8483 *
8484 * @return {OO.ui.MultioptionWidget[]} Selected options
8485 */
8486 OO.ui.MultiselectWidget.prototype.findSelectedItems = function () {
8487 return this.items.filter( function ( item ) {
8488 return item.isSelected();
8489 } );
8490 };
8491
8492 /**
8493 * Find the data of options that are selected.
8494 *
8495 * @return {Object[]|string[]} Values of selected options
8496 */
8497 OO.ui.MultiselectWidget.prototype.findSelectedItemsData = function () {
8498 return this.findSelectedItems().map( function ( item ) {
8499 return item.data;
8500 } );
8501 };
8502
8503 /**
8504 * Select options by reference. Options not mentioned in the `items` array will be deselected.
8505 *
8506 * @param {OO.ui.MultioptionWidget[]} items Items to select
8507 * @chainable
8508 * @return {OO.ui.Widget} The widget, for chaining
8509 */
8510 OO.ui.MultiselectWidget.prototype.selectItems = function ( items ) {
8511 this.items.forEach( function ( item ) {
8512 var selected = items.indexOf( item ) !== -1;
8513 item.setSelected( selected );
8514 } );
8515 return this;
8516 };
8517
8518 /**
8519 * Select items by their data. Options not mentioned in the `datas` array will be deselected.
8520 *
8521 * @param {Object[]|string[]} datas Values of items to select
8522 * @chainable
8523 * @return {OO.ui.Widget} The widget, for chaining
8524 */
8525 OO.ui.MultiselectWidget.prototype.selectItemsByData = function ( datas ) {
8526 var items,
8527 widget = this;
8528 items = datas.map( function ( data ) {
8529 return widget.findItemFromData( data );
8530 } );
8531 this.selectItems( items );
8532 return this;
8533 };
8534
8535 /**
8536 * CheckboxMultioptionWidget is an option widget that looks like a checkbox.
8537 * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
8538 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8539 *
8540 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8541 *
8542 * @class
8543 * @extends OO.ui.MultioptionWidget
8544 *
8545 * @constructor
8546 * @param {Object} [config] Configuration options
8547 */
8548 OO.ui.CheckboxMultioptionWidget = function OoUiCheckboxMultioptionWidget( config ) {
8549 // Configuration initialization
8550 config = config || {};
8551
8552 // Properties (must be done before parent constructor which calls #setDisabled)
8553 this.checkbox = new OO.ui.CheckboxInputWidget();
8554
8555 // Parent constructor
8556 OO.ui.CheckboxMultioptionWidget.parent.call( this, config );
8557
8558 // Events
8559 this.checkbox.on( 'change', this.onCheckboxChange.bind( this ) );
8560 this.$element.on( 'keydown', this.onKeyDown.bind( this ) );
8561
8562 // Initialization
8563 this.$element
8564 .addClass( 'oo-ui-checkboxMultioptionWidget' )
8565 .prepend( this.checkbox.$element );
8566 };
8567
8568 /* Setup */
8569
8570 OO.inheritClass( OO.ui.CheckboxMultioptionWidget, OO.ui.MultioptionWidget );
8571
8572 /* Static Properties */
8573
8574 /**
8575 * @static
8576 * @inheritdoc
8577 */
8578 OO.ui.CheckboxMultioptionWidget.static.tagName = 'label';
8579
8580 /* Methods */
8581
8582 /**
8583 * Handle checkbox selected state change.
8584 *
8585 * @private
8586 */
8587 OO.ui.CheckboxMultioptionWidget.prototype.onCheckboxChange = function () {
8588 this.setSelected( this.checkbox.isSelected() );
8589 };
8590
8591 /**
8592 * @inheritdoc
8593 */
8594 OO.ui.CheckboxMultioptionWidget.prototype.setSelected = function ( state ) {
8595 OO.ui.CheckboxMultioptionWidget.parent.prototype.setSelected.call( this, state );
8596 this.checkbox.setSelected( state );
8597 return this;
8598 };
8599
8600 /**
8601 * @inheritdoc
8602 */
8603 OO.ui.CheckboxMultioptionWidget.prototype.setDisabled = function ( disabled ) {
8604 OO.ui.CheckboxMultioptionWidget.parent.prototype.setDisabled.call( this, disabled );
8605 this.checkbox.setDisabled( this.isDisabled() );
8606 return this;
8607 };
8608
8609 /**
8610 * Focus the widget.
8611 */
8612 OO.ui.CheckboxMultioptionWidget.prototype.focus = function () {
8613 this.checkbox.focus();
8614 };
8615
8616 /**
8617 * Handle key down events.
8618 *
8619 * @protected
8620 * @param {jQuery.Event} e
8621 */
8622 OO.ui.CheckboxMultioptionWidget.prototype.onKeyDown = function ( e ) {
8623 var
8624 element = this.getElementGroup(),
8625 nextItem;
8626
8627 if ( e.keyCode === OO.ui.Keys.LEFT || e.keyCode === OO.ui.Keys.UP ) {
8628 nextItem = element.getRelativeFocusableItem( this, -1 );
8629 } else if ( e.keyCode === OO.ui.Keys.RIGHT || e.keyCode === OO.ui.Keys.DOWN ) {
8630 nextItem = element.getRelativeFocusableItem( this, 1 );
8631 }
8632
8633 if ( nextItem ) {
8634 e.preventDefault();
8635 nextItem.focus();
8636 }
8637 };
8638
8639 /**
8640 * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
8641 * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
8642 * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
8643 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8644 *
8645 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8646 * OO.ui.CheckboxMultiselectInputWidget instead.
8647 *
8648 * @example
8649 * // A CheckboxMultiselectWidget with CheckboxMultioptions.
8650 * var option1 = new OO.ui.CheckboxMultioptionWidget( {
8651 * data: 'a',
8652 * selected: true,
8653 * label: 'Selected checkbox'
8654 * } ),
8655 * option2 = new OO.ui.CheckboxMultioptionWidget( {
8656 * data: 'b',
8657 * label: 'Unselected checkbox'
8658 * } ),
8659 * multiselect = new OO.ui.CheckboxMultiselectWidget( {
8660 * items: [ option1, option2 ]
8661 * } );
8662 * $( document.body ).append( multiselect.$element );
8663 *
8664 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8665 *
8666 * @class
8667 * @extends OO.ui.MultiselectWidget
8668 *
8669 * @constructor
8670 * @param {Object} [config] Configuration options
8671 */
8672 OO.ui.CheckboxMultiselectWidget = function OoUiCheckboxMultiselectWidget( config ) {
8673 // Parent constructor
8674 OO.ui.CheckboxMultiselectWidget.parent.call( this, config );
8675
8676 // Properties
8677 this.$lastClicked = null;
8678
8679 // Events
8680 this.$group.on( 'click', this.onClick.bind( this ) );
8681
8682 // Initialization
8683 this.$element
8684 .addClass( 'oo-ui-checkboxMultiselectWidget' );
8685 };
8686
8687 /* Setup */
8688
8689 OO.inheritClass( OO.ui.CheckboxMultiselectWidget, OO.ui.MultiselectWidget );
8690
8691 /* Methods */
8692
8693 /**
8694 * Get an option by its position relative to the specified item (or to the start of the option array,
8695 * if item is `null`). The direction in which to search through the option array is specified with a
8696 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
8697 * `null` if there are no options in the array.
8698 *
8699 * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
8700 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
8701 * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items in the select
8702 */
8703 OO.ui.CheckboxMultiselectWidget.prototype.getRelativeFocusableItem = function ( item, direction ) {
8704 var currentIndex, nextIndex, i,
8705 increase = direction > 0 ? 1 : -1,
8706 len = this.items.length;
8707
8708 if ( item ) {
8709 currentIndex = this.items.indexOf( item );
8710 nextIndex = ( currentIndex + increase + len ) % len;
8711 } else {
8712 // If no item is selected and moving forward, start at the beginning.
8713 // If moving backward, start at the end.
8714 nextIndex = direction > 0 ? 0 : len - 1;
8715 }
8716
8717 for ( i = 0; i < len; i++ ) {
8718 item = this.items[ nextIndex ];
8719 if ( item && !item.isDisabled() ) {
8720 return item;
8721 }
8722 nextIndex = ( nextIndex + increase + len ) % len;
8723 }
8724 return null;
8725 };
8726
8727 /**
8728 * Handle click events on checkboxes.
8729 *
8730 * @param {jQuery.Event} e
8731 */
8732 OO.ui.CheckboxMultiselectWidget.prototype.onClick = function ( e ) {
8733 var $options, lastClickedIndex, nowClickedIndex, i, direction, wasSelected, items,
8734 $lastClicked = this.$lastClicked,
8735 $nowClicked = $( e.target ).closest( '.oo-ui-checkboxMultioptionWidget' )
8736 .not( '.oo-ui-widget-disabled' );
8737
8738 // Allow selecting multiple options at once by Shift-clicking them
8739 if ( $lastClicked && $nowClicked.length && e.shiftKey ) {
8740 $options = this.$group.find( '.oo-ui-checkboxMultioptionWidget' );
8741 lastClickedIndex = $options.index( $lastClicked );
8742 nowClickedIndex = $options.index( $nowClicked );
8743 // If it's the same item, either the user is being silly, or it's a fake event generated by the
8744 // browser. In either case we don't need custom handling.
8745 if ( nowClickedIndex !== lastClickedIndex ) {
8746 items = this.items;
8747 wasSelected = items[ nowClickedIndex ].isSelected();
8748 direction = nowClickedIndex > lastClickedIndex ? 1 : -1;
8749
8750 // This depends on the DOM order of the items and the order of the .items array being the same.
8751 for ( i = lastClickedIndex; i !== nowClickedIndex; i += direction ) {
8752 if ( !items[ i ].isDisabled() ) {
8753 items[ i ].setSelected( !wasSelected );
8754 }
8755 }
8756 // For the now-clicked element, use immediate timeout to allow the browser to do its own
8757 // handling first, then set our value. The order in which events happen is different for
8758 // clicks on the <input> and on the <label> and there are additional fake clicks fired for
8759 // non-click actions that change the checkboxes.
8760 e.preventDefault();
8761 setTimeout( function () {
8762 if ( !items[ nowClickedIndex ].isDisabled() ) {
8763 items[ nowClickedIndex ].setSelected( !wasSelected );
8764 }
8765 } );
8766 }
8767 }
8768
8769 if ( $nowClicked.length ) {
8770 this.$lastClicked = $nowClicked;
8771 }
8772 };
8773
8774 /**
8775 * Focus the widget
8776 *
8777 * @chainable
8778 * @return {OO.ui.Widget} The widget, for chaining
8779 */
8780 OO.ui.CheckboxMultiselectWidget.prototype.focus = function () {
8781 var item;
8782 if ( !this.isDisabled() ) {
8783 item = this.getRelativeFocusableItem( null, 1 );
8784 if ( item ) {
8785 item.focus();
8786 }
8787 }
8788 return this;
8789 };
8790
8791 /**
8792 * @inheritdoc
8793 */
8794 OO.ui.CheckboxMultiselectWidget.prototype.simulateLabelClick = function () {
8795 this.focus();
8796 };
8797
8798 /**
8799 * Progress bars visually display the status of an operation, such as a download,
8800 * and can be either determinate or indeterminate:
8801 *
8802 * - **determinate** process bars show the percent of an operation that is complete.
8803 *
8804 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
8805 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
8806 * not use percentages.
8807 *
8808 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
8809 *
8810 * @example
8811 * // Examples of determinate and indeterminate progress bars.
8812 * var progressBar1 = new OO.ui.ProgressBarWidget( {
8813 * progress: 33
8814 * } );
8815 * var progressBar2 = new OO.ui.ProgressBarWidget();
8816 *
8817 * // Create a FieldsetLayout to layout progress bars.
8818 * var fieldset = new OO.ui.FieldsetLayout;
8819 * fieldset.addItems( [
8820 * new OO.ui.FieldLayout( progressBar1, {
8821 * label: 'Determinate',
8822 * align: 'top'
8823 * } ),
8824 * new OO.ui.FieldLayout( progressBar2, {
8825 * label: 'Indeterminate',
8826 * align: 'top'
8827 * } )
8828 * ] );
8829 * $( document.body ).append( fieldset.$element );
8830 *
8831 * @class
8832 * @extends OO.ui.Widget
8833 *
8834 * @constructor
8835 * @param {Object} [config] Configuration options
8836 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
8837 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
8838 * By default, the progress bar is indeterminate.
8839 */
8840 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
8841 // Configuration initialization
8842 config = config || {};
8843
8844 // Parent constructor
8845 OO.ui.ProgressBarWidget.parent.call( this, config );
8846
8847 // Properties
8848 this.$bar = $( '<div>' );
8849 this.progress = null;
8850
8851 // Initialization
8852 this.setProgress( config.progress !== undefined ? config.progress : false );
8853 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
8854 this.$element
8855 .attr( {
8856 role: 'progressbar',
8857 'aria-valuemin': 0,
8858 'aria-valuemax': 100
8859 } )
8860 .addClass( 'oo-ui-progressBarWidget' )
8861 .append( this.$bar );
8862 };
8863
8864 /* Setup */
8865
8866 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
8867
8868 /* Static Properties */
8869
8870 /**
8871 * @static
8872 * @inheritdoc
8873 */
8874 OO.ui.ProgressBarWidget.static.tagName = 'div';
8875
8876 /* Methods */
8877
8878 /**
8879 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
8880 *
8881 * @return {number|boolean} Progress percent
8882 */
8883 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
8884 return this.progress;
8885 };
8886
8887 /**
8888 * Set the percent of the process completed or `false` for an indeterminate process.
8889 *
8890 * @param {number|boolean} progress Progress percent or `false` for indeterminate
8891 */
8892 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
8893 this.progress = progress;
8894
8895 if ( progress !== false ) {
8896 this.$bar.css( 'width', this.progress + '%' );
8897 this.$element.attr( 'aria-valuenow', this.progress );
8898 } else {
8899 this.$bar.css( 'width', '' );
8900 this.$element.removeAttr( 'aria-valuenow' );
8901 }
8902 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress === false );
8903 };
8904
8905 /**
8906 * InputWidget is the base class for all input widgets, which
8907 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
8908 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
8909 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
8910 *
8911 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
8912 *
8913 * @abstract
8914 * @class
8915 * @extends OO.ui.Widget
8916 * @mixins OO.ui.mixin.FlaggedElement
8917 * @mixins OO.ui.mixin.TabIndexedElement
8918 * @mixins OO.ui.mixin.TitledElement
8919 * @mixins OO.ui.mixin.AccessKeyedElement
8920 *
8921 * @constructor
8922 * @param {Object} [config] Configuration options
8923 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
8924 * @cfg {string} [value=''] The value of the input.
8925 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
8926 * @cfg {string} [inputId] The value of the input’s HTML `id` attribute.
8927 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
8928 * before it is accepted.
8929 */
8930 OO.ui.InputWidget = function OoUiInputWidget( config ) {
8931 // Configuration initialization
8932 config = config || {};
8933
8934 // Parent constructor
8935 OO.ui.InputWidget.parent.call( this, config );
8936
8937 // Properties
8938 // See #reusePreInfuseDOM about config.$input
8939 this.$input = config.$input || this.getInputElement( config );
8940 this.value = '';
8941 this.inputFilter = config.inputFilter;
8942
8943 // Mixin constructors
8944 OO.ui.mixin.FlaggedElement.call( this, config );
8945 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
8946 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
8947 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$input } ) );
8948
8949 // Events
8950 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
8951
8952 // Initialization
8953 this.$input
8954 .addClass( 'oo-ui-inputWidget-input' )
8955 .attr( 'name', config.name )
8956 .prop( 'disabled', this.isDisabled() );
8957 this.$element
8958 .addClass( 'oo-ui-inputWidget' )
8959 .append( this.$input );
8960 this.setValue( config.value );
8961 if ( config.dir ) {
8962 this.setDir( config.dir );
8963 }
8964 if ( config.inputId !== undefined ) {
8965 this.setInputId( config.inputId );
8966 }
8967 };
8968
8969 /* Setup */
8970
8971 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
8972 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.FlaggedElement );
8973 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TabIndexedElement );
8974 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TitledElement );
8975 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.AccessKeyedElement );
8976
8977 /* Static Methods */
8978
8979 /**
8980 * @inheritdoc
8981 */
8982 OO.ui.InputWidget.static.reusePreInfuseDOM = function ( node, config ) {
8983 config = OO.ui.InputWidget.parent.static.reusePreInfuseDOM( node, config );
8984 // Reusing `$input` lets browsers preserve inputted values across page reloads, see T114134.
8985 config.$input = $( node ).find( '.oo-ui-inputWidget-input' );
8986 return config;
8987 };
8988
8989 /**
8990 * @inheritdoc
8991 */
8992 OO.ui.InputWidget.static.gatherPreInfuseState = function ( node, config ) {
8993 var state = OO.ui.InputWidget.parent.static.gatherPreInfuseState( node, config );
8994 if ( config.$input && config.$input.length ) {
8995 state.value = config.$input.val();
8996 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
8997 state.focus = config.$input.is( ':focus' );
8998 }
8999 return state;
9000 };
9001
9002 /* Events */
9003
9004 /**
9005 * @event change
9006 *
9007 * A change event is emitted when the value of the input changes.
9008 *
9009 * @param {string} value
9010 */
9011
9012 /* Methods */
9013
9014 /**
9015 * Get input element.
9016 *
9017 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
9018 * different circumstances. The element must have a `value` property (like form elements).
9019 *
9020 * @protected
9021 * @param {Object} config Configuration options
9022 * @return {jQuery} Input element
9023 */
9024 OO.ui.InputWidget.prototype.getInputElement = function () {
9025 return $( '<input>' );
9026 };
9027
9028 /**
9029 * Handle potentially value-changing events.
9030 *
9031 * @private
9032 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
9033 */
9034 OO.ui.InputWidget.prototype.onEdit = function () {
9035 var widget = this;
9036 if ( !this.isDisabled() ) {
9037 // Allow the stack to clear so the value will be updated
9038 setTimeout( function () {
9039 widget.setValue( widget.$input.val() );
9040 } );
9041 }
9042 };
9043
9044 /**
9045 * Get the value of the input.
9046 *
9047 * @return {string} Input value
9048 */
9049 OO.ui.InputWidget.prototype.getValue = function () {
9050 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
9051 // it, and we won't know unless they're kind enough to trigger a 'change' event.
9052 var value = this.$input.val();
9053 if ( this.value !== value ) {
9054 this.setValue( value );
9055 }
9056 return this.value;
9057 };
9058
9059 /**
9060 * Set the directionality of the input.
9061 *
9062 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
9063 * @chainable
9064 * @return {OO.ui.Widget} The widget, for chaining
9065 */
9066 OO.ui.InputWidget.prototype.setDir = function ( dir ) {
9067 this.$input.prop( 'dir', dir );
9068 return this;
9069 };
9070
9071 /**
9072 * Set the value of the input.
9073 *
9074 * @param {string} value New value
9075 * @fires change
9076 * @chainable
9077 * @return {OO.ui.Widget} The widget, for chaining
9078 */
9079 OO.ui.InputWidget.prototype.setValue = function ( value ) {
9080 value = this.cleanUpValue( value );
9081 // Update the DOM if it has changed. Note that with cleanUpValue, it
9082 // is possible for the DOM value to change without this.value changing.
9083 if ( this.$input.val() !== value ) {
9084 this.$input.val( value );
9085 }
9086 if ( this.value !== value ) {
9087 this.value = value;
9088 this.emit( 'change', this.value );
9089 }
9090 // The first time that the value is set (probably while constructing the widget),
9091 // remember it in defaultValue. This property can be later used to check whether
9092 // the value of the input has been changed since it was created.
9093 if ( this.defaultValue === undefined ) {
9094 this.defaultValue = this.value;
9095 this.$input[ 0 ].defaultValue = this.defaultValue;
9096 }
9097 return this;
9098 };
9099
9100 /**
9101 * Clean up incoming value.
9102 *
9103 * Ensures value is a string, and converts undefined and null to empty string.
9104 *
9105 * @private
9106 * @param {string} value Original value
9107 * @return {string} Cleaned up value
9108 */
9109 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
9110 if ( value === undefined || value === null ) {
9111 return '';
9112 } else if ( this.inputFilter ) {
9113 return this.inputFilter( String( value ) );
9114 } else {
9115 return String( value );
9116 }
9117 };
9118
9119 /**
9120 * @inheritdoc
9121 */
9122 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
9123 OO.ui.InputWidget.parent.prototype.setDisabled.call( this, state );
9124 if ( this.$input ) {
9125 this.$input.prop( 'disabled', this.isDisabled() );
9126 }
9127 return this;
9128 };
9129
9130 /**
9131 * Set the 'id' attribute of the `<input>` element.
9132 *
9133 * @param {string} id
9134 * @chainable
9135 * @return {OO.ui.Widget} The widget, for chaining
9136 */
9137 OO.ui.InputWidget.prototype.setInputId = function ( id ) {
9138 this.$input.attr( 'id', id );
9139 return this;
9140 };
9141
9142 /**
9143 * @inheritdoc
9144 */
9145 OO.ui.InputWidget.prototype.restorePreInfuseState = function ( state ) {
9146 OO.ui.InputWidget.parent.prototype.restorePreInfuseState.call( this, state );
9147 if ( state.value !== undefined && state.value !== this.getValue() ) {
9148 this.setValue( state.value );
9149 }
9150 if ( state.focus ) {
9151 this.focus();
9152 }
9153 };
9154
9155 /**
9156 * Data widget intended for creating `<input type="hidden">` inputs.
9157 *
9158 * @class
9159 * @extends OO.ui.Widget
9160 *
9161 * @constructor
9162 * @param {Object} [config] Configuration options
9163 * @cfg {string} [value=''] The value of the input.
9164 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
9165 */
9166 OO.ui.HiddenInputWidget = function OoUiHiddenInputWidget( config ) {
9167 // Configuration initialization
9168 config = $.extend( { value: '', name: '' }, config );
9169
9170 // Parent constructor
9171 OO.ui.HiddenInputWidget.parent.call( this, config );
9172
9173 // Initialization
9174 this.$element.attr( {
9175 type: 'hidden',
9176 value: config.value,
9177 name: config.name
9178 } );
9179 this.$element.removeAttr( 'aria-disabled' );
9180 };
9181
9182 /* Setup */
9183
9184 OO.inheritClass( OO.ui.HiddenInputWidget, OO.ui.Widget );
9185
9186 /* Static Properties */
9187
9188 /**
9189 * @static
9190 * @inheritdoc
9191 */
9192 OO.ui.HiddenInputWidget.static.tagName = 'input';
9193
9194 /**
9195 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
9196 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
9197 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
9198 * HTML `<button>` (the default) or an HTML `<input>` tags. See the
9199 * [OOUI documentation on MediaWiki] [1] for more information.
9200 *
9201 * @example
9202 * // A ButtonInputWidget rendered as an HTML button, the default.
9203 * var button = new OO.ui.ButtonInputWidget( {
9204 * label: 'Input button',
9205 * icon: 'check',
9206 * value: 'check'
9207 * } );
9208 * $( document.body ).append( button.$element );
9209 *
9210 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#Button_inputs
9211 *
9212 * @class
9213 * @extends OO.ui.InputWidget
9214 * @mixins OO.ui.mixin.ButtonElement
9215 * @mixins OO.ui.mixin.IconElement
9216 * @mixins OO.ui.mixin.IndicatorElement
9217 * @mixins OO.ui.mixin.LabelElement
9218 *
9219 * @constructor
9220 * @param {Object} [config] Configuration options
9221 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
9222 * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
9223 * Widgets configured to be an `<input>` do not support {@link #icon icons} and {@link #indicator indicators},
9224 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
9225 * be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
9226 */
9227 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
9228 // Configuration initialization
9229 config = $.extend( { type: 'button', useInputTag: false }, config );
9230
9231 // See InputWidget#reusePreInfuseDOM about config.$input
9232 if ( config.$input ) {
9233 config.$input.empty();
9234 }
9235
9236 // Properties (must be set before parent constructor, which calls #setValue)
9237 this.useInputTag = config.useInputTag;
9238
9239 // Parent constructor
9240 OO.ui.ButtonInputWidget.parent.call( this, config );
9241
9242 // Mixin constructors
9243 OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
9244 OO.ui.mixin.IconElement.call( this, config );
9245 OO.ui.mixin.IndicatorElement.call( this, config );
9246 OO.ui.mixin.LabelElement.call( this, config );
9247
9248 // Initialization
9249 if ( !config.useInputTag ) {
9250 this.$input.append( this.$icon, this.$label, this.$indicator );
9251 }
9252 this.$element.addClass( 'oo-ui-buttonInputWidget' );
9253 };
9254
9255 /* Setup */
9256
9257 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
9258 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.ButtonElement );
9259 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IconElement );
9260 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IndicatorElement );
9261 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.LabelElement );
9262
9263 /* Static Properties */
9264
9265 /**
9266 * @static
9267 * @inheritdoc
9268 */
9269 OO.ui.ButtonInputWidget.static.tagName = 'span';
9270
9271 /* Methods */
9272
9273 /**
9274 * @inheritdoc
9275 * @protected
9276 */
9277 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
9278 var type;
9279 type = [ 'button', 'submit', 'reset' ].indexOf( config.type ) !== -1 ? config.type : 'button';
9280 return $( '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + type + '">' );
9281 };
9282
9283 /**
9284 * Set label value.
9285 *
9286 * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
9287 *
9288 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
9289 * text, or `null` for no label
9290 * @chainable
9291 * @return {OO.ui.Widget} The widget, for chaining
9292 */
9293 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
9294 if ( typeof label === 'function' ) {
9295 label = OO.ui.resolveMsg( label );
9296 }
9297
9298 if ( this.useInputTag ) {
9299 // Discard non-plaintext labels
9300 if ( typeof label !== 'string' ) {
9301 label = '';
9302 }
9303
9304 this.$input.val( label );
9305 }
9306
9307 return OO.ui.mixin.LabelElement.prototype.setLabel.call( this, label );
9308 };
9309
9310 /**
9311 * Set the value of the input.
9312 *
9313 * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
9314 * they do not support {@link #value values}.
9315 *
9316 * @param {string} value New value
9317 * @chainable
9318 * @return {OO.ui.Widget} The widget, for chaining
9319 */
9320 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
9321 if ( !this.useInputTag ) {
9322 OO.ui.ButtonInputWidget.parent.prototype.setValue.call( this, value );
9323 }
9324 return this;
9325 };
9326
9327 /**
9328 * @inheritdoc
9329 */
9330 OO.ui.ButtonInputWidget.prototype.getInputId = function () {
9331 // Disable generating `<label>` elements for buttons. One would very rarely need additional label
9332 // for a button, and it's already a big clickable target, and it causes unexpected rendering.
9333 return null;
9334 };
9335
9336 /**
9337 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
9338 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
9339 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
9340 * alignment. For more information, please see the [OOUI documentation on MediaWiki][1].
9341 *
9342 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9343 *
9344 * @example
9345 * // An example of selected, unselected, and disabled checkbox inputs.
9346 * var checkbox1 = new OO.ui.CheckboxInputWidget( {
9347 * value: 'a',
9348 * selected: true
9349 * } ),
9350 * checkbox2 = new OO.ui.CheckboxInputWidget( {
9351 * value: 'b'
9352 * } ),
9353 * checkbox3 = new OO.ui.CheckboxInputWidget( {
9354 * value:'c',
9355 * disabled: true
9356 * } ),
9357 * // Create a fieldset layout with fields for each checkbox.
9358 * fieldset = new OO.ui.FieldsetLayout( {
9359 * label: 'Checkboxes'
9360 * } );
9361 * fieldset.addItems( [
9362 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
9363 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
9364 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
9365 * ] );
9366 * $( document.body ).append( fieldset.$element );
9367 *
9368 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9369 *
9370 * @class
9371 * @extends OO.ui.InputWidget
9372 *
9373 * @constructor
9374 * @param {Object} [config] Configuration options
9375 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
9376 */
9377 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
9378 // Configuration initialization
9379 config = config || {};
9380
9381 // Parent constructor
9382 OO.ui.CheckboxInputWidget.parent.call( this, config );
9383
9384 // Properties
9385 this.checkIcon = new OO.ui.IconWidget( {
9386 icon: 'check',
9387 classes: [ 'oo-ui-checkboxInputWidget-checkIcon' ]
9388 } );
9389
9390 // Initialization
9391 this.$element
9392 .addClass( 'oo-ui-checkboxInputWidget' )
9393 // Required for pretty styling in WikimediaUI theme
9394 .append( this.checkIcon.$element );
9395 this.setSelected( config.selected !== undefined ? config.selected : false );
9396 };
9397
9398 /* Setup */
9399
9400 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
9401
9402 /* Static Properties */
9403
9404 /**
9405 * @static
9406 * @inheritdoc
9407 */
9408 OO.ui.CheckboxInputWidget.static.tagName = 'span';
9409
9410 /* Static Methods */
9411
9412 /**
9413 * @inheritdoc
9414 */
9415 OO.ui.CheckboxInputWidget.static.gatherPreInfuseState = function ( node, config ) {
9416 var state = OO.ui.CheckboxInputWidget.parent.static.gatherPreInfuseState( node, config );
9417 state.checked = config.$input.prop( 'checked' );
9418 return state;
9419 };
9420
9421 /* Methods */
9422
9423 /**
9424 * @inheritdoc
9425 * @protected
9426 */
9427 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
9428 return $( '<input>' ).attr( 'type', 'checkbox' );
9429 };
9430
9431 /**
9432 * @inheritdoc
9433 */
9434 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
9435 var widget = this;
9436 if ( !this.isDisabled() ) {
9437 // Allow the stack to clear so the value will be updated
9438 setTimeout( function () {
9439 widget.setSelected( widget.$input.prop( 'checked' ) );
9440 } );
9441 }
9442 };
9443
9444 /**
9445 * Set selection state of this checkbox.
9446 *
9447 * @param {boolean} state `true` for selected
9448 * @chainable
9449 * @return {OO.ui.Widget} The widget, for chaining
9450 */
9451 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
9452 state = !!state;
9453 if ( this.selected !== state ) {
9454 this.selected = state;
9455 this.$input.prop( 'checked', this.selected );
9456 this.emit( 'change', this.selected );
9457 }
9458 // The first time that the selection state is set (probably while constructing the widget),
9459 // remember it in defaultSelected. This property can be later used to check whether
9460 // the selection state of the input has been changed since it was created.
9461 if ( this.defaultSelected === undefined ) {
9462 this.defaultSelected = this.selected;
9463 this.$input[ 0 ].defaultChecked = this.defaultSelected;
9464 }
9465 return this;
9466 };
9467
9468 /**
9469 * Check if this checkbox is selected.
9470 *
9471 * @return {boolean} Checkbox is selected
9472 */
9473 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
9474 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
9475 // it, and we won't know unless they're kind enough to trigger a 'change' event.
9476 var selected = this.$input.prop( 'checked' );
9477 if ( this.selected !== selected ) {
9478 this.setSelected( selected );
9479 }
9480 return this.selected;
9481 };
9482
9483 /**
9484 * @inheritdoc
9485 */
9486 OO.ui.CheckboxInputWidget.prototype.simulateLabelClick = function () {
9487 if ( !this.isDisabled() ) {
9488 this.$handle.trigger( 'click' );
9489 }
9490 this.focus();
9491 };
9492
9493 /**
9494 * @inheritdoc
9495 */
9496 OO.ui.CheckboxInputWidget.prototype.restorePreInfuseState = function ( state ) {
9497 OO.ui.CheckboxInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
9498 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
9499 this.setSelected( state.checked );
9500 }
9501 };
9502
9503 /**
9504 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
9505 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
9506 * of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9507 * more information about input widgets.
9508 *
9509 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
9510 * are no options. If no `value` configuration option is provided, the first option is selected.
9511 * If you need a state representing no value (no option being selected), use a DropdownWidget.
9512 *
9513 * This and OO.ui.RadioSelectInputWidget support similar configuration options.
9514 *
9515 * @example
9516 * // A DropdownInputWidget with three options.
9517 * var dropdownInput = new OO.ui.DropdownInputWidget( {
9518 * options: [
9519 * { data: 'a', label: 'First' },
9520 * { data: 'b', label: 'Second', disabled: true },
9521 * { optgroup: 'Group label' },
9522 * { data: 'c', label: 'First sub-item)' }
9523 * ]
9524 * } );
9525 * $( document.body ).append( dropdownInput.$element );
9526 *
9527 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9528 *
9529 * @class
9530 * @extends OO.ui.InputWidget
9531 *
9532 * @constructor
9533 * @param {Object} [config] Configuration options
9534 * @cfg {Object[]} [options=[]] Array of menu options in the format described above.
9535 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
9536 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
9537 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
9538 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
9539 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
9540 */
9541 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
9542 // Configuration initialization
9543 config = config || {};
9544
9545 // Properties (must be done before parent constructor which calls #setDisabled)
9546 this.dropdownWidget = new OO.ui.DropdownWidget( $.extend(
9547 {
9548 $overlay: config.$overlay
9549 },
9550 config.dropdown
9551 ) );
9552 // Set up the options before parent constructor, which uses them to validate config.value.
9553 // Use this instead of setOptions() because this.$input is not set up yet.
9554 this.setOptionsData( config.options || [] );
9555
9556 // Parent constructor
9557 OO.ui.DropdownInputWidget.parent.call( this, config );
9558
9559 // Events
9560 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
9561
9562 // Initialization
9563 this.$element
9564 .addClass( 'oo-ui-dropdownInputWidget' )
9565 .append( this.dropdownWidget.$element );
9566 this.setTabIndexedElement( this.dropdownWidget.$tabIndexed );
9567 this.setTitledElement( this.dropdownWidget.$handle );
9568 };
9569
9570 /* Setup */
9571
9572 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
9573
9574 /* Methods */
9575
9576 /**
9577 * @inheritdoc
9578 * @protected
9579 */
9580 OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
9581 return $( '<select>' );
9582 };
9583
9584 /**
9585 * Handles menu select events.
9586 *
9587 * @private
9588 * @param {OO.ui.MenuOptionWidget|null} item Selected menu item
9589 */
9590 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
9591 this.setValue( item ? item.getData() : '' );
9592 };
9593
9594 /**
9595 * @inheritdoc
9596 */
9597 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
9598 var selected;
9599 value = this.cleanUpValue( value );
9600 // Only allow setting values that are actually present in the dropdown
9601 selected = this.dropdownWidget.getMenu().findItemFromData( value ) ||
9602 this.dropdownWidget.getMenu().findFirstSelectableItem();
9603 this.dropdownWidget.getMenu().selectItem( selected );
9604 value = selected ? selected.getData() : '';
9605 OO.ui.DropdownInputWidget.parent.prototype.setValue.call( this, value );
9606 if ( this.optionsDirty ) {
9607 // We reached this from the constructor or from #setOptions.
9608 // We have to update the <select> element.
9609 this.updateOptionsInterface();
9610 }
9611 return this;
9612 };
9613
9614 /**
9615 * @inheritdoc
9616 */
9617 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
9618 this.dropdownWidget.setDisabled( state );
9619 OO.ui.DropdownInputWidget.parent.prototype.setDisabled.call( this, state );
9620 return this;
9621 };
9622
9623 /**
9624 * Set the options available for this input.
9625 *
9626 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9627 * @chainable
9628 * @return {OO.ui.Widget} The widget, for chaining
9629 */
9630 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
9631 var value = this.getValue();
9632
9633 this.setOptionsData( options );
9634
9635 // Re-set the value to update the visible interface (DropdownWidget and <select>).
9636 // In case the previous value is no longer an available option, select the first valid one.
9637 this.setValue( value );
9638
9639 return this;
9640 };
9641
9642 /**
9643 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
9644 *
9645 * This method may be called before the parent constructor, so various properties may not be
9646 * initialized yet.
9647 *
9648 * @param {Object[]} options Array of menu options (see #constructor for details).
9649 * @private
9650 */
9651 OO.ui.DropdownInputWidget.prototype.setOptionsData = function ( options ) {
9652 var optionWidgets, optIndex, opt, previousOptgroup, optionWidget, optValue,
9653 widget = this;
9654
9655 this.optionsDirty = true;
9656
9657 // Go through all the supplied option configs and create either
9658 // MenuSectionOption or MenuOption widgets from each.
9659 optionWidgets = [];
9660 for ( optIndex = 0; optIndex < options.length; optIndex++ ) {
9661 opt = options[ optIndex ];
9662
9663 if ( opt.optgroup !== undefined ) {
9664 // Create a <optgroup> menu item.
9665 optionWidget = widget.createMenuSectionOptionWidget( opt.optgroup );
9666 previousOptgroup = optionWidget;
9667
9668 } else {
9669 // Create a normal <option> menu item.
9670 optValue = widget.cleanUpValue( opt.data );
9671 optionWidget = widget.createMenuOptionWidget(
9672 optValue,
9673 opt.label !== undefined ? opt.label : optValue
9674 );
9675 }
9676
9677 // Disable the menu option if it is itself disabled or if its parent optgroup is disabled.
9678 if ( opt.disabled !== undefined ||
9679 previousOptgroup instanceof OO.ui.MenuSectionOptionWidget && previousOptgroup.isDisabled() ) {
9680 optionWidget.setDisabled( true );
9681 }
9682
9683 optionWidgets.push( optionWidget );
9684 }
9685
9686 this.dropdownWidget.getMenu().clearItems().addItems( optionWidgets );
9687 };
9688
9689 /**
9690 * Create a menu option widget.
9691 *
9692 * @protected
9693 * @param {string} data Item data
9694 * @param {string} label Item label
9695 * @return {OO.ui.MenuOptionWidget} Option widget
9696 */
9697 OO.ui.DropdownInputWidget.prototype.createMenuOptionWidget = function ( data, label ) {
9698 return new OO.ui.MenuOptionWidget( {
9699 data: data,
9700 label: label
9701 } );
9702 };
9703
9704 /**
9705 * Create a menu section option widget.
9706 *
9707 * @protected
9708 * @param {string} label Section item label
9709 * @return {OO.ui.MenuSectionOptionWidget} Menu section option widget
9710 */
9711 OO.ui.DropdownInputWidget.prototype.createMenuSectionOptionWidget = function ( label ) {
9712 return new OO.ui.MenuSectionOptionWidget( {
9713 label: label
9714 } );
9715 };
9716
9717 /**
9718 * Update the user-visible interface to match the internal list of options and value.
9719 *
9720 * This method must only be called after the parent constructor.
9721 *
9722 * @private
9723 */
9724 OO.ui.DropdownInputWidget.prototype.updateOptionsInterface = function () {
9725 var
9726 $optionsContainer = this.$input,
9727 defaultValue = this.defaultValue,
9728 widget = this;
9729
9730 this.$input.empty();
9731
9732 this.dropdownWidget.getMenu().getItems().forEach( function ( optionWidget ) {
9733 var $optionNode;
9734
9735 if ( !( optionWidget instanceof OO.ui.MenuSectionOptionWidget ) ) {
9736 $optionNode = $( '<option>' )
9737 .attr( 'value', optionWidget.getData() )
9738 .text( optionWidget.getLabel() );
9739
9740 // Remember original selection state. This property can be later used to check whether
9741 // the selection state of the input has been changed since it was created.
9742 $optionNode[ 0 ].defaultSelected = ( optionWidget.getData() === defaultValue );
9743
9744 $optionsContainer.append( $optionNode );
9745 } else {
9746 $optionNode = $( '<optgroup>' )
9747 .attr( 'label', optionWidget.getLabel() );
9748 widget.$input.append( $optionNode );
9749 $optionsContainer = $optionNode;
9750 }
9751
9752 // Disable the option or optgroup if required.
9753 if ( optionWidget.isDisabled() ) {
9754 $optionNode.prop( 'disabled', true );
9755 }
9756 } );
9757
9758 this.optionsDirty = false;
9759 };
9760
9761 /**
9762 * @inheritdoc
9763 */
9764 OO.ui.DropdownInputWidget.prototype.focus = function () {
9765 this.dropdownWidget.focus();
9766 return this;
9767 };
9768
9769 /**
9770 * @inheritdoc
9771 */
9772 OO.ui.DropdownInputWidget.prototype.blur = function () {
9773 this.dropdownWidget.blur();
9774 return this;
9775 };
9776
9777 /**
9778 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
9779 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
9780 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
9781 * please see the [OOUI documentation on MediaWiki][1].
9782 *
9783 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9784 *
9785 * @example
9786 * // An example of selected, unselected, and disabled radio inputs
9787 * var radio1 = new OO.ui.RadioInputWidget( {
9788 * value: 'a',
9789 * selected: true
9790 * } );
9791 * var radio2 = new OO.ui.RadioInputWidget( {
9792 * value: 'b'
9793 * } );
9794 * var radio3 = new OO.ui.RadioInputWidget( {
9795 * value: 'c',
9796 * disabled: true
9797 * } );
9798 * // Create a fieldset layout with fields for each radio button.
9799 * var fieldset = new OO.ui.FieldsetLayout( {
9800 * label: 'Radio inputs'
9801 * } );
9802 * fieldset.addItems( [
9803 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
9804 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
9805 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
9806 * ] );
9807 * $( document.body ).append( fieldset.$element );
9808 *
9809 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9810 *
9811 * @class
9812 * @extends OO.ui.InputWidget
9813 *
9814 * @constructor
9815 * @param {Object} [config] Configuration options
9816 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
9817 */
9818 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
9819 // Configuration initialization
9820 config = config || {};
9821
9822 // Parent constructor
9823 OO.ui.RadioInputWidget.parent.call( this, config );
9824
9825 // Initialization
9826 this.$element
9827 .addClass( 'oo-ui-radioInputWidget' )
9828 // Required for pretty styling in WikimediaUI theme
9829 .append( $( '<span>' ) );
9830 this.setSelected( config.selected !== undefined ? config.selected : false );
9831 };
9832
9833 /* Setup */
9834
9835 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
9836
9837 /* Static Properties */
9838
9839 /**
9840 * @static
9841 * @inheritdoc
9842 */
9843 OO.ui.RadioInputWidget.static.tagName = 'span';
9844
9845 /* Static Methods */
9846
9847 /**
9848 * @inheritdoc
9849 */
9850 OO.ui.RadioInputWidget.static.gatherPreInfuseState = function ( node, config ) {
9851 var state = OO.ui.RadioInputWidget.parent.static.gatherPreInfuseState( node, config );
9852 state.checked = config.$input.prop( 'checked' );
9853 return state;
9854 };
9855
9856 /* Methods */
9857
9858 /**
9859 * @inheritdoc
9860 * @protected
9861 */
9862 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
9863 return $( '<input>' ).attr( 'type', 'radio' );
9864 };
9865
9866 /**
9867 * @inheritdoc
9868 */
9869 OO.ui.RadioInputWidget.prototype.onEdit = function () {
9870 // RadioInputWidget doesn't track its state.
9871 };
9872
9873 /**
9874 * Set selection state of this radio button.
9875 *
9876 * @param {boolean} state `true` for selected
9877 * @chainable
9878 * @return {OO.ui.Widget} The widget, for chaining
9879 */
9880 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
9881 // RadioInputWidget doesn't track its state.
9882 this.$input.prop( 'checked', state );
9883 // The first time that the selection state is set (probably while constructing the widget),
9884 // remember it in defaultSelected. This property can be later used to check whether
9885 // the selection state of the input has been changed since it was created.
9886 if ( this.defaultSelected === undefined ) {
9887 this.defaultSelected = state;
9888 this.$input[ 0 ].defaultChecked = this.defaultSelected;
9889 }
9890 return this;
9891 };
9892
9893 /**
9894 * Check if this radio button is selected.
9895 *
9896 * @return {boolean} Radio is selected
9897 */
9898 OO.ui.RadioInputWidget.prototype.isSelected = function () {
9899 return this.$input.prop( 'checked' );
9900 };
9901
9902 /**
9903 * @inheritdoc
9904 */
9905 OO.ui.RadioInputWidget.prototype.simulateLabelClick = function () {
9906 if ( !this.isDisabled() ) {
9907 this.$input.trigger( 'click' );
9908 }
9909 this.focus();
9910 };
9911
9912 /**
9913 * @inheritdoc
9914 */
9915 OO.ui.RadioInputWidget.prototype.restorePreInfuseState = function ( state ) {
9916 OO.ui.RadioInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
9917 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
9918 this.setSelected( state.checked );
9919 }
9920 };
9921
9922 /**
9923 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
9924 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
9925 * of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9926 * more information about input widgets.
9927 *
9928 * This and OO.ui.DropdownInputWidget support similar configuration options.
9929 *
9930 * @example
9931 * // A RadioSelectInputWidget with three options
9932 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
9933 * options: [
9934 * { data: 'a', label: 'First' },
9935 * { data: 'b', label: 'Second'},
9936 * { data: 'c', label: 'Third' }
9937 * ]
9938 * } );
9939 * $( document.body ).append( radioSelectInput.$element );
9940 *
9941 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9942 *
9943 * @class
9944 * @extends OO.ui.InputWidget
9945 *
9946 * @constructor
9947 * @param {Object} [config] Configuration options
9948 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9949 */
9950 OO.ui.RadioSelectInputWidget = function OoUiRadioSelectInputWidget( config ) {
9951 // Configuration initialization
9952 config = config || {};
9953
9954 // Properties (must be done before parent constructor which calls #setDisabled)
9955 this.radioSelectWidget = new OO.ui.RadioSelectWidget();
9956 // Set up the options before parent constructor, which uses them to validate config.value.
9957 // Use this instead of setOptions() because this.$input is not set up yet
9958 this.setOptionsData( config.options || [] );
9959
9960 // Parent constructor
9961 OO.ui.RadioSelectInputWidget.parent.call( this, config );
9962
9963 // Events
9964 this.radioSelectWidget.connect( this, { select: 'onMenuSelect' } );
9965
9966 // Initialization
9967 this.$element
9968 .addClass( 'oo-ui-radioSelectInputWidget' )
9969 .append( this.radioSelectWidget.$element );
9970 this.setTabIndexedElement( this.radioSelectWidget.$tabIndexed );
9971 };
9972
9973 /* Setup */
9974
9975 OO.inheritClass( OO.ui.RadioSelectInputWidget, OO.ui.InputWidget );
9976
9977 /* Static Methods */
9978
9979 /**
9980 * @inheritdoc
9981 */
9982 OO.ui.RadioSelectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
9983 var state = OO.ui.RadioSelectInputWidget.parent.static.gatherPreInfuseState( node, config );
9984 state.value = $( node ).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
9985 return state;
9986 };
9987
9988 /**
9989 * @inheritdoc
9990 */
9991 OO.ui.RadioSelectInputWidget.static.reusePreInfuseDOM = function ( node, config ) {
9992 config = OO.ui.RadioSelectInputWidget.parent.static.reusePreInfuseDOM( node, config );
9993 // Cannot reuse the `<input type=radio>` set
9994 delete config.$input;
9995 return config;
9996 };
9997
9998 /* Methods */
9999
10000 /**
10001 * @inheritdoc
10002 * @protected
10003 */
10004 OO.ui.RadioSelectInputWidget.prototype.getInputElement = function () {
10005 // Use this instead of <input type="hidden">, because hidden inputs do not have separate
10006 // 'value' and 'defaultValue' properties, and InputWidget wants to handle 'defaultValue'.
10007 return $( '<input>' ).addClass( 'oo-ui-element-hidden' );
10008 };
10009
10010 /**
10011 * Handles menu select events.
10012 *
10013 * @private
10014 * @param {OO.ui.RadioOptionWidget} item Selected menu item
10015 */
10016 OO.ui.RadioSelectInputWidget.prototype.onMenuSelect = function ( item ) {
10017 this.setValue( item.getData() );
10018 };
10019
10020 /**
10021 * @inheritdoc
10022 */
10023 OO.ui.RadioSelectInputWidget.prototype.setValue = function ( value ) {
10024 var selected;
10025 value = this.cleanUpValue( value );
10026 // Only allow setting values that are actually present in the dropdown
10027 selected = this.radioSelectWidget.findItemFromData( value ) ||
10028 this.radioSelectWidget.findFirstSelectableItem();
10029 this.radioSelectWidget.selectItem( selected );
10030 value = selected ? selected.getData() : '';
10031 OO.ui.RadioSelectInputWidget.parent.prototype.setValue.call( this, value );
10032 return this;
10033 };
10034
10035 /**
10036 * @inheritdoc
10037 */
10038 OO.ui.RadioSelectInputWidget.prototype.setDisabled = function ( state ) {
10039 this.radioSelectWidget.setDisabled( state );
10040 OO.ui.RadioSelectInputWidget.parent.prototype.setDisabled.call( this, state );
10041 return this;
10042 };
10043
10044 /**
10045 * Set the options available for this input.
10046 *
10047 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10048 * @chainable
10049 * @return {OO.ui.Widget} The widget, for chaining
10050 */
10051 OO.ui.RadioSelectInputWidget.prototype.setOptions = function ( options ) {
10052 var value = this.getValue();
10053
10054 this.setOptionsData( options );
10055
10056 // Re-set the value to update the visible interface (RadioSelectWidget).
10057 // In case the previous value is no longer an available option, select the first valid one.
10058 this.setValue( value );
10059
10060 return this;
10061 };
10062
10063 /**
10064 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
10065 *
10066 * This method may be called before the parent constructor, so various properties may not be
10067 * intialized yet.
10068 *
10069 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10070 * @private
10071 */
10072 OO.ui.RadioSelectInputWidget.prototype.setOptionsData = function ( options ) {
10073 var widget = this;
10074
10075 this.radioSelectWidget
10076 .clearItems()
10077 .addItems( options.map( function ( opt ) {
10078 var optValue = widget.cleanUpValue( opt.data );
10079 return new OO.ui.RadioOptionWidget( {
10080 data: optValue,
10081 label: opt.label !== undefined ? opt.label : optValue
10082 } );
10083 } ) );
10084 };
10085
10086 /**
10087 * @inheritdoc
10088 */
10089 OO.ui.RadioSelectInputWidget.prototype.focus = function () {
10090 this.radioSelectWidget.focus();
10091 return this;
10092 };
10093
10094 /**
10095 * @inheritdoc
10096 */
10097 OO.ui.RadioSelectInputWidget.prototype.blur = function () {
10098 this.radioSelectWidget.blur();
10099 return this;
10100 };
10101
10102 /**
10103 * CheckboxMultiselectInputWidget is a
10104 * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
10105 * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
10106 * HTML `<input type=checkbox>` tags. Please see the [OOUI documentation on MediaWiki][1] for
10107 * more information about input widgets.
10108 *
10109 * @example
10110 * // A CheckboxMultiselectInputWidget with three options.
10111 * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
10112 * options: [
10113 * { data: 'a', label: 'First' },
10114 * { data: 'b', label: 'Second' },
10115 * { data: 'c', label: 'Third' }
10116 * ]
10117 * } );
10118 * $( document.body ).append( multiselectInput.$element );
10119 *
10120 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
10121 *
10122 * @class
10123 * @extends OO.ui.InputWidget
10124 *
10125 * @constructor
10126 * @param {Object} [config] Configuration options
10127 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: …, disabled: … }`
10128 */
10129 OO.ui.CheckboxMultiselectInputWidget = function OoUiCheckboxMultiselectInputWidget( config ) {
10130 // Configuration initialization
10131 config = config || {};
10132
10133 // Properties (must be done before parent constructor which calls #setDisabled)
10134 this.checkboxMultiselectWidget = new OO.ui.CheckboxMultiselectWidget();
10135 // Must be set before the #setOptionsData call below
10136 this.inputName = config.name;
10137 // Set up the options before parent constructor, which uses them to validate config.value.
10138 // Use this instead of setOptions() because this.$input is not set up yet
10139 this.setOptionsData( config.options || [] );
10140
10141 // Parent constructor
10142 OO.ui.CheckboxMultiselectInputWidget.parent.call( this, config );
10143
10144 // Events
10145 this.checkboxMultiselectWidget.connect( this, { select: 'onCheckboxesSelect' } );
10146
10147 // Initialization
10148 this.$element
10149 .addClass( 'oo-ui-checkboxMultiselectInputWidget' )
10150 .append( this.checkboxMultiselectWidget.$element );
10151 // We don't use this.$input, but rather the CheckboxInputWidgets inside each option
10152 this.$input.detach();
10153 };
10154
10155 /* Setup */
10156
10157 OO.inheritClass( OO.ui.CheckboxMultiselectInputWidget, OO.ui.InputWidget );
10158
10159 /* Static Methods */
10160
10161 /**
10162 * @inheritdoc
10163 */
10164 OO.ui.CheckboxMultiselectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
10165 var state = OO.ui.CheckboxMultiselectInputWidget.parent.static.gatherPreInfuseState( node, config );
10166 state.value = $( node ).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
10167 .toArray().map( function ( el ) { return el.value; } );
10168 return state;
10169 };
10170
10171 /**
10172 * @inheritdoc
10173 */
10174 OO.ui.CheckboxMultiselectInputWidget.static.reusePreInfuseDOM = function ( node, config ) {
10175 config = OO.ui.CheckboxMultiselectInputWidget.parent.static.reusePreInfuseDOM( node, config );
10176 // Cannot reuse the `<input type=checkbox>` set
10177 delete config.$input;
10178 return config;
10179 };
10180
10181 /* Methods */
10182
10183 /**
10184 * @inheritdoc
10185 * @protected
10186 */
10187 OO.ui.CheckboxMultiselectInputWidget.prototype.getInputElement = function () {
10188 // Actually unused
10189 return $( '<unused>' );
10190 };
10191
10192 /**
10193 * Handles CheckboxMultiselectWidget select events.
10194 *
10195 * @private
10196 */
10197 OO.ui.CheckboxMultiselectInputWidget.prototype.onCheckboxesSelect = function () {
10198 this.setValue( this.checkboxMultiselectWidget.findSelectedItemsData() );
10199 };
10200
10201 /**
10202 * @inheritdoc
10203 */
10204 OO.ui.CheckboxMultiselectInputWidget.prototype.getValue = function () {
10205 var value = this.$element.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
10206 .toArray().map( function ( el ) { return el.value; } );
10207 if ( this.value !== value ) {
10208 this.setValue( value );
10209 }
10210 return this.value;
10211 };
10212
10213 /**
10214 * @inheritdoc
10215 */
10216 OO.ui.CheckboxMultiselectInputWidget.prototype.setValue = function ( value ) {
10217 value = this.cleanUpValue( value );
10218 this.checkboxMultiselectWidget.selectItemsByData( value );
10219 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.setValue.call( this, value );
10220 if ( this.optionsDirty ) {
10221 // We reached this from the constructor or from #setOptions.
10222 // We have to update the <select> element.
10223 this.updateOptionsInterface();
10224 }
10225 return this;
10226 };
10227
10228 /**
10229 * Clean up incoming value.
10230 *
10231 * @param {string[]} value Original value
10232 * @return {string[]} Cleaned up value
10233 */
10234 OO.ui.CheckboxMultiselectInputWidget.prototype.cleanUpValue = function ( value ) {
10235 var i, singleValue,
10236 cleanValue = [];
10237 if ( !Array.isArray( value ) ) {
10238 return cleanValue;
10239 }
10240 for ( i = 0; i < value.length; i++ ) {
10241 singleValue =
10242 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.cleanUpValue.call( this, value[ i ] );
10243 // Remove options that we don't have here
10244 if ( !this.checkboxMultiselectWidget.findItemFromData( singleValue ) ) {
10245 continue;
10246 }
10247 cleanValue.push( singleValue );
10248 }
10249 return cleanValue;
10250 };
10251
10252 /**
10253 * @inheritdoc
10254 */
10255 OO.ui.CheckboxMultiselectInputWidget.prototype.setDisabled = function ( state ) {
10256 this.checkboxMultiselectWidget.setDisabled( state );
10257 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.setDisabled.call( this, state );
10258 return this;
10259 };
10260
10261 /**
10262 * Set the options available for this input.
10263 *
10264 * @param {Object[]} options Array of menu options in the format `{ data: …, label: …, disabled: … }`
10265 * @chainable
10266 * @return {OO.ui.Widget} The widget, for chaining
10267 */
10268 OO.ui.CheckboxMultiselectInputWidget.prototype.setOptions = function ( options ) {
10269 var value = this.getValue();
10270
10271 this.setOptionsData( options );
10272
10273 // Re-set the value to update the visible interface (CheckboxMultiselectWidget).
10274 // This will also get rid of any stale options that we just removed.
10275 this.setValue( value );
10276
10277 return this;
10278 };
10279
10280 /**
10281 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
10282 *
10283 * This method may be called before the parent constructor, so various properties may not be
10284 * intialized yet.
10285 *
10286 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10287 * @private
10288 */
10289 OO.ui.CheckboxMultiselectInputWidget.prototype.setOptionsData = function ( options ) {
10290 var widget = this;
10291
10292 this.optionsDirty = true;
10293
10294 this.checkboxMultiselectWidget
10295 .clearItems()
10296 .addItems( options.map( function ( opt ) {
10297 var optValue, item, optDisabled;
10298 optValue =
10299 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.cleanUpValue.call( widget, opt.data );
10300 optDisabled = opt.disabled !== undefined ? opt.disabled : false;
10301 item = new OO.ui.CheckboxMultioptionWidget( {
10302 data: optValue,
10303 label: opt.label !== undefined ? opt.label : optValue,
10304 disabled: optDisabled
10305 } );
10306 // Set the 'name' and 'value' for form submission
10307 item.checkbox.$input.attr( 'name', widget.inputName );
10308 item.checkbox.setValue( optValue );
10309 return item;
10310 } ) );
10311 };
10312
10313 /**
10314 * Update the user-visible interface to match the internal list of options and value.
10315 *
10316 * This method must only be called after the parent constructor.
10317 *
10318 * @private
10319 */
10320 OO.ui.CheckboxMultiselectInputWidget.prototype.updateOptionsInterface = function () {
10321 var defaultValue = this.defaultValue;
10322
10323 this.checkboxMultiselectWidget.getItems().forEach( function ( item ) {
10324 // Remember original selection state. This property can be later used to check whether
10325 // the selection state of the input has been changed since it was created.
10326 var isDefault = defaultValue.indexOf( item.getData() ) !== -1;
10327 item.checkbox.defaultSelected = isDefault;
10328 item.checkbox.$input[ 0 ].defaultChecked = isDefault;
10329 } );
10330
10331 this.optionsDirty = false;
10332 };
10333
10334 /**
10335 * @inheritdoc
10336 */
10337 OO.ui.CheckboxMultiselectInputWidget.prototype.focus = function () {
10338 this.checkboxMultiselectWidget.focus();
10339 return this;
10340 };
10341
10342 /**
10343 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
10344 * size of the field as well as its presentation. In addition, these widgets can be configured
10345 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
10346 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
10347 * which modifies incoming values rather than validating them.
10348 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
10349 *
10350 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
10351 *
10352 * @example
10353 * // A TextInputWidget.
10354 * var textInput = new OO.ui.TextInputWidget( {
10355 * value: 'Text input'
10356 * } )
10357 * $( document.body ).append( textInput.$element );
10358 *
10359 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
10360 *
10361 * @class
10362 * @extends OO.ui.InputWidget
10363 * @mixins OO.ui.mixin.IconElement
10364 * @mixins OO.ui.mixin.IndicatorElement
10365 * @mixins OO.ui.mixin.PendingElement
10366 * @mixins OO.ui.mixin.LabelElement
10367 *
10368 * @constructor
10369 * @param {Object} [config] Configuration options
10370 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password'
10371 * 'email', 'url' or 'number'.
10372 * @cfg {string} [placeholder] Placeholder text
10373 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
10374 * instruct the browser to focus this widget.
10375 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
10376 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
10377 *
10378 * For unfortunate historical reasons, this counts the number of UTF-16 code units rather than
10379 * Unicode codepoints, which means that codepoints outside the Basic Multilingual Plane (e.g.
10380 * many emojis) count as 2 characters each.
10381 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
10382 * the value or placeholder text: `'before'` or `'after'`
10383 * @cfg {boolean} [required=false] Mark the field as required with `true`. Implies `indicator: 'required'`.
10384 * Note that `false` & setting `indicator: 'required' will result in no indicator shown.
10385 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
10386 * @cfg {boolean} [spellcheck] Should the browser support spellcheck for this field (`undefined` means
10387 * leaving it up to the browser).
10388 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
10389 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
10390 * (the value must contain only numbers); when RegExp, a regular expression that must match the
10391 * value for it to be considered valid; when Function, a function receiving the value as parameter
10392 * that must return true, or promise resolving to true, for it to be considered valid.
10393 */
10394 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
10395 // Configuration initialization
10396 config = $.extend( {
10397 type: 'text',
10398 labelPosition: 'after'
10399 }, config );
10400
10401 // Parent constructor
10402 OO.ui.TextInputWidget.parent.call( this, config );
10403
10404 // Mixin constructors
10405 OO.ui.mixin.IconElement.call( this, config );
10406 OO.ui.mixin.IndicatorElement.call( this, config );
10407 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$input } ) );
10408 OO.ui.mixin.LabelElement.call( this, config );
10409
10410 // Properties
10411 this.type = this.getSaneType( config );
10412 this.readOnly = false;
10413 this.required = false;
10414 this.validate = null;
10415 this.scrollWidth = null;
10416
10417 this.setValidation( config.validate );
10418 this.setLabelPosition( config.labelPosition );
10419
10420 // Events
10421 this.$input.on( {
10422 keypress: this.onKeyPress.bind( this ),
10423 blur: this.onBlur.bind( this ),
10424 focus: this.onFocus.bind( this )
10425 } );
10426 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
10427 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
10428 this.on( 'labelChange', this.updatePosition.bind( this ) );
10429 this.on( 'change', OO.ui.debounce( this.onDebouncedChange.bind( this ), 250 ) );
10430
10431 // Initialization
10432 this.$element
10433 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type )
10434 .append( this.$icon, this.$indicator );
10435 this.setReadOnly( !!config.readOnly );
10436 this.setRequired( !!config.required );
10437 if ( config.placeholder !== undefined ) {
10438 this.$input.attr( 'placeholder', config.placeholder );
10439 }
10440 if ( config.maxLength !== undefined ) {
10441 this.$input.attr( 'maxlength', config.maxLength );
10442 }
10443 if ( config.autofocus ) {
10444 this.$input.attr( 'autofocus', 'autofocus' );
10445 }
10446 if ( config.autocomplete === false ) {
10447 this.$input.attr( 'autocomplete', 'off' );
10448 // Turning off autocompletion also disables "form caching" when the user navigates to a
10449 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
10450 $( window ).on( {
10451 beforeunload: function () {
10452 this.$input.removeAttr( 'autocomplete' );
10453 }.bind( this ),
10454 pageshow: function () {
10455 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
10456 // whole page... it shouldn't hurt, though.
10457 this.$input.attr( 'autocomplete', 'off' );
10458 }.bind( this )
10459 } );
10460 }
10461 if ( config.spellcheck !== undefined ) {
10462 this.$input.attr( 'spellcheck', config.spellcheck ? 'true' : 'false' );
10463 }
10464 if ( this.label ) {
10465 this.isWaitingToBeAttached = true;
10466 this.installParentChangeDetector();
10467 }
10468 };
10469
10470 /* Setup */
10471
10472 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
10473 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IconElement );
10474 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IndicatorElement );
10475 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.PendingElement );
10476 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.LabelElement );
10477
10478 /* Static Properties */
10479
10480 OO.ui.TextInputWidget.static.validationPatterns = {
10481 'non-empty': /.+/,
10482 integer: /^\d+$/
10483 };
10484
10485 /* Events */
10486
10487 /**
10488 * An `enter` event is emitted when the user presses 'enter' inside the text box.
10489 *
10490 * @event enter
10491 */
10492
10493 /* Methods */
10494
10495 /**
10496 * Handle icon mouse down events.
10497 *
10498 * @private
10499 * @param {jQuery.Event} e Mouse down event
10500 * @return {undefined/boolean} False to prevent default if event is handled
10501 */
10502 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
10503 if ( e.which === OO.ui.MouseButtons.LEFT ) {
10504 this.focus();
10505 return false;
10506 }
10507 };
10508
10509 /**
10510 * Handle indicator mouse down events.
10511 *
10512 * @private
10513 * @param {jQuery.Event} e Mouse down event
10514 * @return {undefined/boolean} False to prevent default if event is handled
10515 */
10516 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
10517 if ( e.which === OO.ui.MouseButtons.LEFT ) {
10518 this.focus();
10519 return false;
10520 }
10521 };
10522
10523 /**
10524 * Handle key press events.
10525 *
10526 * @private
10527 * @param {jQuery.Event} e Key press event
10528 * @fires enter If enter key is pressed
10529 */
10530 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
10531 if ( e.which === OO.ui.Keys.ENTER ) {
10532 this.emit( 'enter', e );
10533 }
10534 };
10535
10536 /**
10537 * Handle blur events.
10538 *
10539 * @private
10540 * @param {jQuery.Event} e Blur event
10541 */
10542 OO.ui.TextInputWidget.prototype.onBlur = function () {
10543 this.setValidityFlag();
10544 };
10545
10546 /**
10547 * Handle focus events.
10548 *
10549 * @private
10550 * @param {jQuery.Event} e Focus event
10551 */
10552 OO.ui.TextInputWidget.prototype.onFocus = function () {
10553 if ( this.isWaitingToBeAttached ) {
10554 // If we've received focus, then we must be attached to the document, and if
10555 // isWaitingToBeAttached is still true, that means the handler never fired. Fire it now.
10556 this.onElementAttach();
10557 }
10558 this.setValidityFlag( true );
10559 };
10560
10561 /**
10562 * Handle element attach events.
10563 *
10564 * @private
10565 * @param {jQuery.Event} e Element attach event
10566 */
10567 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
10568 this.isWaitingToBeAttached = false;
10569 // Any previously calculated size is now probably invalid if we reattached elsewhere
10570 this.valCache = null;
10571 this.positionLabel();
10572 };
10573
10574 /**
10575 * Handle debounced change events.
10576 *
10577 * @param {string} value
10578 * @private
10579 */
10580 OO.ui.TextInputWidget.prototype.onDebouncedChange = function () {
10581 this.setValidityFlag();
10582 };
10583
10584 /**
10585 * Check if the input is {@link #readOnly read-only}.
10586 *
10587 * @return {boolean}
10588 */
10589 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
10590 return this.readOnly;
10591 };
10592
10593 /**
10594 * Set the {@link #readOnly read-only} state of the input.
10595 *
10596 * @param {boolean} state Make input read-only
10597 * @chainable
10598 * @return {OO.ui.Widget} The widget, for chaining
10599 */
10600 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
10601 this.readOnly = !!state;
10602 this.$input.prop( 'readOnly', this.readOnly );
10603 return this;
10604 };
10605
10606 /**
10607 * Check if the input is {@link #required required}.
10608 *
10609 * @return {boolean}
10610 */
10611 OO.ui.TextInputWidget.prototype.isRequired = function () {
10612 return this.required;
10613 };
10614
10615 /**
10616 * Set the {@link #required required} state of the input.
10617 *
10618 * @param {boolean} state Make input required
10619 * @chainable
10620 * @return {OO.ui.Widget} The widget, for chaining
10621 */
10622 OO.ui.TextInputWidget.prototype.setRequired = function ( state ) {
10623 this.required = !!state;
10624 if ( this.required ) {
10625 this.$input
10626 .prop( 'required', true )
10627 .attr( 'aria-required', 'true' );
10628 if ( this.getIndicator() === null ) {
10629 this.setIndicator( 'required' );
10630 }
10631 } else {
10632 this.$input
10633 .prop( 'required', false )
10634 .removeAttr( 'aria-required' );
10635 if ( this.getIndicator() === 'required' ) {
10636 this.setIndicator( null );
10637 }
10638 }
10639 return this;
10640 };
10641
10642 /**
10643 * Support function for making #onElementAttach work across browsers.
10644 *
10645 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
10646 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
10647 *
10648 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
10649 * first time that the element gets attached to the documented.
10650 */
10651 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
10652 var mutationObserver, onRemove, topmostNode, fakeParentNode,
10653 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
10654 widget = this;
10655
10656 if ( MutationObserver ) {
10657 // The new way. If only it wasn't so ugly.
10658
10659 if ( this.isElementAttached() ) {
10660 // Widget is attached already, do nothing. This breaks the functionality of this function when
10661 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
10662 // would require observation of the whole document, which would hurt performance of other,
10663 // more important code.
10664 return;
10665 }
10666
10667 // Find topmost node in the tree
10668 topmostNode = this.$element[ 0 ];
10669 while ( topmostNode.parentNode ) {
10670 topmostNode = topmostNode.parentNode;
10671 }
10672
10673 // We have no way to detect the $element being attached somewhere without observing the entire
10674 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
10675 // parent node of $element, and instead detect when $element is removed from it (and thus
10676 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
10677 // doesn't get attached, we end up back here and create the parent.
10678
10679 mutationObserver = new MutationObserver( function ( mutations ) {
10680 var i, j, removedNodes;
10681 for ( i = 0; i < mutations.length; i++ ) {
10682 removedNodes = mutations[ i ].removedNodes;
10683 for ( j = 0; j < removedNodes.length; j++ ) {
10684 if ( removedNodes[ j ] === topmostNode ) {
10685 setTimeout( onRemove, 0 );
10686 return;
10687 }
10688 }
10689 }
10690 } );
10691
10692 onRemove = function () {
10693 // If the node was attached somewhere else, report it
10694 if ( widget.isElementAttached() ) {
10695 widget.onElementAttach();
10696 }
10697 mutationObserver.disconnect();
10698 widget.installParentChangeDetector();
10699 };
10700
10701 // Create a fake parent and observe it
10702 fakeParentNode = $( '<div>' ).append( topmostNode )[ 0 ];
10703 mutationObserver.observe( fakeParentNode, { childList: true } );
10704 } else {
10705 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
10706 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
10707 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
10708 }
10709 };
10710
10711 /**
10712 * @inheritdoc
10713 * @protected
10714 */
10715 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
10716 if ( this.getSaneType( config ) === 'number' ) {
10717 return $( '<input>' )
10718 .attr( 'step', 'any' )
10719 .attr( 'type', 'number' );
10720 } else {
10721 return $( '<input>' ).attr( 'type', this.getSaneType( config ) );
10722 }
10723 };
10724
10725 /**
10726 * Get sanitized value for 'type' for given config.
10727 *
10728 * @param {Object} config Configuration options
10729 * @return {string|null}
10730 * @protected
10731 */
10732 OO.ui.TextInputWidget.prototype.getSaneType = function ( config ) {
10733 var allowedTypes = [
10734 'text',
10735 'password',
10736 'email',
10737 'url',
10738 'number'
10739 ];
10740 return allowedTypes.indexOf( config.type ) !== -1 ? config.type : 'text';
10741 };
10742
10743 /**
10744 * Focus the input and select a specified range within the text.
10745 *
10746 * @param {number} from Select from offset
10747 * @param {number} [to] Select to offset, defaults to from
10748 * @chainable
10749 * @return {OO.ui.Widget} The widget, for chaining
10750 */
10751 OO.ui.TextInputWidget.prototype.selectRange = function ( from, to ) {
10752 var isBackwards, start, end,
10753 input = this.$input[ 0 ];
10754
10755 to = to || from;
10756
10757 isBackwards = to < from;
10758 start = isBackwards ? to : from;
10759 end = isBackwards ? from : to;
10760
10761 this.focus();
10762
10763 try {
10764 input.setSelectionRange( start, end, isBackwards ? 'backward' : 'forward' );
10765 } catch ( e ) {
10766 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
10767 // Rather than expensively check if the input is attached every time, just check
10768 // if it was the cause of an error being thrown. If not, rethrow the error.
10769 if ( this.getElementDocument().body.contains( input ) ) {
10770 throw e;
10771 }
10772 }
10773 return this;
10774 };
10775
10776 /**
10777 * Get an object describing the current selection range in a directional manner
10778 *
10779 * @return {Object} Object containing 'from' and 'to' offsets
10780 */
10781 OO.ui.TextInputWidget.prototype.getRange = function () {
10782 var input = this.$input[ 0 ],
10783 start = input.selectionStart,
10784 end = input.selectionEnd,
10785 isBackwards = input.selectionDirection === 'backward';
10786
10787 return {
10788 from: isBackwards ? end : start,
10789 to: isBackwards ? start : end
10790 };
10791 };
10792
10793 /**
10794 * Get the length of the text input value.
10795 *
10796 * This could differ from the length of #getValue if the
10797 * value gets filtered
10798 *
10799 * @return {number} Input length
10800 */
10801 OO.ui.TextInputWidget.prototype.getInputLength = function () {
10802 return this.$input[ 0 ].value.length;
10803 };
10804
10805 /**
10806 * Focus the input and select the entire text.
10807 *
10808 * @chainable
10809 * @return {OO.ui.Widget} The widget, for chaining
10810 */
10811 OO.ui.TextInputWidget.prototype.select = function () {
10812 return this.selectRange( 0, this.getInputLength() );
10813 };
10814
10815 /**
10816 * Focus the input and move the cursor to the start.
10817 *
10818 * @chainable
10819 * @return {OO.ui.Widget} The widget, for chaining
10820 */
10821 OO.ui.TextInputWidget.prototype.moveCursorToStart = function () {
10822 return this.selectRange( 0 );
10823 };
10824
10825 /**
10826 * Focus the input and move the cursor to the end.
10827 *
10828 * @chainable
10829 * @return {OO.ui.Widget} The widget, for chaining
10830 */
10831 OO.ui.TextInputWidget.prototype.moveCursorToEnd = function () {
10832 return this.selectRange( this.getInputLength() );
10833 };
10834
10835 /**
10836 * Insert new content into the input.
10837 *
10838 * @param {string} content Content to be inserted
10839 * @chainable
10840 * @return {OO.ui.Widget} The widget, for chaining
10841 */
10842 OO.ui.TextInputWidget.prototype.insertContent = function ( content ) {
10843 var start, end,
10844 range = this.getRange(),
10845 value = this.getValue();
10846
10847 start = Math.min( range.from, range.to );
10848 end = Math.max( range.from, range.to );
10849
10850 this.setValue( value.slice( 0, start ) + content + value.slice( end ) );
10851 this.selectRange( start + content.length );
10852 return this;
10853 };
10854
10855 /**
10856 * Insert new content either side of a selection.
10857 *
10858 * @param {string} pre Content to be inserted before the selection
10859 * @param {string} post Content to be inserted after the selection
10860 * @chainable
10861 * @return {OO.ui.Widget} The widget, for chaining
10862 */
10863 OO.ui.TextInputWidget.prototype.encapsulateContent = function ( pre, post ) {
10864 var start, end,
10865 range = this.getRange(),
10866 offset = pre.length;
10867
10868 start = Math.min( range.from, range.to );
10869 end = Math.max( range.from, range.to );
10870
10871 this.selectRange( start ).insertContent( pre );
10872 this.selectRange( offset + end ).insertContent( post );
10873
10874 this.selectRange( offset + start, offset + end );
10875 return this;
10876 };
10877
10878 /**
10879 * Set the validation pattern.
10880 *
10881 * The validation pattern is either a regular expression, a function, or the symbolic name of a
10882 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
10883 * value must contain only numbers).
10884 *
10885 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
10886 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
10887 */
10888 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
10889 if ( validate instanceof RegExp || validate instanceof Function ) {
10890 this.validate = validate;
10891 } else {
10892 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
10893 }
10894 };
10895
10896 /**
10897 * Sets the 'invalid' flag appropriately.
10898 *
10899 * @param {boolean} [isValid] Optionally override validation result
10900 */
10901 OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) {
10902 var widget = this,
10903 setFlag = function ( valid ) {
10904 if ( !valid ) {
10905 widget.$input.attr( 'aria-invalid', 'true' );
10906 } else {
10907 widget.$input.removeAttr( 'aria-invalid' );
10908 }
10909 widget.setFlags( { invalid: !valid } );
10910 };
10911
10912 if ( isValid !== undefined ) {
10913 setFlag( isValid );
10914 } else {
10915 this.getValidity().then( function () {
10916 setFlag( true );
10917 }, function () {
10918 setFlag( false );
10919 } );
10920 }
10921 };
10922
10923 /**
10924 * Get the validity of current value.
10925 *
10926 * This method returns a promise that resolves if the value is valid and rejects if
10927 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
10928 *
10929 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
10930 */
10931 OO.ui.TextInputWidget.prototype.getValidity = function () {
10932 var result;
10933
10934 function rejectOrResolve( valid ) {
10935 if ( valid ) {
10936 return $.Deferred().resolve().promise();
10937 } else {
10938 return $.Deferred().reject().promise();
10939 }
10940 }
10941
10942 // Check browser validity and reject if it is invalid
10943 if (
10944 this.$input[ 0 ].checkValidity !== undefined &&
10945 this.$input[ 0 ].checkValidity() === false
10946 ) {
10947 return rejectOrResolve( false );
10948 }
10949
10950 // Run our checks if the browser thinks the field is valid
10951 if ( this.validate instanceof Function ) {
10952 result = this.validate( this.getValue() );
10953 if ( result && typeof result.promise === 'function' ) {
10954 return result.promise().then( function ( valid ) {
10955 return rejectOrResolve( valid );
10956 } );
10957 } else {
10958 return rejectOrResolve( result );
10959 }
10960 } else {
10961 return rejectOrResolve( this.getValue().match( this.validate ) );
10962 }
10963 };
10964
10965 /**
10966 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
10967 *
10968 * @param {string} labelPosition Label position, 'before' or 'after'
10969 * @chainable
10970 * @return {OO.ui.Widget} The widget, for chaining
10971 */
10972 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
10973 this.labelPosition = labelPosition;
10974 if ( this.label ) {
10975 // If there is no label and we only change the position, #updatePosition is a no-op,
10976 // but it takes really a lot of work to do nothing.
10977 this.updatePosition();
10978 }
10979 return this;
10980 };
10981
10982 /**
10983 * Update the position of the inline label.
10984 *
10985 * This method is called by #setLabelPosition, and can also be called on its own if
10986 * something causes the label to be mispositioned.
10987 *
10988 * @chainable
10989 * @return {OO.ui.Widget} The widget, for chaining
10990 */
10991 OO.ui.TextInputWidget.prototype.updatePosition = function () {
10992 var after = this.labelPosition === 'after';
10993
10994 this.$element
10995 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
10996 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
10997
10998 this.valCache = null;
10999 this.scrollWidth = null;
11000 this.positionLabel();
11001
11002 return this;
11003 };
11004
11005 /**
11006 * Position the label by setting the correct padding on the input.
11007 *
11008 * @private
11009 * @chainable
11010 * @return {OO.ui.Widget} The widget, for chaining
11011 */
11012 OO.ui.TextInputWidget.prototype.positionLabel = function () {
11013 var after, rtl, property, newCss;
11014
11015 if ( this.isWaitingToBeAttached ) {
11016 // #onElementAttach will be called soon, which calls this method
11017 return this;
11018 }
11019
11020 newCss = {
11021 'padding-right': '',
11022 'padding-left': ''
11023 };
11024
11025 if ( this.label ) {
11026 this.$element.append( this.$label );
11027 } else {
11028 this.$label.detach();
11029 // Clear old values if present
11030 this.$input.css( newCss );
11031 return;
11032 }
11033
11034 after = this.labelPosition === 'after';
11035 rtl = this.$element.css( 'direction' ) === 'rtl';
11036 property = after === rtl ? 'padding-left' : 'padding-right';
11037
11038 newCss[ property ] = this.$label.outerWidth( true ) + ( after ? this.scrollWidth : 0 );
11039 // We have to clear the padding on the other side, in case the element direction changed
11040 this.$input.css( newCss );
11041
11042 return this;
11043 };
11044
11045 /**
11046 * SearchInputWidgets are TextInputWidgets with `type="search"` assigned and feature a
11047 * {@link OO.ui.mixin.IconElement search icon} by default.
11048 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
11049 *
11050 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#SearchInputWidget
11051 *
11052 * @class
11053 * @extends OO.ui.TextInputWidget
11054 *
11055 * @constructor
11056 * @param {Object} [config] Configuration options
11057 */
11058 OO.ui.SearchInputWidget = function OoUiSearchInputWidget( config ) {
11059 config = $.extend( {
11060 icon: 'search'
11061 }, config );
11062
11063 // Parent constructor
11064 OO.ui.SearchInputWidget.parent.call( this, config );
11065
11066 // Events
11067 this.connect( this, {
11068 change: 'onChange'
11069 } );
11070
11071 // Initialization
11072 this.updateSearchIndicator();
11073 this.connect( this, {
11074 disable: 'onDisable'
11075 } );
11076 };
11077
11078 /* Setup */
11079
11080 OO.inheritClass( OO.ui.SearchInputWidget, OO.ui.TextInputWidget );
11081
11082 /* Methods */
11083
11084 /**
11085 * @inheritdoc
11086 * @protected
11087 */
11088 OO.ui.SearchInputWidget.prototype.getSaneType = function () {
11089 return 'search';
11090 };
11091
11092 /**
11093 * @inheritdoc
11094 */
11095 OO.ui.SearchInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
11096 if ( e.which === OO.ui.MouseButtons.LEFT ) {
11097 // Clear the text field
11098 this.setValue( '' );
11099 this.focus();
11100 return false;
11101 }
11102 };
11103
11104 /**
11105 * Update the 'clear' indicator displayed on type: 'search' text
11106 * fields, hiding it when the field is already empty or when it's not
11107 * editable.
11108 */
11109 OO.ui.SearchInputWidget.prototype.updateSearchIndicator = function () {
11110 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
11111 this.setIndicator( null );
11112 } else {
11113 this.setIndicator( 'clear' );
11114 }
11115 };
11116
11117 /**
11118 * Handle change events.
11119 *
11120 * @private
11121 */
11122 OO.ui.SearchInputWidget.prototype.onChange = function () {
11123 this.updateSearchIndicator();
11124 };
11125
11126 /**
11127 * Handle disable events.
11128 *
11129 * @param {boolean} disabled Element is disabled
11130 * @private
11131 */
11132 OO.ui.SearchInputWidget.prototype.onDisable = function () {
11133 this.updateSearchIndicator();
11134 };
11135
11136 /**
11137 * @inheritdoc
11138 */
11139 OO.ui.SearchInputWidget.prototype.setReadOnly = function ( state ) {
11140 OO.ui.SearchInputWidget.parent.prototype.setReadOnly.call( this, state );
11141 this.updateSearchIndicator();
11142 return this;
11143 };
11144
11145 /**
11146 * MultilineTextInputWidgets, like HTML textareas, are featuring customization options to
11147 * configure number of rows visible. In addition, these widgets can be autosized to fit user
11148 * inputs and can show {@link OO.ui.mixin.IconElement icons} and
11149 * {@link OO.ui.mixin.IndicatorElement indicators}.
11150 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
11151 *
11152 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
11153 *
11154 * @example
11155 * // A MultilineTextInputWidget.
11156 * var multilineTextInput = new OO.ui.MultilineTextInputWidget( {
11157 * value: 'Text input on multiple lines'
11158 * } )
11159 * $( 'body' ).append( multilineTextInput.$element );
11160 *
11161 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#MultilineTextInputWidget
11162 *
11163 * @class
11164 * @extends OO.ui.TextInputWidget
11165 *
11166 * @constructor
11167 * @param {Object} [config] Configuration options
11168 * @cfg {number} [rows] Number of visible lines in textarea. If used with `autosize`,
11169 * specifies minimum number of rows to display.
11170 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
11171 * Use the #maxRows config to specify a maximum number of displayed rows.
11172 * @cfg {number} [maxRows] Maximum number of rows to display when #autosize is set to true.
11173 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
11174 */
11175 OO.ui.MultilineTextInputWidget = function OoUiMultilineTextInputWidget( config ) {
11176 config = $.extend( {
11177 type: 'text'
11178 }, config );
11179 // Parent constructor
11180 OO.ui.MultilineTextInputWidget.parent.call( this, config );
11181
11182 // Properties
11183 this.autosize = !!config.autosize;
11184 this.styleHeight = null;
11185 this.minRows = config.rows !== undefined ? config.rows : '';
11186 this.maxRows = config.maxRows || Math.max( 2 * ( this.minRows || 0 ), 10 );
11187
11188 // Clone for resizing
11189 if ( this.autosize ) {
11190 this.$clone = this.$input
11191 .clone()
11192 .removeAttr( 'id' )
11193 .removeAttr( 'name' )
11194 .insertAfter( this.$input )
11195 .attr( 'aria-hidden', 'true' )
11196 .addClass( 'oo-ui-element-hidden' );
11197 }
11198
11199 // Events
11200 this.connect( this, {
11201 change: 'onChange'
11202 } );
11203
11204 // Initialization
11205 if ( config.rows ) {
11206 this.$input.attr( 'rows', config.rows );
11207 }
11208 if ( this.autosize ) {
11209 this.$input.addClass( 'oo-ui-textInputWidget-autosized' );
11210 this.isWaitingToBeAttached = true;
11211 this.installParentChangeDetector();
11212 }
11213 };
11214
11215 /* Setup */
11216
11217 OO.inheritClass( OO.ui.MultilineTextInputWidget, OO.ui.TextInputWidget );
11218
11219 /* Static Methods */
11220
11221 /**
11222 * @inheritdoc
11223 */
11224 OO.ui.MultilineTextInputWidget.static.gatherPreInfuseState = function ( node, config ) {
11225 var state = OO.ui.MultilineTextInputWidget.parent.static.gatherPreInfuseState( node, config );
11226 state.scrollTop = config.$input.scrollTop();
11227 return state;
11228 };
11229
11230 /* Methods */
11231
11232 /**
11233 * @inheritdoc
11234 */
11235 OO.ui.MultilineTextInputWidget.prototype.onElementAttach = function () {
11236 OO.ui.MultilineTextInputWidget.parent.prototype.onElementAttach.call( this );
11237 this.adjustSize();
11238 };
11239
11240 /**
11241 * Handle change events.
11242 *
11243 * @private
11244 */
11245 OO.ui.MultilineTextInputWidget.prototype.onChange = function () {
11246 this.adjustSize();
11247 };
11248
11249 /**
11250 * @inheritdoc
11251 */
11252 OO.ui.MultilineTextInputWidget.prototype.updatePosition = function () {
11253 OO.ui.MultilineTextInputWidget.parent.prototype.updatePosition.call( this );
11254 this.adjustSize();
11255 };
11256
11257 /**
11258 * @inheritdoc
11259 *
11260 * Modify to emit 'enter' on Ctrl/Meta+Enter, instead of plain Enter
11261 */
11262 OO.ui.MultilineTextInputWidget.prototype.onKeyPress = function ( e ) {
11263 if (
11264 ( e.which === OO.ui.Keys.ENTER && ( e.ctrlKey || e.metaKey ) ) ||
11265 // Some platforms emit keycode 10 for ctrl+enter in a textarea
11266 e.which === 10
11267 ) {
11268 this.emit( 'enter', e );
11269 }
11270 };
11271
11272 /**
11273 * Automatically adjust the size of the text input.
11274 *
11275 * This only affects multiline inputs that are {@link #autosize autosized}.
11276 *
11277 * @chainable
11278 * @return {OO.ui.Widget} The widget, for chaining
11279 * @fires resize
11280 */
11281 OO.ui.MultilineTextInputWidget.prototype.adjustSize = function () {
11282 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError,
11283 idealHeight, newHeight, scrollWidth, property;
11284
11285 if ( this.$input.val() !== this.valCache ) {
11286 if ( this.autosize ) {
11287 this.$clone
11288 .val( this.$input.val() )
11289 .attr( 'rows', this.minRows )
11290 // Set inline height property to 0 to measure scroll height
11291 .css( 'height', 0 );
11292
11293 this.$clone.removeClass( 'oo-ui-element-hidden' );
11294
11295 this.valCache = this.$input.val();
11296
11297 scrollHeight = this.$clone[ 0 ].scrollHeight;
11298
11299 // Remove inline height property to measure natural heights
11300 this.$clone.css( 'height', '' );
11301 innerHeight = this.$clone.innerHeight();
11302 outerHeight = this.$clone.outerHeight();
11303
11304 // Measure max rows height
11305 this.$clone
11306 .attr( 'rows', this.maxRows )
11307 .css( 'height', 'auto' )
11308 .val( '' );
11309 maxInnerHeight = this.$clone.innerHeight();
11310
11311 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
11312 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
11313 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
11314 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
11315
11316 this.$clone.addClass( 'oo-ui-element-hidden' );
11317
11318 // Only apply inline height when expansion beyond natural height is needed
11319 // Use the difference between the inner and outer height as a buffer
11320 newHeight = idealHeight > innerHeight ? idealHeight + ( outerHeight - innerHeight ) : '';
11321 if ( newHeight !== this.styleHeight ) {
11322 this.$input.css( 'height', newHeight );
11323 this.styleHeight = newHeight;
11324 this.emit( 'resize' );
11325 }
11326 }
11327 scrollWidth = this.$input[ 0 ].offsetWidth - this.$input[ 0 ].clientWidth;
11328 if ( scrollWidth !== this.scrollWidth ) {
11329 property = this.$element.css( 'direction' ) === 'rtl' ? 'left' : 'right';
11330 // Reset
11331 this.$label.css( { right: '', left: '' } );
11332 this.$indicator.css( { right: '', left: '' } );
11333
11334 if ( scrollWidth ) {
11335 this.$indicator.css( property, scrollWidth );
11336 if ( this.labelPosition === 'after' ) {
11337 this.$label.css( property, scrollWidth );
11338 }
11339 }
11340
11341 this.scrollWidth = scrollWidth;
11342 this.positionLabel();
11343 }
11344 }
11345 return this;
11346 };
11347
11348 /**
11349 * @inheritdoc
11350 * @protected
11351 */
11352 OO.ui.MultilineTextInputWidget.prototype.getInputElement = function () {
11353 return $( '<textarea>' );
11354 };
11355
11356 /**
11357 * Check if the input automatically adjusts its size.
11358 *
11359 * @return {boolean}
11360 */
11361 OO.ui.MultilineTextInputWidget.prototype.isAutosizing = function () {
11362 return !!this.autosize;
11363 };
11364
11365 /**
11366 * @inheritdoc
11367 */
11368 OO.ui.MultilineTextInputWidget.prototype.restorePreInfuseState = function ( state ) {
11369 OO.ui.MultilineTextInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
11370 if ( state.scrollTop !== undefined ) {
11371 this.$input.scrollTop( state.scrollTop );
11372 }
11373 };
11374
11375 /**
11376 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
11377 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
11378 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
11379 *
11380 * - by typing a value in the text input field. If the value exactly matches the value of a menu
11381 * option, that option will appear to be selected.
11382 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
11383 * input field.
11384 *
11385 * After the user chooses an option, its `data` will be used as a new value for the widget.
11386 * A `label` also can be specified for each option: if given, it will be shown instead of the
11387 * `data` in the dropdown menu.
11388 *
11389 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
11390 *
11391 * For more information about menus and options, please see the [OOUI documentation on MediaWiki][1].
11392 *
11393 * @example
11394 * // A ComboBoxInputWidget.
11395 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11396 * value: 'Option 1',
11397 * options: [
11398 * { data: 'Option 1' },
11399 * { data: 'Option 2' },
11400 * { data: 'Option 3' }
11401 * ]
11402 * } );
11403 * $( document.body ).append( comboBox.$element );
11404 *
11405 * @example
11406 * // Example: A ComboBoxInputWidget with additional option labels.
11407 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11408 * value: 'Option 1',
11409 * options: [
11410 * {
11411 * data: 'Option 1',
11412 * label: 'Option One'
11413 * },
11414 * {
11415 * data: 'Option 2',
11416 * label: 'Option Two'
11417 * },
11418 * {
11419 * data: 'Option 3',
11420 * label: 'Option Three'
11421 * }
11422 * ]
11423 * } );
11424 * $( document.body ).append( comboBox.$element );
11425 *
11426 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
11427 *
11428 * @class
11429 * @extends OO.ui.TextInputWidget
11430 *
11431 * @constructor
11432 * @param {Object} [config] Configuration options
11433 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
11434 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
11435 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
11436 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
11437 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
11438 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11439 */
11440 OO.ui.ComboBoxInputWidget = function OoUiComboBoxInputWidget( config ) {
11441 // Configuration initialization
11442 config = $.extend( {
11443 autocomplete: false
11444 }, config );
11445
11446 // ComboBoxInputWidget shouldn't support `multiline`
11447 config.multiline = false;
11448
11449 // See InputWidget#reusePreInfuseDOM about `config.$input`
11450 if ( config.$input ) {
11451 config.$input.removeAttr( 'list' );
11452 }
11453
11454 // Parent constructor
11455 OO.ui.ComboBoxInputWidget.parent.call( this, config );
11456
11457 // Properties
11458 this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
11459 this.dropdownButton = new OO.ui.ButtonWidget( {
11460 classes: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ],
11461 label: OO.ui.msg( 'ooui-combobox-button-label' ),
11462 indicator: 'down',
11463 invisibleLabel: true,
11464 disabled: this.disabled
11465 } );
11466 this.menu = new OO.ui.MenuSelectWidget( $.extend(
11467 {
11468 widget: this,
11469 input: this,
11470 $floatableContainer: this.$element,
11471 disabled: this.isDisabled()
11472 },
11473 config.menu
11474 ) );
11475
11476 // Events
11477 this.connect( this, {
11478 change: 'onInputChange',
11479 enter: 'onInputEnter'
11480 } );
11481 this.dropdownButton.connect( this, {
11482 click: 'onDropdownButtonClick'
11483 } );
11484 this.menu.connect( this, {
11485 choose: 'onMenuChoose',
11486 add: 'onMenuItemsChange',
11487 remove: 'onMenuItemsChange',
11488 toggle: 'onMenuToggle'
11489 } );
11490
11491 // Initialization
11492 this.$input.attr( {
11493 role: 'combobox',
11494 'aria-owns': this.menu.getElementId(),
11495 'aria-autocomplete': 'list'
11496 } );
11497 this.dropdownButton.$button.attr( {
11498 'aria-controls': this.menu.getElementId()
11499 } );
11500 // Do not override options set via config.menu.items
11501 if ( config.options !== undefined ) {
11502 this.setOptions( config.options );
11503 }
11504 this.$field = $( '<div>' )
11505 .addClass( 'oo-ui-comboBoxInputWidget-field' )
11506 .append( this.$input, this.dropdownButton.$element );
11507 this.$element
11508 .addClass( 'oo-ui-comboBoxInputWidget' )
11509 .append( this.$field );
11510 this.$overlay.append( this.menu.$element );
11511 this.onMenuItemsChange();
11512 };
11513
11514 /* Setup */
11515
11516 OO.inheritClass( OO.ui.ComboBoxInputWidget, OO.ui.TextInputWidget );
11517
11518 /* Methods */
11519
11520 /**
11521 * Get the combobox's menu.
11522 *
11523 * @return {OO.ui.MenuSelectWidget} Menu widget
11524 */
11525 OO.ui.ComboBoxInputWidget.prototype.getMenu = function () {
11526 return this.menu;
11527 };
11528
11529 /**
11530 * Get the combobox's text input widget.
11531 *
11532 * @return {OO.ui.TextInputWidget} Text input widget
11533 */
11534 OO.ui.ComboBoxInputWidget.prototype.getInput = function () {
11535 return this;
11536 };
11537
11538 /**
11539 * Handle input change events.
11540 *
11541 * @private
11542 * @param {string} value New value
11543 */
11544 OO.ui.ComboBoxInputWidget.prototype.onInputChange = function ( value ) {
11545 var match = this.menu.findItemFromData( value );
11546
11547 this.menu.selectItem( match );
11548 if ( this.menu.findHighlightedItem() ) {
11549 this.menu.highlightItem( match );
11550 }
11551
11552 if ( !this.isDisabled() ) {
11553 this.menu.toggle( true );
11554 }
11555 };
11556
11557 /**
11558 * Handle input enter events.
11559 *
11560 * @private
11561 */
11562 OO.ui.ComboBoxInputWidget.prototype.onInputEnter = function () {
11563 if ( !this.isDisabled() ) {
11564 this.menu.toggle( false );
11565 }
11566 };
11567
11568 /**
11569 * Handle button click events.
11570 *
11571 * @private
11572 */
11573 OO.ui.ComboBoxInputWidget.prototype.onDropdownButtonClick = function () {
11574 this.menu.toggle();
11575 this.focus();
11576 };
11577
11578 /**
11579 * Handle menu choose events.
11580 *
11581 * @private
11582 * @param {OO.ui.OptionWidget} item Chosen item
11583 */
11584 OO.ui.ComboBoxInputWidget.prototype.onMenuChoose = function ( item ) {
11585 this.setValue( item.getData() );
11586 };
11587
11588 /**
11589 * Handle menu item change events.
11590 *
11591 * @private
11592 */
11593 OO.ui.ComboBoxInputWidget.prototype.onMenuItemsChange = function () {
11594 var match = this.menu.findItemFromData( this.getValue() );
11595 this.menu.selectItem( match );
11596 if ( this.menu.findHighlightedItem() ) {
11597 this.menu.highlightItem( match );
11598 }
11599 this.$element.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu.isEmpty() );
11600 };
11601
11602 /**
11603 * Handle menu toggle events.
11604 *
11605 * @private
11606 * @param {boolean} isVisible Open state of the menu
11607 */
11608 OO.ui.ComboBoxInputWidget.prototype.onMenuToggle = function ( isVisible ) {
11609 this.$element.toggleClass( 'oo-ui-comboBoxInputWidget-open', isVisible );
11610 };
11611
11612 /**
11613 * Update the disabled state of the controls
11614 *
11615 * @chainable
11616 * @protected
11617 * @return {OO.ui.ComboBoxInputWidget} The widget, for chaining
11618 */
11619 OO.ui.ComboBoxInputWidget.prototype.updateControlsDisabled = function () {
11620 var disabled = this.isDisabled() || this.isReadOnly();
11621 if ( this.dropdownButton ) {
11622 this.dropdownButton.setDisabled( disabled );
11623 }
11624 if ( this.menu ) {
11625 this.menu.setDisabled( disabled );
11626 }
11627 return this;
11628 };
11629
11630 /**
11631 * @inheritdoc
11632 */
11633 OO.ui.ComboBoxInputWidget.prototype.setDisabled = function () {
11634 // Parent method
11635 OO.ui.ComboBoxInputWidget.parent.prototype.setDisabled.apply( this, arguments );
11636 this.updateControlsDisabled();
11637 return this;
11638 };
11639
11640 /**
11641 * @inheritdoc
11642 */
11643 OO.ui.ComboBoxInputWidget.prototype.setReadOnly = function () {
11644 // Parent method
11645 OO.ui.ComboBoxInputWidget.parent.prototype.setReadOnly.apply( this, arguments );
11646 this.updateControlsDisabled();
11647 return this;
11648 };
11649
11650 /**
11651 * Set the options available for this input.
11652 *
11653 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
11654 * @chainable
11655 * @return {OO.ui.Widget} The widget, for chaining
11656 */
11657 OO.ui.ComboBoxInputWidget.prototype.setOptions = function ( options ) {
11658 this.getMenu()
11659 .clearItems()
11660 .addItems( options.map( function ( opt ) {
11661 return new OO.ui.MenuOptionWidget( {
11662 data: opt.data,
11663 label: opt.label !== undefined ? opt.label : opt.data
11664 } );
11665 } ) );
11666
11667 return this;
11668 };
11669
11670 /**
11671 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
11672 * which is a widget that is specified by reference before any optional configuration settings.
11673 *
11674 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
11675 *
11676 * - **left**: The label is placed before the field-widget and aligned with the left margin.
11677 * A left-alignment is used for forms with many fields.
11678 * - **right**: The label is placed before the field-widget and aligned to the right margin.
11679 * A right-alignment is used for long but familiar forms which users tab through,
11680 * verifying the current field with a quick glance at the label.
11681 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
11682 * that users fill out from top to bottom.
11683 * - **inline**: The label is placed after the field-widget and aligned to the left.
11684 * An inline-alignment is best used with checkboxes or radio buttons.
11685 *
11686 * Help text can either be:
11687 *
11688 * - accessed via a help icon that appears in the upper right corner of the rendered field layout, or
11689 * - shown as a subtle explanation below the label.
11690 *
11691 * If the help text is brief, or is essential to always expose it, set `helpInline` to `true`. If it
11692 * is long or not essential, leave `helpInline` to its default, `false`.
11693 *
11694 * Please see the [OOUI documentation on MediaWiki] [1] for examples and more information.
11695 *
11696 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
11697 *
11698 * @class
11699 * @extends OO.ui.Layout
11700 * @mixins OO.ui.mixin.LabelElement
11701 * @mixins OO.ui.mixin.TitledElement
11702 *
11703 * @constructor
11704 * @param {OO.ui.Widget} fieldWidget Field widget
11705 * @param {Object} [config] Configuration options
11706 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top'
11707 * or 'inline'
11708 * @cfg {Array} [errors] Error messages about the widget, which will be
11709 * displayed below the widget.
11710 * The array may contain strings or OO.ui.HtmlSnippet instances.
11711 * @cfg {Array} [notices] Notices about the widget, which will be displayed
11712 * below the widget.
11713 * The array may contain strings or OO.ui.HtmlSnippet instances.
11714 * These are more visible than `help` messages when `helpInline` is set, and so
11715 * might be good for transient messages.
11716 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified
11717 * and `helpInline` is `false`, a "help" icon will appear in the upper-right
11718 * corner of the rendered field; clicking it will display the text in a popup.
11719 * If `helpInline` is `true`, then a subtle description will be shown after the
11720 * label.
11721 * @cfg {boolean} [helpInline=false] Whether or not the help should be inline,
11722 * or shown when the "help" icon is clicked.
11723 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if
11724 * `help` is given.
11725 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11726 *
11727 * @throws {Error} An error is thrown if no widget is specified
11728 */
11729 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
11730 // Allow passing positional parameters inside the config object
11731 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
11732 config = fieldWidget;
11733 fieldWidget = config.fieldWidget;
11734 }
11735
11736 // Make sure we have required constructor arguments
11737 if ( fieldWidget === undefined ) {
11738 throw new Error( 'Widget not found' );
11739 }
11740
11741 // Configuration initialization
11742 config = $.extend( { align: 'left', helpInline: false }, config );
11743
11744 // Parent constructor
11745 OO.ui.FieldLayout.parent.call( this, config );
11746
11747 // Mixin constructors
11748 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, {
11749 $label: $( '<label>' )
11750 } ) );
11751 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
11752
11753 // Properties
11754 this.fieldWidget = fieldWidget;
11755 this.errors = [];
11756 this.notices = [];
11757 this.$field = this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
11758 this.$messages = $( '<ul>' );
11759 this.$header = $( '<span>' );
11760 this.$body = $( '<div>' );
11761 this.align = null;
11762 this.helpInline = config.helpInline;
11763
11764 // Events
11765 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
11766
11767 // Initialization
11768 this.$help = config.help ?
11769 this.createHelpElement( config.help, config.$overlay ) :
11770 $( [] );
11771 if ( this.fieldWidget.getInputId() ) {
11772 this.$label.attr( 'for', this.fieldWidget.getInputId() );
11773 if ( this.helpInline ) {
11774 this.$help.attr( 'for', this.fieldWidget.getInputId() );
11775 }
11776 } else {
11777 this.$label.on( 'click', function () {
11778 this.fieldWidget.simulateLabelClick();
11779 }.bind( this ) );
11780 if ( this.helpInline ) {
11781 this.$help.on( 'click', function () {
11782 this.fieldWidget.simulateLabelClick();
11783 }.bind( this ) );
11784 }
11785 }
11786 this.$element
11787 .addClass( 'oo-ui-fieldLayout' )
11788 .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget.isDisabled() )
11789 .append( this.$body );
11790 this.$body.addClass( 'oo-ui-fieldLayout-body' );
11791 this.$header.addClass( 'oo-ui-fieldLayout-header' );
11792 this.$messages.addClass( 'oo-ui-fieldLayout-messages' );
11793 this.$field
11794 .addClass( 'oo-ui-fieldLayout-field' )
11795 .append( this.fieldWidget.$element );
11796
11797 this.setErrors( config.errors || [] );
11798 this.setNotices( config.notices || [] );
11799 this.setAlignment( config.align );
11800 // Call this again to take into account the widget's accessKey
11801 this.updateTitle();
11802 };
11803
11804 /* Setup */
11805
11806 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
11807 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.LabelElement );
11808 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.TitledElement );
11809
11810 /* Methods */
11811
11812 /**
11813 * Handle field disable events.
11814 *
11815 * @private
11816 * @param {boolean} value Field is disabled
11817 */
11818 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
11819 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
11820 };
11821
11822 /**
11823 * Get the widget contained by the field.
11824 *
11825 * @return {OO.ui.Widget} Field widget
11826 */
11827 OO.ui.FieldLayout.prototype.getField = function () {
11828 return this.fieldWidget;
11829 };
11830
11831 /**
11832 * Return `true` if the given field widget can be used with `'inline'` alignment (see
11833 * #setAlignment). Return `false` if it can't or if this can't be determined.
11834 *
11835 * @return {boolean}
11836 */
11837 OO.ui.FieldLayout.prototype.isFieldInline = function () {
11838 // This is very simplistic, but should be good enough.
11839 return this.getField().$element.prop( 'tagName' ).toLowerCase() === 'span';
11840 };
11841
11842 /**
11843 * @protected
11844 * @param {string} kind 'error' or 'notice'
11845 * @param {string|OO.ui.HtmlSnippet} text
11846 * @return {jQuery}
11847 */
11848 OO.ui.FieldLayout.prototype.makeMessage = function ( kind, text ) {
11849 var $listItem, $icon, message;
11850 $listItem = $( '<li>' );
11851 if ( kind === 'error' ) {
11852 $icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'warning' ] } ).$element;
11853 $listItem.attr( 'role', 'alert' );
11854 } else if ( kind === 'notice' ) {
11855 $icon = new OO.ui.IconWidget( { icon: 'notice' } ).$element;
11856 } else {
11857 $icon = '';
11858 }
11859 message = new OO.ui.LabelWidget( { label: text } );
11860 $listItem
11861 .append( $icon, message.$element )
11862 .addClass( 'oo-ui-fieldLayout-messages-' + kind );
11863 return $listItem;
11864 };
11865
11866 /**
11867 * Set the field alignment mode.
11868 *
11869 * @private
11870 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
11871 * @chainable
11872 * @return {OO.ui.BookletLayout} The layout, for chaining
11873 */
11874 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
11875 if ( value !== this.align ) {
11876 // Default to 'left'
11877 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
11878 value = 'left';
11879 }
11880 // Validate
11881 if ( value === 'inline' && !this.isFieldInline() ) {
11882 value = 'top';
11883 }
11884 // Reorder elements
11885
11886 if ( this.helpInline ) {
11887 if ( value === 'top' ) {
11888 this.$header.append( this.$label );
11889 this.$body.append( this.$header, this.$field, this.$help );
11890 } else if ( value === 'inline' ) {
11891 this.$header.append( this.$label, this.$help );
11892 this.$body.append( this.$field, this.$header );
11893 } else {
11894 this.$header.append( this.$label, this.$help );
11895 this.$body.append( this.$header, this.$field );
11896 }
11897 } else {
11898 if ( value === 'top' ) {
11899 this.$header.append( this.$help, this.$label );
11900 this.$body.append( this.$header, this.$field );
11901 } else if ( value === 'inline' ) {
11902 this.$header.append( this.$help, this.$label );
11903 this.$body.append( this.$field, this.$header );
11904 } else {
11905 this.$header.append( this.$label );
11906 this.$body.append( this.$header, this.$help, this.$field );
11907 }
11908 }
11909 // Set classes. The following classes can be used here:
11910 // * oo-ui-fieldLayout-align-left
11911 // * oo-ui-fieldLayout-align-right
11912 // * oo-ui-fieldLayout-align-top
11913 // * oo-ui-fieldLayout-align-inline
11914 if ( this.align ) {
11915 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
11916 }
11917 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
11918 this.align = value;
11919 }
11920
11921 return this;
11922 };
11923
11924 /**
11925 * Set the list of error messages.
11926 *
11927 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
11928 * The array may contain strings or OO.ui.HtmlSnippet instances.
11929 * @chainable
11930 * @return {OO.ui.BookletLayout} The layout, for chaining
11931 */
11932 OO.ui.FieldLayout.prototype.setErrors = function ( errors ) {
11933 this.errors = errors.slice();
11934 this.updateMessages();
11935 return this;
11936 };
11937
11938 /**
11939 * Set the list of notice messages.
11940 *
11941 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
11942 * The array may contain strings or OO.ui.HtmlSnippet instances.
11943 * @chainable
11944 * @return {OO.ui.BookletLayout} The layout, for chaining
11945 */
11946 OO.ui.FieldLayout.prototype.setNotices = function ( notices ) {
11947 this.notices = notices.slice();
11948 this.updateMessages();
11949 return this;
11950 };
11951
11952 /**
11953 * Update the rendering of error and notice messages.
11954 *
11955 * @private
11956 */
11957 OO.ui.FieldLayout.prototype.updateMessages = function () {
11958 var i;
11959 this.$messages.empty();
11960
11961 if ( this.errors.length || this.notices.length ) {
11962 this.$body.after( this.$messages );
11963 } else {
11964 this.$messages.remove();
11965 return;
11966 }
11967
11968 for ( i = 0; i < this.notices.length; i++ ) {
11969 this.$messages.append( this.makeMessage( 'notice', this.notices[ i ] ) );
11970 }
11971 for ( i = 0; i < this.errors.length; i++ ) {
11972 this.$messages.append( this.makeMessage( 'error', this.errors[ i ] ) );
11973 }
11974 };
11975
11976 /**
11977 * Include information about the widget's accessKey in our title. TitledElement calls this method.
11978 * (This is a bit of a hack.)
11979 *
11980 * @protected
11981 * @param {string} title Tooltip label for 'title' attribute
11982 * @return {string}
11983 */
11984 OO.ui.FieldLayout.prototype.formatTitleWithAccessKey = function ( title ) {
11985 if ( this.fieldWidget && this.fieldWidget.formatTitleWithAccessKey ) {
11986 return this.fieldWidget.formatTitleWithAccessKey( title );
11987 }
11988 return title;
11989 };
11990
11991 /**
11992 * Creates and returns the help element. Also sets the `aria-describedby`
11993 * attribute on the main element of the `fieldWidget`.
11994 *
11995 * @private
11996 * @param {string|OO.ui.HtmlSnippet} [help] Help text.
11997 * @param {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup.
11998 * @return {jQuery} The element that should become `this.$help`.
11999 */
12000 OO.ui.FieldLayout.prototype.createHelpElement = function ( help, $overlay ) {
12001 var helpId, helpWidget;
12002
12003 if ( this.helpInline ) {
12004 helpWidget = new OO.ui.LabelWidget( {
12005 label: help,
12006 classes: [ 'oo-ui-inline-help' ]
12007 } );
12008
12009 helpId = helpWidget.getElementId();
12010 } else {
12011 helpWidget = new OO.ui.PopupButtonWidget( {
12012 $overlay: $overlay,
12013 popup: {
12014 padded: true
12015 },
12016 classes: [ 'oo-ui-fieldLayout-help' ],
12017 framed: false,
12018 icon: 'info',
12019 label: OO.ui.msg( 'ooui-field-help' ),
12020 invisibleLabel: true
12021 } );
12022 if ( help instanceof OO.ui.HtmlSnippet ) {
12023 helpWidget.getPopup().$body.html( help.toString() );
12024 } else {
12025 helpWidget.getPopup().$body.text( help );
12026 }
12027
12028 helpId = helpWidget.getPopup().getBodyId();
12029 }
12030
12031 // Set the 'aria-describedby' attribute on the fieldWidget
12032 // Preference given to an input or a button
12033 (
12034 this.fieldWidget.$input ||
12035 this.fieldWidget.$button ||
12036 this.fieldWidget.$element
12037 ).attr( 'aria-describedby', helpId );
12038
12039 return helpWidget.$element;
12040 };
12041
12042 /**
12043 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
12044 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
12045 * is required and is specified before any optional configuration settings.
12046 *
12047 * Labels can be aligned in one of four ways:
12048 *
12049 * - **left**: The label is placed before the field-widget and aligned with the left margin.
12050 * A left-alignment is used for forms with many fields.
12051 * - **right**: The label is placed before the field-widget and aligned to the right margin.
12052 * A right-alignment is used for long but familiar forms which users tab through,
12053 * verifying the current field with a quick glance at the label.
12054 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
12055 * that users fill out from top to bottom.
12056 * - **inline**: The label is placed after the field-widget and aligned to the left.
12057 * An inline-alignment is best used with checkboxes or radio buttons.
12058 *
12059 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
12060 * text is specified.
12061 *
12062 * @example
12063 * // Example of an ActionFieldLayout
12064 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
12065 * new OO.ui.TextInputWidget( {
12066 * placeholder: 'Field widget'
12067 * } ),
12068 * new OO.ui.ButtonWidget( {
12069 * label: 'Button'
12070 * } ),
12071 * {
12072 * label: 'An ActionFieldLayout. This label is aligned top',
12073 * align: 'top',
12074 * help: 'This is help text'
12075 * }
12076 * );
12077 *
12078 * $( document.body ).append( actionFieldLayout.$element );
12079 *
12080 * @class
12081 * @extends OO.ui.FieldLayout
12082 *
12083 * @constructor
12084 * @param {OO.ui.Widget} fieldWidget Field widget
12085 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
12086 * @param {Object} config
12087 */
12088 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
12089 // Allow passing positional parameters inside the config object
12090 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
12091 config = fieldWidget;
12092 fieldWidget = config.fieldWidget;
12093 buttonWidget = config.buttonWidget;
12094 }
12095
12096 // Parent constructor
12097 OO.ui.ActionFieldLayout.parent.call( this, fieldWidget, config );
12098
12099 // Properties
12100 this.buttonWidget = buttonWidget;
12101 this.$button = $( '<span>' );
12102 this.$input = this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
12103
12104 // Initialization
12105 this.$element
12106 .addClass( 'oo-ui-actionFieldLayout' );
12107 this.$button
12108 .addClass( 'oo-ui-actionFieldLayout-button' )
12109 .append( this.buttonWidget.$element );
12110 this.$input
12111 .addClass( 'oo-ui-actionFieldLayout-input' )
12112 .append( this.fieldWidget.$element );
12113 this.$field
12114 .append( this.$input, this.$button );
12115 };
12116
12117 /* Setup */
12118
12119 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
12120
12121 /**
12122 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
12123 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
12124 * configured with a label as well. For more information and examples,
12125 * please see the [OOUI documentation on MediaWiki][1].
12126 *
12127 * @example
12128 * // Example of a fieldset layout
12129 * var input1 = new OO.ui.TextInputWidget( {
12130 * placeholder: 'A text input field'
12131 * } );
12132 *
12133 * var input2 = new OO.ui.TextInputWidget( {
12134 * placeholder: 'A text input field'
12135 * } );
12136 *
12137 * var fieldset = new OO.ui.FieldsetLayout( {
12138 * label: 'Example of a fieldset layout'
12139 * } );
12140 *
12141 * fieldset.addItems( [
12142 * new OO.ui.FieldLayout( input1, {
12143 * label: 'Field One'
12144 * } ),
12145 * new OO.ui.FieldLayout( input2, {
12146 * label: 'Field Two'
12147 * } )
12148 * ] );
12149 * $( document.body ).append( fieldset.$element );
12150 *
12151 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
12152 *
12153 * @class
12154 * @extends OO.ui.Layout
12155 * @mixins OO.ui.mixin.IconElement
12156 * @mixins OO.ui.mixin.LabelElement
12157 * @mixins OO.ui.mixin.GroupElement
12158 *
12159 * @constructor
12160 * @param {Object} [config] Configuration options
12161 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
12162 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
12163 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
12164 * For important messages, you are advised to use `notices`, as they are always shown.
12165 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
12166 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
12167 */
12168 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
12169 // Configuration initialization
12170 config = config || {};
12171
12172 // Parent constructor
12173 OO.ui.FieldsetLayout.parent.call( this, config );
12174
12175 // Mixin constructors
12176 OO.ui.mixin.IconElement.call( this, config );
12177 OO.ui.mixin.LabelElement.call( this, config );
12178 OO.ui.mixin.GroupElement.call( this, config );
12179
12180 // Properties
12181 this.$header = $( '<legend>' );
12182 if ( config.help ) {
12183 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
12184 $overlay: config.$overlay,
12185 popup: {
12186 padded: true
12187 },
12188 classes: [ 'oo-ui-fieldsetLayout-help' ],
12189 framed: false,
12190 icon: 'info',
12191 label: OO.ui.msg( 'ooui-field-help' ),
12192 invisibleLabel: true
12193 } );
12194 if ( config.help instanceof OO.ui.HtmlSnippet ) {
12195 this.popupButtonWidget.getPopup().$body.html( config.help.toString() );
12196 } else {
12197 this.popupButtonWidget.getPopup().$body.text( config.help );
12198 }
12199 this.$help = this.popupButtonWidget.$element;
12200 } else {
12201 this.$help = $( [] );
12202 }
12203
12204 // Initialization
12205 this.$header
12206 .addClass( 'oo-ui-fieldsetLayout-header' )
12207 .append( this.$icon, this.$label, this.$help );
12208 this.$group.addClass( 'oo-ui-fieldsetLayout-group' );
12209 this.$element
12210 .addClass( 'oo-ui-fieldsetLayout' )
12211 .prepend( this.$header, this.$group );
12212 if ( Array.isArray( config.items ) ) {
12213 this.addItems( config.items );
12214 }
12215 };
12216
12217 /* Setup */
12218
12219 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
12220 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.IconElement );
12221 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.LabelElement );
12222 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.GroupElement );
12223
12224 /* Static Properties */
12225
12226 /**
12227 * @static
12228 * @inheritdoc
12229 */
12230 OO.ui.FieldsetLayout.static.tagName = 'fieldset';
12231
12232 /**
12233 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
12234 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
12235 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
12236 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
12237 *
12238 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
12239 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
12240 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
12241 * some fancier controls. Some controls have both regular and InputWidget variants, for example
12242 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
12243 * often have simplified APIs to match the capabilities of HTML forms.
12244 * See the [OOUI documentation on MediaWiki] [2] for more information about InputWidgets.
12245 *
12246 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Forms
12247 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
12248 *
12249 * @example
12250 * // Example of a form layout that wraps a fieldset layout
12251 * var input1 = new OO.ui.TextInputWidget( {
12252 * placeholder: 'Username'
12253 * } );
12254 * var input2 = new OO.ui.TextInputWidget( {
12255 * placeholder: 'Password',
12256 * type: 'password'
12257 * } );
12258 * var submit = new OO.ui.ButtonInputWidget( {
12259 * label: 'Submit'
12260 * } );
12261 *
12262 * var fieldset = new OO.ui.FieldsetLayout( {
12263 * label: 'A form layout'
12264 * } );
12265 * fieldset.addItems( [
12266 * new OO.ui.FieldLayout( input1, {
12267 * label: 'Username',
12268 * align: 'top'
12269 * } ),
12270 * new OO.ui.FieldLayout( input2, {
12271 * label: 'Password',
12272 * align: 'top'
12273 * } ),
12274 * new OO.ui.FieldLayout( submit )
12275 * ] );
12276 * var form = new OO.ui.FormLayout( {
12277 * items: [ fieldset ],
12278 * action: '/api/formhandler',
12279 * method: 'get'
12280 * } )
12281 * $( document.body ).append( form.$element );
12282 *
12283 * @class
12284 * @extends OO.ui.Layout
12285 * @mixins OO.ui.mixin.GroupElement
12286 *
12287 * @constructor
12288 * @param {Object} [config] Configuration options
12289 * @cfg {string} [method] HTML form `method` attribute
12290 * @cfg {string} [action] HTML form `action` attribute
12291 * @cfg {string} [enctype] HTML form `enctype` attribute
12292 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
12293 */
12294 OO.ui.FormLayout = function OoUiFormLayout( config ) {
12295 var action;
12296
12297 // Configuration initialization
12298 config = config || {};
12299
12300 // Parent constructor
12301 OO.ui.FormLayout.parent.call( this, config );
12302
12303 // Mixin constructors
12304 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
12305
12306 // Events
12307 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
12308
12309 // Make sure the action is safe
12310 action = config.action;
12311 if ( action !== undefined && !OO.ui.isSafeUrl( action ) ) {
12312 action = './' + action;
12313 }
12314
12315 // Initialization
12316 this.$element
12317 .addClass( 'oo-ui-formLayout' )
12318 .attr( {
12319 method: config.method,
12320 action: action,
12321 enctype: config.enctype
12322 } );
12323 if ( Array.isArray( config.items ) ) {
12324 this.addItems( config.items );
12325 }
12326 };
12327
12328 /* Setup */
12329
12330 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
12331 OO.mixinClass( OO.ui.FormLayout, OO.ui.mixin.GroupElement );
12332
12333 /* Events */
12334
12335 /**
12336 * A 'submit' event is emitted when the form is submitted.
12337 *
12338 * @event submit
12339 */
12340
12341 /* Static Properties */
12342
12343 /**
12344 * @static
12345 * @inheritdoc
12346 */
12347 OO.ui.FormLayout.static.tagName = 'form';
12348
12349 /* Methods */
12350
12351 /**
12352 * Handle form submit events.
12353 *
12354 * @private
12355 * @param {jQuery.Event} e Submit event
12356 * @fires submit
12357 * @return {OO.ui.FormLayout} The layout, for chaining
12358 */
12359 OO.ui.FormLayout.prototype.onFormSubmit = function () {
12360 if ( this.emit( 'submit' ) ) {
12361 return false;
12362 }
12363 };
12364
12365 /**
12366 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
12367 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
12368 *
12369 * @example
12370 * // Example of a panel layout
12371 * var panel = new OO.ui.PanelLayout( {
12372 * expanded: false,
12373 * framed: true,
12374 * padded: true,
12375 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
12376 * } );
12377 * $( document.body ).append( panel.$element );
12378 *
12379 * @class
12380 * @extends OO.ui.Layout
12381 *
12382 * @constructor
12383 * @param {Object} [config] Configuration options
12384 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
12385 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
12386 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
12387 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
12388 */
12389 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
12390 // Configuration initialization
12391 config = $.extend( {
12392 scrollable: false,
12393 padded: false,
12394 expanded: true,
12395 framed: false
12396 }, config );
12397
12398 // Parent constructor
12399 OO.ui.PanelLayout.parent.call( this, config );
12400
12401 // Initialization
12402 this.$element.addClass( 'oo-ui-panelLayout' );
12403 if ( config.scrollable ) {
12404 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
12405 }
12406 if ( config.padded ) {
12407 this.$element.addClass( 'oo-ui-panelLayout-padded' );
12408 }
12409 if ( config.expanded ) {
12410 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
12411 }
12412 if ( config.framed ) {
12413 this.$element.addClass( 'oo-ui-panelLayout-framed' );
12414 }
12415 };
12416
12417 /* Setup */
12418
12419 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
12420
12421 /* Methods */
12422
12423 /**
12424 * Focus the panel layout
12425 *
12426 * The default implementation just focuses the first focusable element in the panel
12427 */
12428 OO.ui.PanelLayout.prototype.focus = function () {
12429 OO.ui.findFocusable( this.$element ).focus();
12430 };
12431
12432 /**
12433 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
12434 * items), with small margins between them. Convenient when you need to put a number of block-level
12435 * widgets on a single line next to each other.
12436 *
12437 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
12438 *
12439 * @example
12440 * // HorizontalLayout with a text input and a label
12441 * var layout = new OO.ui.HorizontalLayout( {
12442 * items: [
12443 * new OO.ui.LabelWidget( { label: 'Label' } ),
12444 * new OO.ui.TextInputWidget( { value: 'Text' } )
12445 * ]
12446 * } );
12447 * $( document.body ).append( layout.$element );
12448 *
12449 * @class
12450 * @extends OO.ui.Layout
12451 * @mixins OO.ui.mixin.GroupElement
12452 *
12453 * @constructor
12454 * @param {Object} [config] Configuration options
12455 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
12456 */
12457 OO.ui.HorizontalLayout = function OoUiHorizontalLayout( config ) {
12458 // Configuration initialization
12459 config = config || {};
12460
12461 // Parent constructor
12462 OO.ui.HorizontalLayout.parent.call( this, config );
12463
12464 // Mixin constructors
12465 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
12466
12467 // Initialization
12468 this.$element.addClass( 'oo-ui-horizontalLayout' );
12469 if ( Array.isArray( config.items ) ) {
12470 this.addItems( config.items );
12471 }
12472 };
12473
12474 /* Setup */
12475
12476 OO.inheritClass( OO.ui.HorizontalLayout, OO.ui.Layout );
12477 OO.mixinClass( OO.ui.HorizontalLayout, OO.ui.mixin.GroupElement );
12478
12479 /**
12480 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
12481 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
12482 * (to adjust the value in increments) to allow the user to enter a number.
12483 *
12484 * @example
12485 * // A NumberInputWidget.
12486 * var numberInput = new OO.ui.NumberInputWidget( {
12487 * label: 'NumberInputWidget',
12488 * input: { value: 5 },
12489 * min: 1,
12490 * max: 10
12491 * } );
12492 * $( document.body ).append( numberInput.$element );
12493 *
12494 * @class
12495 * @extends OO.ui.TextInputWidget
12496 *
12497 * @constructor
12498 * @param {Object} [config] Configuration options
12499 * @cfg {Object} [minusButton] Configuration options to pass to the
12500 * {@link OO.ui.ButtonWidget decrementing button widget}.
12501 * @cfg {Object} [plusButton] Configuration options to pass to the
12502 * {@link OO.ui.ButtonWidget incrementing button widget}.
12503 * @cfg {number} [min=-Infinity] Minimum allowed value
12504 * @cfg {number} [max=Infinity] Maximum allowed value
12505 * @cfg {number|null} [step] If specified, the field only accepts values that are multiples of this.
12506 * @cfg {number} [buttonStep=step||1] Delta when using the buttons or up/down arrow keys.
12507 * Defaults to `step` if specified, otherwise `1`.
12508 * @cfg {number} [pageStep=10*buttonStep] Delta when using the page-up/page-down keys.
12509 * Defaults to 10 times `buttonStep`.
12510 * @cfg {boolean} [showButtons=true] Whether to show the plus and minus buttons.
12511 */
12512 OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
12513 var $field = $( '<div>' )
12514 .addClass( 'oo-ui-numberInputWidget-field' );
12515
12516 // Configuration initialization
12517 config = $.extend( {
12518 min: -Infinity,
12519 max: Infinity,
12520 showButtons: true
12521 }, config );
12522
12523 // For backward compatibility
12524 $.extend( config, config.input );
12525 this.input = this;
12526
12527 // Parent constructor
12528 OO.ui.NumberInputWidget.parent.call( this, $.extend( config, {
12529 type: 'number'
12530 } ) );
12531
12532 if ( config.showButtons ) {
12533 this.minusButton = new OO.ui.ButtonWidget( $.extend(
12534 {
12535 disabled: this.isDisabled(),
12536 tabIndex: -1,
12537 classes: [ 'oo-ui-numberInputWidget-minusButton' ],
12538 icon: 'subtract'
12539 },
12540 config.minusButton
12541 ) );
12542 this.minusButton.$element.attr( 'aria-hidden', 'true' );
12543 this.plusButton = new OO.ui.ButtonWidget( $.extend(
12544 {
12545 disabled: this.isDisabled(),
12546 tabIndex: -1,
12547 classes: [ 'oo-ui-numberInputWidget-plusButton' ],
12548 icon: 'add'
12549 },
12550 config.plusButton
12551 ) );
12552 this.plusButton.$element.attr( 'aria-hidden', 'true' );
12553 }
12554
12555 // Events
12556 this.$input.on( {
12557 keydown: this.onKeyDown.bind( this ),
12558 'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
12559 } );
12560 if ( config.showButtons ) {
12561 this.plusButton.connect( this, {
12562 click: [ 'onButtonClick', +1 ]
12563 } );
12564 this.minusButton.connect( this, {
12565 click: [ 'onButtonClick', -1 ]
12566 } );
12567 }
12568
12569 // Build the field
12570 $field.append( this.$input );
12571 if ( config.showButtons ) {
12572 $field
12573 .prepend( this.minusButton.$element )
12574 .append( this.plusButton.$element );
12575 }
12576
12577 // Initialization
12578 if ( config.allowInteger || config.isInteger ) {
12579 // Backward compatibility
12580 config.step = 1;
12581 }
12582 this.setRange( config.min, config.max );
12583 this.setStep( config.buttonStep, config.pageStep, config.step );
12584 // Set the validation method after we set step and range
12585 // so that it doesn't immediately call setValidityFlag
12586 this.setValidation( this.validateNumber.bind( this ) );
12587
12588 this.$element
12589 .addClass( 'oo-ui-numberInputWidget' )
12590 .toggleClass( 'oo-ui-numberInputWidget-buttoned', config.showButtons )
12591 .append( $field );
12592 };
12593
12594 /* Setup */
12595
12596 OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.TextInputWidget );
12597
12598 /* Methods */
12599
12600 // Backward compatibility
12601 OO.ui.NumberInputWidget.prototype.setAllowInteger = function ( flag ) {
12602 this.setStep( flag ? 1 : null );
12603 };
12604 // Backward compatibility
12605 OO.ui.NumberInputWidget.prototype.setIsInteger = OO.ui.NumberInputWidget.prototype.setAllowInteger;
12606
12607 // Backward compatibility
12608 OO.ui.NumberInputWidget.prototype.getAllowInteger = function () {
12609 return this.step === 1;
12610 };
12611 // Backward compatibility
12612 OO.ui.NumberInputWidget.prototype.getIsInteger = OO.ui.NumberInputWidget.prototype.getAllowInteger;
12613
12614 /**
12615 * Set the range of allowed values
12616 *
12617 * @param {number} min Minimum allowed value
12618 * @param {number} max Maximum allowed value
12619 */
12620 OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
12621 if ( min > max ) {
12622 throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
12623 }
12624 this.min = min;
12625 this.max = max;
12626 this.$input.attr( 'min', this.min );
12627 this.$input.attr( 'max', this.max );
12628 this.setValidityFlag();
12629 };
12630
12631 /**
12632 * Get the current range
12633 *
12634 * @return {number[]} Minimum and maximum values
12635 */
12636 OO.ui.NumberInputWidget.prototype.getRange = function () {
12637 return [ this.min, this.max ];
12638 };
12639
12640 /**
12641 * Set the stepping deltas
12642 *
12643 * @param {number} [buttonStep=step||1] Delta when using the buttons or up/down arrow keys.
12644 * Defaults to `step` if specified, otherwise `1`.
12645 * @param {number} [pageStep=10*buttonStep] Delta when using the page-up/page-down keys.
12646 * Defaults to 10 times `buttonStep`.
12647 * @param {number|null} [step] If specified, the field only accepts values that are multiples of this.
12648 */
12649 OO.ui.NumberInputWidget.prototype.setStep = function ( buttonStep, pageStep, step ) {
12650 if ( buttonStep === undefined ) {
12651 buttonStep = step || 1;
12652 }
12653 if ( pageStep === undefined ) {
12654 pageStep = 10 * buttonStep;
12655 }
12656 if ( step !== null && step <= 0 ) {
12657 throw new Error( 'Step value, if given, must be positive' );
12658 }
12659 if ( buttonStep <= 0 ) {
12660 throw new Error( 'Button step value must be positive' );
12661 }
12662 if ( pageStep <= 0 ) {
12663 throw new Error( 'Page step value must be positive' );
12664 }
12665 this.step = step;
12666 this.buttonStep = buttonStep;
12667 this.pageStep = pageStep;
12668 this.$input.attr( 'step', this.step || 'any' );
12669 this.setValidityFlag();
12670 };
12671
12672 /**
12673 * @inheritdoc
12674 */
12675 OO.ui.NumberInputWidget.prototype.setValue = function ( value ) {
12676 if ( value === '' ) {
12677 // Some browsers allow a value in the input even if there isn't one reported by $input.val()
12678 // so here we make sure an 'empty' value is actually displayed as such.
12679 this.$input.val( '' );
12680 }
12681 return OO.ui.NumberInputWidget.parent.prototype.setValue.call( this, value );
12682 };
12683
12684 /**
12685 * Get the current stepping values
12686 *
12687 * @return {number[]} Button step, page step, and validity step
12688 */
12689 OO.ui.NumberInputWidget.prototype.getStep = function () {
12690 return [ this.buttonStep, this.pageStep, this.step ];
12691 };
12692
12693 /**
12694 * Get the current value of the widget as a number
12695 *
12696 * @return {number} May be NaN, or an invalid number
12697 */
12698 OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
12699 return +this.getValue();
12700 };
12701
12702 /**
12703 * Adjust the value of the widget
12704 *
12705 * @param {number} delta Adjustment amount
12706 */
12707 OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
12708 var n, v = this.getNumericValue();
12709
12710 delta = +delta;
12711 if ( isNaN( delta ) || !isFinite( delta ) ) {
12712 throw new Error( 'Delta must be a finite number' );
12713 }
12714
12715 if ( isNaN( v ) ) {
12716 n = 0;
12717 } else {
12718 n = v + delta;
12719 n = Math.max( Math.min( n, this.max ), this.min );
12720 if ( this.step ) {
12721 n = Math.round( n / this.step ) * this.step;
12722 }
12723 }
12724
12725 if ( n !== v ) {
12726 this.setValue( n );
12727 }
12728 };
12729 /**
12730 * Validate input
12731 *
12732 * @private
12733 * @param {string} value Field value
12734 * @return {boolean}
12735 */
12736 OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
12737 var n = +value;
12738 if ( value === '' ) {
12739 return !this.isRequired();
12740 }
12741
12742 if ( isNaN( n ) || !isFinite( n ) ) {
12743 return false;
12744 }
12745
12746 if ( this.step && Math.floor( n / this.step ) !== n / this.step ) {
12747 return false;
12748 }
12749
12750 if ( n < this.min || n > this.max ) {
12751 return false;
12752 }
12753
12754 return true;
12755 };
12756
12757 /**
12758 * Handle mouse click events.
12759 *
12760 * @private
12761 * @param {number} dir +1 or -1
12762 */
12763 OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
12764 this.adjustValue( dir * this.buttonStep );
12765 };
12766
12767 /**
12768 * Handle mouse wheel events.
12769 *
12770 * @private
12771 * @param {jQuery.Event} event
12772 * @return {undefined/boolean} False to prevent default if event is handled
12773 */
12774 OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
12775 var delta = 0;
12776
12777 if ( !this.isDisabled() && this.$input.is( ':focus' ) ) {
12778 // Standard 'wheel' event
12779 if ( event.originalEvent.deltaMode !== undefined ) {
12780 this.sawWheelEvent = true;
12781 }
12782 if ( event.originalEvent.deltaY ) {
12783 delta = -event.originalEvent.deltaY;
12784 } else if ( event.originalEvent.deltaX ) {
12785 delta = event.originalEvent.deltaX;
12786 }
12787
12788 // Non-standard events
12789 if ( !this.sawWheelEvent ) {
12790 if ( event.originalEvent.wheelDeltaX ) {
12791 delta = -event.originalEvent.wheelDeltaX;
12792 } else if ( event.originalEvent.wheelDeltaY ) {
12793 delta = event.originalEvent.wheelDeltaY;
12794 } else if ( event.originalEvent.wheelDelta ) {
12795 delta = event.originalEvent.wheelDelta;
12796 } else if ( event.originalEvent.detail ) {
12797 delta = -event.originalEvent.detail;
12798 }
12799 }
12800
12801 if ( delta ) {
12802 delta = delta < 0 ? -1 : 1;
12803 this.adjustValue( delta * this.buttonStep );
12804 }
12805
12806 return false;
12807 }
12808 };
12809
12810 /**
12811 * Handle key down events.
12812 *
12813 * @private
12814 * @param {jQuery.Event} e Key down event
12815 * @return {undefined/boolean} False to prevent default if event is handled
12816 */
12817 OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
12818 if ( !this.isDisabled() ) {
12819 switch ( e.which ) {
12820 case OO.ui.Keys.UP:
12821 this.adjustValue( this.buttonStep );
12822 return false;
12823 case OO.ui.Keys.DOWN:
12824 this.adjustValue( -this.buttonStep );
12825 return false;
12826 case OO.ui.Keys.PAGEUP:
12827 this.adjustValue( this.pageStep );
12828 return false;
12829 case OO.ui.Keys.PAGEDOWN:
12830 this.adjustValue( -this.pageStep );
12831 return false;
12832 }
12833 }
12834 };
12835
12836 /**
12837 * @inheritdoc
12838 */
12839 OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
12840 // Parent method
12841 OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
12842
12843 if ( this.minusButton ) {
12844 this.minusButton.setDisabled( this.isDisabled() );
12845 }
12846 if ( this.plusButton ) {
12847 this.plusButton.setDisabled( this.isDisabled() );
12848 }
12849
12850 return this;
12851 };
12852
12853 }( OO ) );
12854
12855 //# sourceMappingURL=oojs-ui-core.js.map.json