OOUI: Bring forward UBN fix for DropdownInputWidget with MenuSectionOptionWidget
[lhc/web/wiklou.git] / resources / lib / ooui / oojs-ui-core.js
1 /*!
2 * OOUI v0.31.0
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-03-20T23:07:02Z
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,
215 * otherwise only match descendants
216 * @return {boolean} The node is in the list of target nodes
217 */
218 OO.ui.contains = function ( containers, contained, matchContainers ) {
219 var i;
220 if ( !Array.isArray( containers ) ) {
221 containers = [ containers ];
222 }
223 for ( i = containers.length - 1; i >= 0; i-- ) {
224 if (
225 ( matchContainers && contained === containers[ i ] ) ||
226 $.contains( containers[ i ], contained )
227 ) {
228 return true;
229 }
230 }
231 return false;
232 };
233
234 /**
235 * Return a function, that, as long as it continues to be invoked, will not
236 * be triggered. The function will be called after it stops being called for
237 * N milliseconds. If `immediate` is passed, trigger the function on the
238 * leading edge, instead of the trailing.
239 *
240 * Ported from: http://underscorejs.org/underscore.js
241 *
242 * @param {Function} func Function to debounce
243 * @param {number} [wait=0] Wait period in milliseconds
244 * @param {boolean} [immediate] Trigger on leading edge
245 * @return {Function} Debounced function
246 */
247 OO.ui.debounce = function ( func, wait, immediate ) {
248 var timeout;
249 return function () {
250 var context = this,
251 args = arguments,
252 later = function () {
253 timeout = null;
254 if ( !immediate ) {
255 func.apply( context, args );
256 }
257 };
258 if ( immediate && !timeout ) {
259 func.apply( context, args );
260 }
261 if ( !timeout || wait ) {
262 clearTimeout( timeout );
263 timeout = setTimeout( later, wait );
264 }
265 };
266 };
267
268 /**
269 * Puts a console warning with provided message.
270 *
271 * @param {string} message Message
272 */
273 OO.ui.warnDeprecation = function ( message ) {
274 if ( OO.getProp( window, 'console', 'warn' ) !== undefined ) {
275 // eslint-disable-next-line no-console
276 console.warn( message );
277 }
278 };
279
280 /**
281 * Returns a function, that, when invoked, will only be triggered at most once
282 * during a given window of time. If called again during that window, it will
283 * wait until the window ends and then trigger itself again.
284 *
285 * As it's not knowable to the caller whether the function will actually run
286 * when the wrapper is called, return values from the function are entirely
287 * discarded.
288 *
289 * @param {Function} func Function to throttle
290 * @param {number} wait Throttle window length, in milliseconds
291 * @return {Function} Throttled function
292 */
293 OO.ui.throttle = function ( func, wait ) {
294 var context, args, timeout,
295 previous = 0,
296 run = function () {
297 timeout = null;
298 previous = OO.ui.now();
299 func.apply( context, args );
300 };
301 return function () {
302 // Check how long it's been since the last time the function was
303 // called, and whether it's more or less than the requested throttle
304 // period. If it's less, run the function immediately. If it's more,
305 // set a timeout for the remaining time -- but don't replace an
306 // existing timeout, since that'd indefinitely prolong the wait.
307 var remaining = wait - ( OO.ui.now() - previous );
308 context = this;
309 args = arguments;
310 if ( remaining <= 0 ) {
311 // Note: unless wait was ridiculously large, this means we'll
312 // automatically run the first time the function was called in a
313 // given period. (If you provide a wait period larger than the
314 // current Unix timestamp, you *deserve* unexpected behavior.)
315 clearTimeout( timeout );
316 run();
317 } else if ( !timeout ) {
318 timeout = setTimeout( run, remaining );
319 }
320 };
321 };
322
323 /**
324 * A (possibly faster) way to get the current timestamp as an integer.
325 *
326 * @return {number} Current timestamp, in milliseconds since the Unix epoch
327 */
328 OO.ui.now = Date.now || function () {
329 return new Date().getTime();
330 };
331
332 /**
333 * Reconstitute a JavaScript object corresponding to a widget created by
334 * the PHP implementation.
335 *
336 * This is an alias for `OO.ui.Element.static.infuse()`.
337 *
338 * @param {string|HTMLElement|jQuery} idOrNode
339 * A DOM id (if a string) or node for the widget to infuse.
340 * @param {Object} [config] Configuration options
341 * @return {OO.ui.Element}
342 * The `OO.ui.Element` corresponding to this (infusable) document node.
343 */
344 OO.ui.infuse = function ( idOrNode, config ) {
345 return OO.ui.Element.static.infuse( idOrNode, config );
346 };
347
348 ( function () {
349 /**
350 * Message store for the default implementation of OO.ui.msg.
351 *
352 * Environments that provide a localization system should not use this, but should override
353 * OO.ui.msg altogether.
354 *
355 * @private
356 */
357 var messages = {
358 // Tool tip for a button that moves items in a list down one place
359 'ooui-outline-control-move-down': 'Move item down',
360 // Tool tip for a button that moves items in a list up one place
361 'ooui-outline-control-move-up': 'Move item up',
362 // Tool tip for a button that removes items from a list
363 'ooui-outline-control-remove': 'Remove item',
364 // Label for the toolbar group that contains a list of all other available tools
365 'ooui-toolbar-more': 'More',
366 // Label for the fake tool that expands the full list of tools in a toolbar group
367 'ooui-toolgroup-expand': 'More',
368 // Label for the fake tool that collapses the full list of tools in a toolbar group
369 'ooui-toolgroup-collapse': 'Fewer',
370 // Default label for the tooltip for the button that removes a tag item
371 'ooui-item-remove': 'Remove',
372 // Default label for the accept button of a confirmation dialog
373 'ooui-dialog-message-accept': 'OK',
374 // Default label for the reject button of a confirmation dialog
375 'ooui-dialog-message-reject': 'Cancel',
376 // Title for process dialog error description
377 'ooui-dialog-process-error': 'Something went wrong',
378 // Label for process dialog dismiss error button, visible when describing errors
379 'ooui-dialog-process-dismiss': 'Dismiss',
380 // Label for process dialog retry action button, visible when describing only recoverable
381 // errors
382 'ooui-dialog-process-retry': 'Try again',
383 // Label for process dialog retry action button, visible when describing only warnings
384 'ooui-dialog-process-continue': 'Continue',
385 // Label for button in combobox input that triggers its dropdown
386 'ooui-combobox-button-label': 'Dropdown for combobox',
387 // Label for the file selection widget's select file button
388 'ooui-selectfile-button-select': 'Select a file',
389 // Label for the file selection widget if file selection is not supported
390 'ooui-selectfile-not-supported': 'File selection is not supported',
391 // Label for the file selection widget when no file is currently selected
392 'ooui-selectfile-placeholder': 'No file is selected',
393 // Label for the file selection widget's drop target
394 'ooui-selectfile-dragdrop-placeholder': 'Drop file here',
395 // Label for the help icon attached to a form field
396 'ooui-field-help': 'Help'
397 };
398
399 /**
400 * Get a localized message.
401 *
402 * After the message key, message parameters may optionally be passed. In the default
403 * implementation, any occurrences of $1 are replaced with the first parameter, $2 with the
404 * second parameter, etc.
405 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long
406 * as they support unnamed, ordered message parameters.
407 *
408 * In environments that provide a localization system, this function should be overridden to
409 * return the message translated in the user's language. The default implementation always
410 * returns English messages. An example of doing this with
411 * [jQuery.i18n](https://github.com/wikimedia/jquery.i18n) follows.
412 *
413 * @example
414 * var i, iLen, button,
415 * messagePath = 'oojs-ui/dist/i18n/',
416 * languages = [ $.i18n().locale, 'ur', 'en' ],
417 * languageMap = {};
418 *
419 * for ( i = 0, iLen = languages.length; i < iLen; i++ ) {
420 * languageMap[ languages[ i ] ] = messagePath + languages[ i ].toLowerCase() + '.json';
421 * }
422 *
423 * $.i18n().load( languageMap ).done( function() {
424 * // Replace the built-in `msg` only once we've loaded the internationalization.
425 * // OOUI uses `OO.ui.deferMsg` for all initially-loaded messages. So long as
426 * // you put off creating any widgets until this promise is complete, no English
427 * // will be displayed.
428 * OO.ui.msg = $.i18n;
429 *
430 * // A button displaying "OK" in the default locale
431 * button = new OO.ui.ButtonWidget( {
432 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
433 * icon: 'check'
434 * } );
435 * $( document.body ).append( button.$element );
436 *
437 * // A button displaying "OK" in Urdu
438 * $.i18n().locale = 'ur';
439 * button = new OO.ui.ButtonWidget( {
440 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
441 * icon: 'check'
442 * } );
443 * $( document.body ).append( button.$element );
444 * } );
445 *
446 * @param {string} key Message key
447 * @param {...Mixed} [params] Message parameters
448 * @return {string} Translated message with parameters substituted
449 */
450 OO.ui.msg = function ( key ) {
451 var message = messages[ key ],
452 params = Array.prototype.slice.call( arguments, 1 );
453 if ( typeof message === 'string' ) {
454 // Perform $1 substitution
455 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
456 var i = parseInt( n, 10 );
457 return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n;
458 } );
459 } else {
460 // Return placeholder if message not found
461 message = '[' + key + ']';
462 }
463 return message;
464 };
465 }() );
466
467 /**
468 * Package a message and arguments for deferred resolution.
469 *
470 * Use this when you are statically specifying a message and the message may not yet be present.
471 *
472 * @param {string} key Message key
473 * @param {...Mixed} [params] Message parameters
474 * @return {Function} Function that returns the resolved message when executed
475 */
476 OO.ui.deferMsg = function () {
477 var args = arguments;
478 return function () {
479 return OO.ui.msg.apply( OO.ui, args );
480 };
481 };
482
483 /**
484 * Resolve a message.
485 *
486 * If the message is a function it will be executed, otherwise it will pass through directly.
487 *
488 * @param {Function|string} msg Deferred message, or message text
489 * @return {string} Resolved message
490 */
491 OO.ui.resolveMsg = function ( msg ) {
492 if ( typeof msg === 'function' ) {
493 return msg();
494 }
495 return msg;
496 };
497
498 /**
499 * @param {string} url
500 * @return {boolean}
501 */
502 OO.ui.isSafeUrl = function ( url ) {
503 // Keep this function in sync with php/Tag.php
504 var i, protocolWhitelist;
505
506 function stringStartsWith( haystack, needle ) {
507 return haystack.substr( 0, needle.length ) === needle;
508 }
509
510 protocolWhitelist = [
511 'bitcoin', 'ftp', 'ftps', 'geo', 'git', 'gopher', 'http', 'https', 'irc', 'ircs',
512 'magnet', 'mailto', 'mms', 'news', 'nntp', 'redis', 'sftp', 'sip', 'sips', 'sms', 'ssh',
513 'svn', 'tel', 'telnet', 'urn', 'worldwind', 'xmpp'
514 ];
515
516 if ( url === '' ) {
517 return true;
518 }
519
520 for ( i = 0; i < protocolWhitelist.length; i++ ) {
521 if ( stringStartsWith( url, protocolWhitelist[ i ] + ':' ) ) {
522 return true;
523 }
524 }
525
526 // This matches '//' too
527 if ( stringStartsWith( url, '/' ) || stringStartsWith( url, './' ) ) {
528 return true;
529 }
530 if ( stringStartsWith( url, '?' ) || stringStartsWith( url, '#' ) ) {
531 return true;
532 }
533
534 return false;
535 };
536
537 /**
538 * Check if the user has a 'mobile' device.
539 *
540 * For our purposes this means the user is primarily using an
541 * on-screen keyboard, touch input instead of a mouse and may
542 * have a physically small display.
543 *
544 * It is left up to implementors to decide how to compute this
545 * so the default implementation always returns false.
546 *
547 * @return {boolean} User is on a mobile device
548 */
549 OO.ui.isMobile = function () {
550 return false;
551 };
552
553 /**
554 * Get the additional spacing that should be taken into account when displaying elements that are
555 * clipped to the viewport, e.g. dropdown menus and popups. This is meant to be overridden to avoid
556 * such menus overlapping any fixed headers/toolbars/navigation used by the site.
557 *
558 * @return {Object} Object with the properties 'top', 'right', 'bottom', 'left', each representing
559 * the extra spacing from that edge of viewport (in pixels)
560 */
561 OO.ui.getViewportSpacing = function () {
562 return {
563 top: 0,
564 right: 0,
565 bottom: 0,
566 left: 0
567 };
568 };
569
570 /**
571 * Get the default overlay, which is used by various widgets when they are passed `$overlay: true`.
572 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
573 *
574 * @return {jQuery} Default overlay node
575 */
576 OO.ui.getDefaultOverlay = function () {
577 if ( !OO.ui.$defaultOverlay ) {
578 OO.ui.$defaultOverlay = $( '<div>' ).addClass( 'oo-ui-defaultOverlay' );
579 $( document.body ).append( OO.ui.$defaultOverlay );
580 }
581 return OO.ui.$defaultOverlay;
582 };
583
584 /*!
585 * Mixin namespace.
586 */
587
588 /**
589 * Namespace for OOUI mixins.
590 *
591 * Mixins are named according to the type of object they are intended to
592 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
593 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
594 * is intended to be mixed in to an instance of OO.ui.Widget.
595 *
596 * @class
597 * @singleton
598 */
599 OO.ui.mixin = {};
600
601 /**
602 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
603 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not
604 * have events connected to them and can't be interacted with.
605 *
606 * @abstract
607 * @class
608 *
609 * @constructor
610 * @param {Object} [config] Configuration options
611 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are
612 * added to the top level (e.g., the outermost div) of the element. See the
613 * [OOUI documentation on MediaWiki][2] for an example.
614 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches#cssExample
615 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
616 * @cfg {string} [text] Text to insert
617 * @cfg {Array} [content] An array of content elements to append (after #text).
618 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
619 * Instances of OO.ui.Element will have their $element appended.
620 * @cfg {jQuery} [$content] Content elements to append (after #text).
621 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
622 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number,
623 * array, object).
624 * Data can also be specified with the #setData method.
625 */
626 OO.ui.Element = function OoUiElement( config ) {
627 if ( OO.ui.isDemo ) {
628 this.initialConfig = config;
629 }
630 // Configuration initialization
631 config = config || {};
632
633 // Properties
634 this.$ = function () {
635 OO.ui.warnDeprecation( 'this.$ is deprecated, use global $ instead' );
636 return $.apply( this, arguments );
637 };
638 this.elementId = null;
639 this.visible = true;
640 this.data = config.data;
641 this.$element = config.$element ||
642 $( document.createElement( this.getTagName() ) );
643 this.elementGroup = null;
644
645 // Initialization
646 if ( Array.isArray( config.classes ) ) {
647 this.$element.addClass( config.classes );
648 }
649 if ( config.id ) {
650 this.setElementId( config.id );
651 }
652 if ( config.text ) {
653 this.$element.text( config.text );
654 }
655 if ( config.content ) {
656 // The `content` property treats plain strings as text; use an
657 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
658 // appropriate $element appended.
659 this.$element.append( config.content.map( function ( v ) {
660 if ( typeof v === 'string' ) {
661 // Escape string so it is properly represented in HTML.
662 // Don't create empty text nodes for empty strings.
663 return v ? document.createTextNode( v ) : undefined;
664 } else if ( v instanceof OO.ui.HtmlSnippet ) {
665 // Bypass escaping.
666 return v.toString();
667 } else if ( v instanceof OO.ui.Element ) {
668 return v.$element;
669 }
670 return v;
671 } ) );
672 }
673 if ( config.$content ) {
674 // The `$content` property treats plain strings as HTML.
675 this.$element.append( config.$content );
676 }
677 };
678
679 /* Setup */
680
681 OO.initClass( OO.ui.Element );
682
683 /* Static Properties */
684
685 /**
686 * The name of the HTML tag used by the element.
687 *
688 * The static value may be ignored if the #getTagName method is overridden.
689 *
690 * @static
691 * @inheritable
692 * @property {string}
693 */
694 OO.ui.Element.static.tagName = 'div';
695
696 /* Static Methods */
697
698 /**
699 * Reconstitute a JavaScript object corresponding to a widget created
700 * by the PHP implementation.
701 *
702 * @param {string|HTMLElement|jQuery} idOrNode
703 * A DOM id (if a string) or node for the widget to infuse.
704 * @param {Object} [config] Configuration options
705 * @return {OO.ui.Element}
706 * The `OO.ui.Element` corresponding to this (infusable) document node.
707 * For `Tag` objects emitted on the HTML side (used occasionally for content)
708 * the value returned is a newly-created Element wrapping around the existing
709 * DOM node.
710 */
711 OO.ui.Element.static.infuse = function ( idOrNode, config ) {
712 var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, config, false );
713
714 if ( typeof idOrNode === 'string' ) {
715 // IDs deprecated since 0.29.7
716 OO.ui.warnDeprecation(
717 'Passing a string ID to infuse is deprecated. Use an HTMLElement or jQuery collection instead.'
718 );
719 }
720 // Verify that the type matches up.
721 // FIXME: uncomment after T89721 is fixed, see T90929.
722 /*
723 if ( !( obj instanceof this['class'] ) ) {
724 throw new Error( 'Infusion type mismatch!' );
725 }
726 */
727 return obj;
728 };
729
730 /**
731 * Implementation helper for `infuse`; skips the type check and has an
732 * extra property so that only the top-level invocation touches the DOM.
733 *
734 * @private
735 * @param {string|HTMLElement|jQuery} idOrNode
736 * @param {Object} [config] Configuration options
737 * @param {jQuery.Promise} [domPromise] A promise that will be resolved
738 * when the top-level widget of this infusion is inserted into DOM,
739 * replacing the original node; only used internally.
740 * @return {OO.ui.Element}
741 */
742 OO.ui.Element.static.unsafeInfuse = function ( idOrNode, config, domPromise ) {
743 // look for a cached result of a previous infusion.
744 var id, $elem, error, data, cls, parts, parent, obj, top, state, infusedChildren;
745 if ( typeof idOrNode === 'string' ) {
746 id = idOrNode;
747 $elem = $( document.getElementById( id ) );
748 } else {
749 $elem = $( idOrNode );
750 id = $elem.attr( 'id' );
751 }
752 if ( !$elem.length ) {
753 if ( typeof idOrNode === 'string' ) {
754 error = 'Widget not found: ' + idOrNode;
755 } else if ( idOrNode && idOrNode.selector ) {
756 error = 'Widget not found: ' + idOrNode.selector;
757 } else {
758 error = 'Widget not found';
759 }
760 throw new Error( error );
761 }
762 if ( $elem[ 0 ].oouiInfused ) {
763 $elem = $elem[ 0 ].oouiInfused;
764 }
765 data = $elem.data( 'ooui-infused' );
766 if ( data ) {
767 // cached!
768 if ( data === true ) {
769 throw new Error( 'Circular dependency! ' + id );
770 }
771 if ( domPromise ) {
772 // Pick up dynamic state, like focus, value of form inputs, scroll position, etc.
773 state = data.constructor.static.gatherPreInfuseState( $elem, data );
774 // Restore dynamic state after the new element is re-inserted into DOM under
775 // infused parent.
776 domPromise.done( data.restorePreInfuseState.bind( data, state ) );
777 infusedChildren = $elem.data( 'ooui-infused-children' );
778 if ( infusedChildren && infusedChildren.length ) {
779 infusedChildren.forEach( function ( data ) {
780 var state = data.constructor.static.gatherPreInfuseState( $elem, data );
781 domPromise.done( data.restorePreInfuseState.bind( data, state ) );
782 } );
783 }
784 }
785 return data;
786 }
787 data = $elem.attr( 'data-ooui' );
788 if ( !data ) {
789 throw new Error( 'No infusion data found: ' + id );
790 }
791 try {
792 data = JSON.parse( data );
793 } catch ( _ ) {
794 data = null;
795 }
796 if ( !( data && data._ ) ) {
797 throw new Error( 'No valid infusion data found: ' + id );
798 }
799 if ( data._ === 'Tag' ) {
800 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
801 return new OO.ui.Element( $.extend( {}, config, { $element: $elem } ) );
802 }
803 parts = data._.split( '.' );
804 cls = OO.getProp.apply( OO, [ window ].concat( parts ) );
805 if ( cls === undefined ) {
806 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
807 }
808
809 // Verify that we're creating an OO.ui.Element instance
810 parent = cls.parent;
811
812 while ( parent !== undefined ) {
813 if ( parent === OO.ui.Element ) {
814 // Safe
815 break;
816 }
817
818 parent = parent.parent;
819 }
820
821 if ( parent !== OO.ui.Element ) {
822 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
823 }
824
825 if ( !domPromise ) {
826 top = $.Deferred();
827 domPromise = top.promise();
828 }
829 $elem.data( 'ooui-infused', true ); // prevent loops
830 data.id = id; // implicit
831 infusedChildren = [];
832 data = OO.copy( data, null, function deserialize( value ) {
833 var infused;
834 if ( OO.isPlainObject( value ) ) {
835 if ( value.tag ) {
836 infused = OO.ui.Element.static.unsafeInfuse( value.tag, config, domPromise );
837 infusedChildren.push( infused );
838 // Flatten the structure
839 infusedChildren.push.apply(
840 infusedChildren,
841 infused.$element.data( 'ooui-infused-children' ) || []
842 );
843 infused.$element.removeData( 'ooui-infused-children' );
844 return infused;
845 }
846 if ( value.html !== undefined ) {
847 return new OO.ui.HtmlSnippet( value.html );
848 }
849 }
850 } );
851 // allow widgets to reuse parts of the DOM
852 data = cls.static.reusePreInfuseDOM( $elem[ 0 ], data );
853 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
854 state = cls.static.gatherPreInfuseState( $elem[ 0 ], data );
855 // rebuild widget
856 // eslint-disable-next-line new-cap
857 obj = new cls( $.extend( {}, config, data ) );
858 // If anyone is holding a reference to the old DOM element,
859 // let's allow them to OO.ui.infuse() it and do what they expect, see T105828.
860 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
861 $elem[ 0 ].oouiInfused = obj.$element;
862 // now replace old DOM with this new DOM.
863 if ( top ) {
864 // An efficient constructor might be able to reuse the entire DOM tree of the original
865 // element, so only mutate the DOM if we need to.
866 if ( $elem[ 0 ] !== obj.$element[ 0 ] ) {
867 $elem.replaceWith( obj.$element );
868 }
869 top.resolve();
870 }
871 obj.$element.data( 'ooui-infused', obj );
872 obj.$element.data( 'ooui-infused-children', infusedChildren );
873 // set the 'data-ooui' attribute so we can identify infused widgets
874 obj.$element.attr( 'data-ooui', '' );
875 // restore dynamic state after the new element is inserted into DOM
876 domPromise.done( obj.restorePreInfuseState.bind( obj, state ) );
877 return obj;
878 };
879
880 /**
881 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
882 *
883 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
884 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
885 * constructor, which will be given the enhanced config.
886 *
887 * @protected
888 * @param {HTMLElement} node
889 * @param {Object} config
890 * @return {Object}
891 */
892 OO.ui.Element.static.reusePreInfuseDOM = function ( node, config ) {
893 return config;
894 };
895
896 /**
897 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of an HTML DOM
898 * node (and its children) that represent an Element of the same class and the given configuration,
899 * generated by the PHP implementation.
900 *
901 * This method is called just before `node` is detached from the DOM. The return value of this
902 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
903 * is inserted into DOM to replace `node`.
904 *
905 * @protected
906 * @param {HTMLElement} node
907 * @param {Object} config
908 * @return {Object}
909 */
910 OO.ui.Element.static.gatherPreInfuseState = function () {
911 return {};
912 };
913
914 /**
915 * Get a jQuery function within a specific document.
916 *
917 * @static
918 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
919 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
920 * not in an iframe
921 * @return {Function} Bound jQuery function
922 */
923 OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
924 function wrapper( selector ) {
925 return $( selector, wrapper.context );
926 }
927
928 wrapper.context = this.getDocument( context );
929
930 if ( $iframe ) {
931 wrapper.$iframe = $iframe;
932 }
933
934 return wrapper;
935 };
936
937 /**
938 * Get the document of an element.
939 *
940 * @static
941 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
942 * @return {HTMLDocument|null} Document object
943 */
944 OO.ui.Element.static.getDocument = function ( obj ) {
945 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
946 return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
947 // Empty jQuery selections might have a context
948 obj.context ||
949 // HTMLElement
950 obj.ownerDocument ||
951 // Window
952 obj.document ||
953 // HTMLDocument
954 ( obj.nodeType === Node.DOCUMENT_NODE && obj ) ||
955 null;
956 };
957
958 /**
959 * Get the window of an element or document.
960 *
961 * @static
962 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
963 * @return {Window} Window object
964 */
965 OO.ui.Element.static.getWindow = function ( obj ) {
966 var doc = this.getDocument( obj );
967 return doc.defaultView;
968 };
969
970 /**
971 * Get the direction of an element or document.
972 *
973 * @static
974 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
975 * @return {string} Text direction, either 'ltr' or 'rtl'
976 */
977 OO.ui.Element.static.getDir = function ( obj ) {
978 var isDoc, isWin;
979
980 if ( obj instanceof $ ) {
981 obj = obj[ 0 ];
982 }
983 isDoc = obj.nodeType === Node.DOCUMENT_NODE;
984 isWin = obj.document !== undefined;
985 if ( isDoc || isWin ) {
986 if ( isWin ) {
987 obj = obj.document;
988 }
989 obj = obj.body;
990 }
991 return $( obj ).css( 'direction' );
992 };
993
994 /**
995 * Get the offset between two frames.
996 *
997 * TODO: Make this function not use recursion.
998 *
999 * @static
1000 * @param {Window} from Window of the child frame
1001 * @param {Window} [to=window] Window of the parent frame
1002 * @param {Object} [offset] Offset to start with, used internally
1003 * @return {Object} Offset object, containing left and top properties
1004 */
1005 OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
1006 var i, len, frames, frame, rect;
1007
1008 if ( !to ) {
1009 to = window;
1010 }
1011 if ( !offset ) {
1012 offset = { top: 0, left: 0 };
1013 }
1014 if ( from.parent === from ) {
1015 return offset;
1016 }
1017
1018 // Get iframe element
1019 frames = from.parent.document.getElementsByTagName( 'iframe' );
1020 for ( i = 0, len = frames.length; i < len; i++ ) {
1021 if ( frames[ i ].contentWindow === from ) {
1022 frame = frames[ i ];
1023 break;
1024 }
1025 }
1026
1027 // Recursively accumulate offset values
1028 if ( frame ) {
1029 rect = frame.getBoundingClientRect();
1030 offset.left += rect.left;
1031 offset.top += rect.top;
1032 if ( from !== to ) {
1033 this.getFrameOffset( from.parent, offset );
1034 }
1035 }
1036 return offset;
1037 };
1038
1039 /**
1040 * Get the offset between two elements.
1041 *
1042 * The two elements may be in a different frame, but in that case the frame $element is in must
1043 * be contained in the frame $anchor is in.
1044 *
1045 * @static
1046 * @param {jQuery} $element Element whose position to get
1047 * @param {jQuery} $anchor Element to get $element's position relative to
1048 * @return {Object} Translated position coordinates, containing top and left properties
1049 */
1050 OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
1051 var iframe, iframePos,
1052 pos = $element.offset(),
1053 anchorPos = $anchor.offset(),
1054 elementDocument = this.getDocument( $element ),
1055 anchorDocument = this.getDocument( $anchor );
1056
1057 // If $element isn't in the same document as $anchor, traverse up
1058 while ( elementDocument !== anchorDocument ) {
1059 iframe = elementDocument.defaultView.frameElement;
1060 if ( !iframe ) {
1061 throw new Error( '$element frame is not contained in $anchor frame' );
1062 }
1063 iframePos = $( iframe ).offset();
1064 pos.left += iframePos.left;
1065 pos.top += iframePos.top;
1066 elementDocument = iframe.ownerDocument;
1067 }
1068 pos.left -= anchorPos.left;
1069 pos.top -= anchorPos.top;
1070 return pos;
1071 };
1072
1073 /**
1074 * Get element border sizes.
1075 *
1076 * @static
1077 * @param {HTMLElement} el Element to measure
1078 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1079 */
1080 OO.ui.Element.static.getBorders = function ( el ) {
1081 var doc = el.ownerDocument,
1082 win = doc.defaultView,
1083 style = win.getComputedStyle( el, null ),
1084 $el = $( el ),
1085 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
1086 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
1087 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
1088 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
1089
1090 return {
1091 top: top,
1092 left: left,
1093 bottom: bottom,
1094 right: right
1095 };
1096 };
1097
1098 /**
1099 * Get dimensions of an element or window.
1100 *
1101 * @static
1102 * @param {HTMLElement|Window} el Element to measure
1103 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1104 */
1105 OO.ui.Element.static.getDimensions = function ( el ) {
1106 var $el, $win,
1107 doc = el.ownerDocument || el.document,
1108 win = doc.defaultView;
1109
1110 if ( win === el || el === doc.documentElement ) {
1111 $win = $( win );
1112 return {
1113 borders: { top: 0, left: 0, bottom: 0, right: 0 },
1114 scroll: {
1115 top: $win.scrollTop(),
1116 left: $win.scrollLeft()
1117 },
1118 scrollbar: { right: 0, bottom: 0 },
1119 rect: {
1120 top: 0,
1121 left: 0,
1122 bottom: $win.innerHeight(),
1123 right: $win.innerWidth()
1124 }
1125 };
1126 } else {
1127 $el = $( el );
1128 return {
1129 borders: this.getBorders( el ),
1130 scroll: {
1131 top: $el.scrollTop(),
1132 left: $el.scrollLeft()
1133 },
1134 scrollbar: {
1135 right: $el.innerWidth() - el.clientWidth,
1136 bottom: $el.innerHeight() - el.clientHeight
1137 },
1138 rect: el.getBoundingClientRect()
1139 };
1140 }
1141 };
1142
1143 /**
1144 * Get the number of pixels that an element's content is scrolled to the left.
1145 *
1146 * Adapted from <https://github.com/othree/jquery.rtl-scroll-type>.
1147 * Original code copyright 2012 Wei-Ko Kao, licensed under the MIT License.
1148 *
1149 * This function smooths out browser inconsistencies (nicely described in the README at
1150 * <https://github.com/othree/jquery.rtl-scroll-type>) and produces a result consistent
1151 * with Firefox's 'scrollLeft', which seems the sanest.
1152 *
1153 * @static
1154 * @method
1155 * @param {HTMLElement|Window} el Element to measure
1156 * @return {number} Scroll position from the left.
1157 * If the element's direction is LTR, this is a positive number between `0` (initial scroll
1158 * position) and `el.scrollWidth - el.clientWidth` (furthest possible scroll position).
1159 * If the element's direction is RTL, this is a negative number between `0` (initial scroll
1160 * position) and `-el.scrollWidth + el.clientWidth` (furthest possible scroll position).
1161 */
1162 OO.ui.Element.static.getScrollLeft = ( function () {
1163 var rtlScrollType = null;
1164
1165 function test() {
1166 var $definer = $( '<div>' ).attr( {
1167 dir: 'rtl',
1168 style: 'font-size: 14px; width: 4px; height: 1px; position: absolute; top: -1000px; overflow: scroll;'
1169 } ).text( 'ABCD' ),
1170 definer = $definer[ 0 ];
1171
1172 $definer.appendTo( 'body' );
1173 if ( definer.scrollLeft > 0 ) {
1174 // Safari, Chrome
1175 rtlScrollType = 'default';
1176 } else {
1177 definer.scrollLeft = 1;
1178 if ( definer.scrollLeft === 0 ) {
1179 // Firefox, old Opera
1180 rtlScrollType = 'negative';
1181 } else {
1182 // Internet Explorer, Edge
1183 rtlScrollType = 'reverse';
1184 }
1185 }
1186 $definer.remove();
1187 }
1188
1189 return function getScrollLeft( el ) {
1190 var isRoot = el.window === el ||
1191 el === el.ownerDocument.body ||
1192 el === el.ownerDocument.documentElement,
1193 scrollLeft = isRoot ? $( window ).scrollLeft() : el.scrollLeft,
1194 // All browsers use the correct scroll type ('negative') on the root, so don't
1195 // do any fixups when looking at the root element
1196 direction = isRoot ? 'ltr' : $( el ).css( 'direction' );
1197
1198 if ( direction === 'rtl' ) {
1199 if ( rtlScrollType === null ) {
1200 test();
1201 }
1202 if ( rtlScrollType === 'reverse' ) {
1203 scrollLeft = -scrollLeft;
1204 } else if ( rtlScrollType === 'default' ) {
1205 scrollLeft = scrollLeft - el.scrollWidth + el.clientWidth;
1206 }
1207 }
1208
1209 return scrollLeft;
1210 };
1211 }() );
1212
1213 /**
1214 * Get the root scrollable element of given element's document.
1215 *
1216 * On Blink-based browsers (Chrome etc.), `document.documentElement` can't be used to get or set
1217 * the scrollTop property; instead we have to use `document.body`. Changing and testing the value
1218 * lets us use 'body' or 'documentElement' based on what is working.
1219 *
1220 * https://code.google.com/p/chromium/issues/detail?id=303131
1221 *
1222 * @static
1223 * @param {HTMLElement} el Element to find root scrollable parent for
1224 * @return {HTMLElement} Scrollable parent, `document.body` or `document.documentElement`
1225 * depending on browser
1226 */
1227 OO.ui.Element.static.getRootScrollableElement = function ( el ) {
1228 var scrollTop, body;
1229
1230 if ( OO.ui.scrollableElement === undefined ) {
1231 body = el.ownerDocument.body;
1232 scrollTop = body.scrollTop;
1233 body.scrollTop = 1;
1234
1235 // In some browsers (observed in Chrome 56 on Linux Mint 18.1),
1236 // body.scrollTop doesn't become exactly 1, but a fractional value like 0.76
1237 if ( Math.round( body.scrollTop ) === 1 ) {
1238 body.scrollTop = scrollTop;
1239 OO.ui.scrollableElement = 'body';
1240 } else {
1241 OO.ui.scrollableElement = 'documentElement';
1242 }
1243 }
1244
1245 return el.ownerDocument[ OO.ui.scrollableElement ];
1246 };
1247
1248 /**
1249 * Get closest scrollable container.
1250 *
1251 * Traverses up until either a scrollable element or the root is reached, in which case the root
1252 * scrollable element will be returned (see #getRootScrollableElement).
1253 *
1254 * @static
1255 * @param {HTMLElement} el Element to find scrollable container for
1256 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1257 * @return {HTMLElement} Closest scrollable container
1258 */
1259 OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
1260 var i, val,
1261 // Browsers do not correctly return the computed value of 'overflow' when 'overflow-x' and
1262 // 'overflow-y' have different values, so we need to check the separate properties.
1263 props = [ 'overflow-x', 'overflow-y' ],
1264 $parent = $( el ).parent();
1265
1266 if ( dimension === 'x' || dimension === 'y' ) {
1267 props = [ 'overflow-' + dimension ];
1268 }
1269
1270 // Special case for the document root (which doesn't really have any scrollable container,
1271 // since it is the ultimate scrollable container, but this is probably saner than null or
1272 // exception).
1273 if ( $( el ).is( 'html, body' ) ) {
1274 return this.getRootScrollableElement( el );
1275 }
1276
1277 while ( $parent.length ) {
1278 if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
1279 return $parent[ 0 ];
1280 }
1281 i = props.length;
1282 while ( i-- ) {
1283 val = $parent.css( props[ i ] );
1284 // We assume that elements with 'overflow' (in any direction) set to 'hidden' will
1285 // never be scrolled in that direction, but they can actually be scrolled
1286 // programatically. The user can unintentionally perform a scroll in such case even if
1287 // the application doesn't scroll programatically, e.g. when jumping to an anchor, or
1288 // when using built-in find functionality.
1289 // This could cause funny issues...
1290 if ( val === 'auto' || val === 'scroll' ) {
1291 return $parent[ 0 ];
1292 }
1293 }
1294 $parent = $parent.parent();
1295 }
1296 // The element is unattached... return something mostly sane
1297 return this.getRootScrollableElement( el );
1298 };
1299
1300 /**
1301 * Scroll element into view.
1302 *
1303 * @static
1304 * @param {HTMLElement} el Element to scroll into view
1305 * @param {Object} [config] Configuration options
1306 * @param {string} [config.duration='fast'] jQuery animation duration value
1307 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1308 * to scroll in both directions
1309 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1310 */
1311 OO.ui.Element.static.scrollIntoView = function ( el, config ) {
1312 var position, animations, container, $container, elementDimensions, containerDimensions,
1313 $window,
1314 deferred = $.Deferred();
1315
1316 // Configuration initialization
1317 config = config || {};
1318
1319 animations = {};
1320 container = this.getClosestScrollableContainer( el, config.direction );
1321 $container = $( container );
1322 elementDimensions = this.getDimensions( el );
1323 containerDimensions = this.getDimensions( container );
1324 $window = $( this.getWindow( el ) );
1325
1326 // Compute the element's position relative to the container
1327 if ( $container.is( 'html, body' ) ) {
1328 // If the scrollable container is the root, this is easy
1329 position = {
1330 top: elementDimensions.rect.top,
1331 bottom: $window.innerHeight() - elementDimensions.rect.bottom,
1332 left: elementDimensions.rect.left,
1333 right: $window.innerWidth() - elementDimensions.rect.right
1334 };
1335 } else {
1336 // Otherwise, we have to subtract el's coordinates from container's coordinates
1337 position = {
1338 top: elementDimensions.rect.top -
1339 ( containerDimensions.rect.top + containerDimensions.borders.top ),
1340 bottom: containerDimensions.rect.bottom - containerDimensions.borders.bottom -
1341 containerDimensions.scrollbar.bottom - elementDimensions.rect.bottom,
1342 left: elementDimensions.rect.left -
1343 ( containerDimensions.rect.left + containerDimensions.borders.left ),
1344 right: containerDimensions.rect.right - containerDimensions.borders.right -
1345 containerDimensions.scrollbar.right - elementDimensions.rect.right
1346 };
1347 }
1348
1349 if ( !config.direction || config.direction === 'y' ) {
1350 if ( position.top < 0 ) {
1351 animations.scrollTop = containerDimensions.scroll.top + position.top;
1352 } else if ( position.top > 0 && position.bottom < 0 ) {
1353 animations.scrollTop = containerDimensions.scroll.top +
1354 Math.min( position.top, -position.bottom );
1355 }
1356 }
1357 if ( !config.direction || config.direction === 'x' ) {
1358 if ( position.left < 0 ) {
1359 animations.scrollLeft = containerDimensions.scroll.left + position.left;
1360 } else if ( position.left > 0 && position.right < 0 ) {
1361 animations.scrollLeft = containerDimensions.scroll.left +
1362 Math.min( position.left, -position.right );
1363 }
1364 }
1365 if ( !$.isEmptyObject( animations ) ) {
1366 // eslint-disable-next-line no-jquery/no-animate
1367 $container.stop( true ).animate( animations, config.duration === undefined ?
1368 'fast' : config.duration );
1369 $container.queue( function ( next ) {
1370 deferred.resolve();
1371 next();
1372 } );
1373 } else {
1374 deferred.resolve();
1375 }
1376 return deferred.promise();
1377 };
1378
1379 /**
1380 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1381 * and reserve space for them, because it probably doesn't.
1382 *
1383 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1384 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1385 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a
1386 * reflow, and then reattach (or show) them back.
1387 *
1388 * @static
1389 * @param {HTMLElement} el Element to reconsider the scrollbars on
1390 */
1391 OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
1392 var i, len, scrollLeft, scrollTop, nodes = [];
1393 // Save scroll position
1394 scrollLeft = el.scrollLeft;
1395 scrollTop = el.scrollTop;
1396 // Detach all children
1397 while ( el.firstChild ) {
1398 nodes.push( el.firstChild );
1399 el.removeChild( el.firstChild );
1400 }
1401 // Force reflow
1402 // eslint-disable-next-line no-void
1403 void el.offsetHeight;
1404 // Reattach all children
1405 for ( i = 0, len = nodes.length; i < len; i++ ) {
1406 el.appendChild( nodes[ i ] );
1407 }
1408 // Restore scroll position (no-op if scrollbars disappeared)
1409 el.scrollLeft = scrollLeft;
1410 el.scrollTop = scrollTop;
1411 };
1412
1413 /* Methods */
1414
1415 /**
1416 * Toggle visibility of an element.
1417 *
1418 * @param {boolean} [show] Make element visible, omit to toggle visibility
1419 * @fires visible
1420 * @chainable
1421 * @return {OO.ui.Element} The element, for chaining
1422 */
1423 OO.ui.Element.prototype.toggle = function ( show ) {
1424 show = show === undefined ? !this.visible : !!show;
1425
1426 if ( show !== this.isVisible() ) {
1427 this.visible = show;
1428 this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
1429 this.emit( 'toggle', show );
1430 }
1431
1432 return this;
1433 };
1434
1435 /**
1436 * Check if element is visible.
1437 *
1438 * @return {boolean} element is visible
1439 */
1440 OO.ui.Element.prototype.isVisible = function () {
1441 return this.visible;
1442 };
1443
1444 /**
1445 * Get element data.
1446 *
1447 * @return {Mixed} Element data
1448 */
1449 OO.ui.Element.prototype.getData = function () {
1450 return this.data;
1451 };
1452
1453 /**
1454 * Set element data.
1455 *
1456 * @param {Mixed} data Element data
1457 * @chainable
1458 * @return {OO.ui.Element} The element, for chaining
1459 */
1460 OO.ui.Element.prototype.setData = function ( data ) {
1461 this.data = data;
1462 return this;
1463 };
1464
1465 /**
1466 * Set the element has an 'id' attribute.
1467 *
1468 * @param {string} id
1469 * @chainable
1470 * @return {OO.ui.Element} The element, for chaining
1471 */
1472 OO.ui.Element.prototype.setElementId = function ( id ) {
1473 this.elementId = id;
1474 this.$element.attr( 'id', id );
1475 return this;
1476 };
1477
1478 /**
1479 * Ensure that the element has an 'id' attribute, setting it to an unique value if it's missing,
1480 * and return its value.
1481 *
1482 * @return {string}
1483 */
1484 OO.ui.Element.prototype.getElementId = function () {
1485 if ( this.elementId === null ) {
1486 this.setElementId( OO.ui.generateElementId() );
1487 }
1488 return this.elementId;
1489 };
1490
1491 /**
1492 * Check if element supports one or more methods.
1493 *
1494 * @param {string|string[]} methods Method or list of methods to check
1495 * @return {boolean} All methods are supported
1496 */
1497 OO.ui.Element.prototype.supports = function ( methods ) {
1498 var i, len,
1499 support = 0;
1500
1501 methods = Array.isArray( methods ) ? methods : [ methods ];
1502 for ( i = 0, len = methods.length; i < len; i++ ) {
1503 if ( typeof this[ methods[ i ] ] === 'function' ) {
1504 support++;
1505 }
1506 }
1507
1508 return methods.length === support;
1509 };
1510
1511 /**
1512 * Update the theme-provided classes.
1513 *
1514 * @localdoc This is called in element mixins and widget classes any time state changes.
1515 * Updating is debounced, minimizing overhead of changing multiple attributes and
1516 * guaranteeing that theme updates do not occur within an element's constructor
1517 */
1518 OO.ui.Element.prototype.updateThemeClasses = function () {
1519 OO.ui.theme.queueUpdateElementClasses( this );
1520 };
1521
1522 /**
1523 * Get the HTML tag name.
1524 *
1525 * Override this method to base the result on instance information.
1526 *
1527 * @return {string} HTML tag name
1528 */
1529 OO.ui.Element.prototype.getTagName = function () {
1530 return this.constructor.static.tagName;
1531 };
1532
1533 /**
1534 * Check if the element is attached to the DOM
1535 *
1536 * @return {boolean} The element is attached to the DOM
1537 */
1538 OO.ui.Element.prototype.isElementAttached = function () {
1539 return $.contains( this.getElementDocument(), this.$element[ 0 ] );
1540 };
1541
1542 /**
1543 * Get the DOM document.
1544 *
1545 * @return {HTMLDocument} Document object
1546 */
1547 OO.ui.Element.prototype.getElementDocument = function () {
1548 // Don't cache this in other ways either because subclasses could can change this.$element
1549 return OO.ui.Element.static.getDocument( this.$element );
1550 };
1551
1552 /**
1553 * Get the DOM window.
1554 *
1555 * @return {Window} Window object
1556 */
1557 OO.ui.Element.prototype.getElementWindow = function () {
1558 return OO.ui.Element.static.getWindow( this.$element );
1559 };
1560
1561 /**
1562 * Get closest scrollable container.
1563 *
1564 * @return {HTMLElement} Closest scrollable container
1565 */
1566 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1567 return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
1568 };
1569
1570 /**
1571 * Get group element is in.
1572 *
1573 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1574 */
1575 OO.ui.Element.prototype.getElementGroup = function () {
1576 return this.elementGroup;
1577 };
1578
1579 /**
1580 * Set group element is in.
1581 *
1582 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1583 * @chainable
1584 * @return {OO.ui.Element} The element, for chaining
1585 */
1586 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1587 this.elementGroup = group;
1588 return this;
1589 };
1590
1591 /**
1592 * Scroll element into view.
1593 *
1594 * @param {Object} [config] Configuration options
1595 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1596 */
1597 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
1598 if (
1599 !this.isElementAttached() ||
1600 !this.isVisible() ||
1601 ( this.getElementGroup() && !this.getElementGroup().isVisible() )
1602 ) {
1603 return $.Deferred().resolve();
1604 }
1605 return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
1606 };
1607
1608 /**
1609 * Restore the pre-infusion dynamic state for this widget.
1610 *
1611 * This method is called after #$element has been inserted into DOM. The parameter is the return
1612 * value of #gatherPreInfuseState.
1613 *
1614 * @protected
1615 * @param {Object} state
1616 */
1617 OO.ui.Element.prototype.restorePreInfuseState = function () {
1618 };
1619
1620 /**
1621 * Wraps an HTML snippet for use with configuration values which default
1622 * to strings. This bypasses the default html-escaping done to string
1623 * values.
1624 *
1625 * @class
1626 *
1627 * @constructor
1628 * @param {string} [content] HTML content
1629 */
1630 OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
1631 // Properties
1632 this.content = content;
1633 };
1634
1635 /* Setup */
1636
1637 OO.initClass( OO.ui.HtmlSnippet );
1638
1639 /* Methods */
1640
1641 /**
1642 * Render into HTML.
1643 *
1644 * @return {string} Unchanged HTML snippet.
1645 */
1646 OO.ui.HtmlSnippet.prototype.toString = function () {
1647 return this.content;
1648 };
1649
1650 /**
1651 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in
1652 * a way that is centrally controlled and can be updated dynamically. Layouts can be, and usually
1653 * are, combined.
1654 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout},
1655 * {@link OO.ui.FormLayout FormLayout}, {@link OO.ui.PanelLayout PanelLayout},
1656 * {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1657 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout}
1658 * for more information and examples.
1659 *
1660 * @abstract
1661 * @class
1662 * @extends OO.ui.Element
1663 * @mixins OO.EventEmitter
1664 *
1665 * @constructor
1666 * @param {Object} [config] Configuration options
1667 */
1668 OO.ui.Layout = function OoUiLayout( config ) {
1669 // Configuration initialization
1670 config = config || {};
1671
1672 // Parent constructor
1673 OO.ui.Layout.parent.call( this, config );
1674
1675 // Mixin constructors
1676 OO.EventEmitter.call( this );
1677
1678 // Initialization
1679 this.$element.addClass( 'oo-ui-layout' );
1680 };
1681
1682 /* Setup */
1683
1684 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1685 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1686
1687 /* Methods */
1688
1689 /**
1690 * Reset scroll offsets
1691 *
1692 * @chainable
1693 * @return {OO.ui.Layout} The layout, for chaining
1694 */
1695 OO.ui.Layout.prototype.resetScroll = function () {
1696 this.$element[ 0 ].scrollTop = 0;
1697 // TODO: Reset scrollLeft in an RTL-aware manner, see OO.ui.Element.static.getScrollLeft.
1698
1699 return this;
1700 };
1701
1702 /**
1703 * Widgets are compositions of one or more OOUI elements that users can both view
1704 * and interact with. All widgets can be configured and modified via a standard API,
1705 * and their state can change dynamically according to a model.
1706 *
1707 * @abstract
1708 * @class
1709 * @extends OO.ui.Element
1710 * @mixins OO.EventEmitter
1711 *
1712 * @constructor
1713 * @param {Object} [config] Configuration options
1714 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1715 * appearance reflects this state.
1716 */
1717 OO.ui.Widget = function OoUiWidget( config ) {
1718 // Initialize config
1719 config = $.extend( { disabled: false }, config );
1720
1721 // Parent constructor
1722 OO.ui.Widget.parent.call( this, config );
1723
1724 // Mixin constructors
1725 OO.EventEmitter.call( this );
1726
1727 // Properties
1728 this.disabled = null;
1729 this.wasDisabled = null;
1730
1731 // Initialization
1732 this.$element.addClass( 'oo-ui-widget' );
1733 this.setDisabled( !!config.disabled );
1734 };
1735
1736 /* Setup */
1737
1738 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
1739 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
1740
1741 /* Events */
1742
1743 /**
1744 * @event disable
1745 *
1746 * A 'disable' event is emitted when the disabled state of the widget changes
1747 * (i.e. on disable **and** enable).
1748 *
1749 * @param {boolean} disabled Widget is disabled
1750 */
1751
1752 /**
1753 * @event toggle
1754 *
1755 * A 'toggle' event is emitted when the visibility of the widget changes.
1756 *
1757 * @param {boolean} visible Widget is visible
1758 */
1759
1760 /* Methods */
1761
1762 /**
1763 * Check if the widget is disabled.
1764 *
1765 * @return {boolean} Widget is disabled
1766 */
1767 OO.ui.Widget.prototype.isDisabled = function () {
1768 return this.disabled;
1769 };
1770
1771 /**
1772 * Set the 'disabled' state of the widget.
1773 *
1774 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1775 *
1776 * @param {boolean} disabled Disable widget
1777 * @chainable
1778 * @return {OO.ui.Widget} The widget, for chaining
1779 */
1780 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
1781 var isDisabled;
1782
1783 this.disabled = !!disabled;
1784 isDisabled = this.isDisabled();
1785 if ( isDisabled !== this.wasDisabled ) {
1786 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
1787 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
1788 this.$element.attr( 'aria-disabled', isDisabled.toString() );
1789 this.emit( 'disable', isDisabled );
1790 this.updateThemeClasses();
1791 }
1792 this.wasDisabled = isDisabled;
1793
1794 return this;
1795 };
1796
1797 /**
1798 * Update the disabled state, in case of changes in parent widget.
1799 *
1800 * @chainable
1801 * @return {OO.ui.Widget} The widget, for chaining
1802 */
1803 OO.ui.Widget.prototype.updateDisabled = function () {
1804 this.setDisabled( this.disabled );
1805 return this;
1806 };
1807
1808 /**
1809 * Get an ID of a labelable node which is part of this widget, if any, to be used for `<label for>`
1810 * value.
1811 *
1812 * If this function returns null, the widget should have a meaningful #simulateLabelClick method
1813 * instead.
1814 *
1815 * @return {string|null} The ID of the labelable element
1816 */
1817 OO.ui.Widget.prototype.getInputId = function () {
1818 return null;
1819 };
1820
1821 /**
1822 * Simulate the behavior of clicking on a label (a HTML `<label>` element) bound to this input.
1823 * HTML only allows `<label>` to act on specific "labelable" elements; complex widgets might need to
1824 * override this method to provide intuitive, accessible behavior.
1825 *
1826 * By default, this does nothing. OO.ui.mixin.TabIndexedElement overrides it for focusable widgets.
1827 * Individual widgets may override it too.
1828 *
1829 * This method is called by OO.ui.LabelWidget and OO.ui.FieldLayout. It should not be called
1830 * directly.
1831 */
1832 OO.ui.Widget.prototype.simulateLabelClick = function () {
1833 };
1834
1835 /**
1836 * Theme logic.
1837 *
1838 * @abstract
1839 * @class
1840 *
1841 * @constructor
1842 */
1843 OO.ui.Theme = function OoUiTheme() {
1844 this.elementClassesQueue = [];
1845 this.debouncedUpdateQueuedElementClasses = OO.ui.debounce( this.updateQueuedElementClasses );
1846 };
1847
1848 /* Setup */
1849
1850 OO.initClass( OO.ui.Theme );
1851
1852 /* Methods */
1853
1854 /**
1855 * Get a list of classes to be applied to a widget.
1856 *
1857 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
1858 * otherwise state transitions will not work properly.
1859 *
1860 * @param {OO.ui.Element} element Element for which to get classes
1861 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1862 */
1863 OO.ui.Theme.prototype.getElementClasses = function () {
1864 return { on: [], off: [] };
1865 };
1866
1867 /**
1868 * Update CSS classes provided by the theme.
1869 *
1870 * For elements with theme logic hooks, this should be called any time there's a state change.
1871 *
1872 * @param {OO.ui.Element} element Element for which to update classes
1873 */
1874 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
1875 var $elements = $( [] ),
1876 classes = this.getElementClasses( element );
1877
1878 if ( element.$icon ) {
1879 $elements = $elements.add( element.$icon );
1880 }
1881 if ( element.$indicator ) {
1882 $elements = $elements.add( element.$indicator );
1883 }
1884
1885 $elements
1886 .removeClass( classes.off )
1887 .addClass( classes.on );
1888 };
1889
1890 /**
1891 * @private
1892 */
1893 OO.ui.Theme.prototype.updateQueuedElementClasses = function () {
1894 var i;
1895 for ( i = 0; i < this.elementClassesQueue.length; i++ ) {
1896 this.updateElementClasses( this.elementClassesQueue[ i ] );
1897 }
1898 // Clear the queue
1899 this.elementClassesQueue = [];
1900 };
1901
1902 /**
1903 * Queue #updateElementClasses to be called for this element.
1904 *
1905 * @localdoc QUnit tests override this method to directly call #queueUpdateElementClasses,
1906 * to make them synchronous.
1907 *
1908 * @param {OO.ui.Element} element Element for which to update classes
1909 */
1910 OO.ui.Theme.prototype.queueUpdateElementClasses = function ( element ) {
1911 // Keep items in the queue unique. Use lastIndexOf to start checking from the end because that's
1912 // the most common case (this method is often called repeatedly for the same element).
1913 if ( this.elementClassesQueue.lastIndexOf( element ) !== -1 ) {
1914 return;
1915 }
1916 this.elementClassesQueue.push( element );
1917 this.debouncedUpdateQueuedElementClasses();
1918 };
1919
1920 /**
1921 * Get the transition duration in milliseconds for dialogs opening/closing
1922 *
1923 * The dialog should be fully rendered this many milliseconds after the
1924 * ready process has executed.
1925 *
1926 * @return {number} Transition duration in milliseconds
1927 */
1928 OO.ui.Theme.prototype.getDialogTransitionDuration = function () {
1929 return 0;
1930 };
1931
1932 /**
1933 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
1934 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
1935 * order in which users will navigate through the focusable elements via the Tab key.
1936 *
1937 * @example
1938 * // TabIndexedElement is mixed into the ButtonWidget class
1939 * // to provide a tabIndex property.
1940 * var button1 = new OO.ui.ButtonWidget( {
1941 * label: 'fourth',
1942 * tabIndex: 4
1943 * } ),
1944 * button2 = new OO.ui.ButtonWidget( {
1945 * label: 'second',
1946 * tabIndex: 2
1947 * } ),
1948 * button3 = new OO.ui.ButtonWidget( {
1949 * label: 'third',
1950 * tabIndex: 3
1951 * } ),
1952 * button4 = new OO.ui.ButtonWidget( {
1953 * label: 'first',
1954 * tabIndex: 1
1955 * } );
1956 * $( document.body ).append(
1957 * button1.$element,
1958 * button2.$element,
1959 * button3.$element,
1960 * button4.$element
1961 * );
1962 *
1963 * @abstract
1964 * @class
1965 *
1966 * @constructor
1967 * @param {Object} [config] Configuration options
1968 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
1969 * the functionality is applied to the element created by the class ($element). If a different
1970 * element is specified, the tabindex functionality will be applied to it instead.
1971 * @cfg {string|number|null} [tabIndex=0] Number that specifies the element’s position in the
1972 * tab-navigation order (e.g., 1 for the first focusable element). Use 0 to use the default
1973 * navigation order; use -1 to remove the element from the tab-navigation flow.
1974 */
1975 OO.ui.mixin.TabIndexedElement = function OoUiMixinTabIndexedElement( config ) {
1976 // Configuration initialization
1977 config = $.extend( { tabIndex: 0 }, config );
1978
1979 // Properties
1980 this.$tabIndexed = null;
1981 this.tabIndex = null;
1982
1983 // Events
1984 this.connect( this, {
1985 disable: 'onTabIndexedElementDisable'
1986 } );
1987
1988 // Initialization
1989 this.setTabIndex( config.tabIndex );
1990 this.setTabIndexedElement( config.$tabIndexed || this.$element );
1991 };
1992
1993 /* Setup */
1994
1995 OO.initClass( OO.ui.mixin.TabIndexedElement );
1996
1997 /* Methods */
1998
1999 /**
2000 * Set the element that should use the tabindex functionality.
2001 *
2002 * This method is used to retarget a tabindex mixin so that its functionality applies
2003 * to the specified element. If an element is currently using the functionality, the mixin’s
2004 * effect on that element is removed before the new element is set up.
2005 *
2006 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
2007 * @chainable
2008 * @return {OO.ui.Element} The element, for chaining
2009 */
2010 OO.ui.mixin.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
2011 var tabIndex = this.tabIndex;
2012 // Remove attributes from old $tabIndexed
2013 this.setTabIndex( null );
2014 // Force update of new $tabIndexed
2015 this.$tabIndexed = $tabIndexed;
2016 this.tabIndex = tabIndex;
2017 return this.updateTabIndex();
2018 };
2019
2020 /**
2021 * Set the value of the tabindex.
2022 *
2023 * @param {string|number|null} tabIndex Tabindex value, or `null` for no tabindex
2024 * @chainable
2025 * @return {OO.ui.Element} The element, for chaining
2026 */
2027 OO.ui.mixin.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
2028 tabIndex = /^-?\d+$/.test( tabIndex ) ? Number( tabIndex ) : null;
2029
2030 if ( this.tabIndex !== tabIndex ) {
2031 this.tabIndex = tabIndex;
2032 this.updateTabIndex();
2033 }
2034
2035 return this;
2036 };
2037
2038 /**
2039 * Update the `tabindex` attribute, in case of changes to tab index or
2040 * disabled state.
2041 *
2042 * @private
2043 * @chainable
2044 * @return {OO.ui.Element} The element, for chaining
2045 */
2046 OO.ui.mixin.TabIndexedElement.prototype.updateTabIndex = function () {
2047 if ( this.$tabIndexed ) {
2048 if ( this.tabIndex !== null ) {
2049 // Do not index over disabled elements
2050 this.$tabIndexed.attr( {
2051 tabindex: this.isDisabled() ? -1 : this.tabIndex,
2052 // Support: ChromeVox and NVDA
2053 // These do not seem to inherit aria-disabled from parent elements
2054 'aria-disabled': this.isDisabled().toString()
2055 } );
2056 } else {
2057 this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
2058 }
2059 }
2060 return this;
2061 };
2062
2063 /**
2064 * Handle disable events.
2065 *
2066 * @private
2067 * @param {boolean} disabled Element is disabled
2068 */
2069 OO.ui.mixin.TabIndexedElement.prototype.onTabIndexedElementDisable = function () {
2070 this.updateTabIndex();
2071 };
2072
2073 /**
2074 * Get the value of the tabindex.
2075 *
2076 * @return {number|null} Tabindex value
2077 */
2078 OO.ui.mixin.TabIndexedElement.prototype.getTabIndex = function () {
2079 return this.tabIndex;
2080 };
2081
2082 /**
2083 * Get an ID of a focusable element of this widget, if any, to be used for `<label for>` value.
2084 *
2085 * If the element already has an ID then that is returned, otherwise unique ID is
2086 * generated, set on the element, and returned.
2087 *
2088 * @return {string|null} The ID of the focusable element
2089 */
2090 OO.ui.mixin.TabIndexedElement.prototype.getInputId = function () {
2091 var id;
2092
2093 if ( !this.$tabIndexed ) {
2094 return null;
2095 }
2096 if ( !this.isLabelableNode( this.$tabIndexed ) ) {
2097 return null;
2098 }
2099
2100 id = this.$tabIndexed.attr( 'id' );
2101 if ( id === undefined ) {
2102 id = OO.ui.generateElementId();
2103 this.$tabIndexed.attr( 'id', id );
2104 }
2105
2106 return id;
2107 };
2108
2109 /**
2110 * Whether the node is 'labelable' according to the HTML spec
2111 * (i.e., whether it can be interacted with through a `<label for="…">`).
2112 * See: <https://html.spec.whatwg.org/multipage/forms.html#category-label>.
2113 *
2114 * @private
2115 * @param {jQuery} $node
2116 * @return {boolean}
2117 */
2118 OO.ui.mixin.TabIndexedElement.prototype.isLabelableNode = function ( $node ) {
2119 var
2120 labelableTags = [ 'button', 'meter', 'output', 'progress', 'select', 'textarea' ],
2121 tagName = $node.prop( 'tagName' ).toLowerCase();
2122
2123 if ( tagName === 'input' && $node.attr( 'type' ) !== 'hidden' ) {
2124 return true;
2125 }
2126 if ( labelableTags.indexOf( tagName ) !== -1 ) {
2127 return true;
2128 }
2129 return false;
2130 };
2131
2132 /**
2133 * Focus this element.
2134 *
2135 * @chainable
2136 * @return {OO.ui.Element} The element, for chaining
2137 */
2138 OO.ui.mixin.TabIndexedElement.prototype.focus = function () {
2139 if ( !this.isDisabled() ) {
2140 this.$tabIndexed.trigger( 'focus' );
2141 }
2142 return this;
2143 };
2144
2145 /**
2146 * Blur this element.
2147 *
2148 * @chainable
2149 * @return {OO.ui.Element} The element, for chaining
2150 */
2151 OO.ui.mixin.TabIndexedElement.prototype.blur = function () {
2152 this.$tabIndexed.trigger( 'blur' );
2153 return this;
2154 };
2155
2156 /**
2157 * @inheritdoc OO.ui.Widget
2158 */
2159 OO.ui.mixin.TabIndexedElement.prototype.simulateLabelClick = function () {
2160 this.focus();
2161 };
2162
2163 /**
2164 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
2165 * interface element that can be configured with access keys for keyboard interaction.
2166 * See the [OOUI documentation on MediaWiki] [1] for examples.
2167 *
2168 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches#Buttons
2169 *
2170 * @abstract
2171 * @class
2172 *
2173 * @constructor
2174 * @param {Object} [config] Configuration options
2175 * @cfg {jQuery} [$button] The button element created by the class.
2176 * If this configuration is omitted, the button element will use a generated `<a>`.
2177 * @cfg {boolean} [framed=true] Render the button with a frame
2178 */
2179 OO.ui.mixin.ButtonElement = function OoUiMixinButtonElement( config ) {
2180 // Configuration initialization
2181 config = config || {};
2182
2183 // Properties
2184 this.$button = null;
2185 this.framed = null;
2186 this.active = config.active !== undefined && config.active;
2187 this.onDocumentMouseUpHandler = this.onDocumentMouseUp.bind( this );
2188 this.onMouseDownHandler = this.onMouseDown.bind( this );
2189 this.onDocumentKeyUpHandler = this.onDocumentKeyUp.bind( this );
2190 this.onKeyDownHandler = this.onKeyDown.bind( this );
2191 this.onClickHandler = this.onClick.bind( this );
2192 this.onKeyPressHandler = this.onKeyPress.bind( this );
2193
2194 // Initialization
2195 this.$element.addClass( 'oo-ui-buttonElement' );
2196 this.toggleFramed( config.framed === undefined || config.framed );
2197 this.setButtonElement( config.$button || $( '<a>' ) );
2198 };
2199
2200 /* Setup */
2201
2202 OO.initClass( OO.ui.mixin.ButtonElement );
2203
2204 /* Static Properties */
2205
2206 /**
2207 * Cancel mouse down events.
2208 *
2209 * This property is usually set to `true` to prevent the focus from changing when the button is
2210 * clicked.
2211 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and
2212 * {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} use a value of `false` so that dragging
2213 * behavior is possible and mousedown events can be handled by a parent widget.
2214 *
2215 * @static
2216 * @inheritable
2217 * @property {boolean}
2218 */
2219 OO.ui.mixin.ButtonElement.static.cancelButtonMouseDownEvents = true;
2220
2221 /* Events */
2222
2223 /**
2224 * A 'click' event is emitted when the button element is clicked.
2225 *
2226 * @event click
2227 */
2228
2229 /* Methods */
2230
2231 /**
2232 * Set the button element.
2233 *
2234 * This method is used to retarget a button mixin so that its functionality applies to
2235 * the specified button element instead of the one created by the class. If a button element
2236 * is already set, the method will remove the mixin’s effect on that element.
2237 *
2238 * @param {jQuery} $button Element to use as button
2239 */
2240 OO.ui.mixin.ButtonElement.prototype.setButtonElement = function ( $button ) {
2241 if ( this.$button ) {
2242 this.$button
2243 .removeClass( 'oo-ui-buttonElement-button' )
2244 .removeAttr( 'role accesskey' )
2245 .off( {
2246 mousedown: this.onMouseDownHandler,
2247 keydown: this.onKeyDownHandler,
2248 click: this.onClickHandler,
2249 keypress: this.onKeyPressHandler
2250 } );
2251 }
2252
2253 this.$button = $button
2254 .addClass( 'oo-ui-buttonElement-button' )
2255 .on( {
2256 mousedown: this.onMouseDownHandler,
2257 keydown: this.onKeyDownHandler,
2258 click: this.onClickHandler,
2259 keypress: this.onKeyPressHandler
2260 } );
2261
2262 // Add `role="button"` on `<a>` elements, where it's needed
2263 // `toUpperCase()` is added for XHTML documents
2264 if ( this.$button.prop( 'tagName' ).toUpperCase() === 'A' ) {
2265 this.$button.attr( 'role', 'button' );
2266 }
2267 };
2268
2269 /**
2270 * Handles mouse down events.
2271 *
2272 * @protected
2273 * @param {jQuery.Event} e Mouse down event
2274 * @return {undefined/boolean} False to prevent default if event is handled
2275 */
2276 OO.ui.mixin.ButtonElement.prototype.onMouseDown = function ( e ) {
2277 if ( this.isDisabled() || e.which !== OO.ui.MouseButtons.LEFT ) {
2278 return;
2279 }
2280 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
2281 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
2282 // reliably remove the pressed class
2283 this.getElementDocument().addEventListener( 'mouseup', this.onDocumentMouseUpHandler, true );
2284 // Prevent change of focus unless specifically configured otherwise
2285 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
2286 return false;
2287 }
2288 };
2289
2290 /**
2291 * Handles document mouse up events.
2292 *
2293 * @protected
2294 * @param {MouseEvent} e Mouse up event
2295 */
2296 OO.ui.mixin.ButtonElement.prototype.onDocumentMouseUp = function ( e ) {
2297 if ( this.isDisabled() || e.which !== OO.ui.MouseButtons.LEFT ) {
2298 return;
2299 }
2300 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
2301 // Stop listening for mouseup, since we only needed this once
2302 this.getElementDocument().removeEventListener( 'mouseup', this.onDocumentMouseUpHandler, true );
2303 };
2304
2305 /**
2306 * Handles mouse click events.
2307 *
2308 * @protected
2309 * @param {jQuery.Event} e Mouse click event
2310 * @fires click
2311 * @return {undefined/boolean} False to prevent default if event is handled
2312 */
2313 OO.ui.mixin.ButtonElement.prototype.onClick = function ( e ) {
2314 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
2315 if ( this.emit( 'click' ) ) {
2316 return false;
2317 }
2318 }
2319 };
2320
2321 /**
2322 * Handles key down events.
2323 *
2324 * @protected
2325 * @param {jQuery.Event} e Key down event
2326 */
2327 OO.ui.mixin.ButtonElement.prototype.onKeyDown = function ( e ) {
2328 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
2329 return;
2330 }
2331 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
2332 // Run the keyup handler no matter where the key is when the button is let go, so we can
2333 // reliably remove the pressed class
2334 this.getElementDocument().addEventListener( 'keyup', this.onDocumentKeyUpHandler, true );
2335 };
2336
2337 /**
2338 * Handles document key up events.
2339 *
2340 * @protected
2341 * @param {KeyboardEvent} e Key up event
2342 */
2343 OO.ui.mixin.ButtonElement.prototype.onDocumentKeyUp = function ( e ) {
2344 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
2345 return;
2346 }
2347 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
2348 // Stop listening for keyup, since we only needed this once
2349 this.getElementDocument().removeEventListener( 'keyup', this.onDocumentKeyUpHandler, true );
2350 };
2351
2352 /**
2353 * Handles key press events.
2354 *
2355 * @protected
2356 * @param {jQuery.Event} e Key press event
2357 * @fires click
2358 * @return {undefined/boolean} False to prevent default if event is handled
2359 */
2360 OO.ui.mixin.ButtonElement.prototype.onKeyPress = function ( e ) {
2361 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
2362 if ( this.emit( 'click' ) ) {
2363 return false;
2364 }
2365 }
2366 };
2367
2368 /**
2369 * Check if button has a frame.
2370 *
2371 * @return {boolean} Button is framed
2372 */
2373 OO.ui.mixin.ButtonElement.prototype.isFramed = function () {
2374 return this.framed;
2375 };
2376
2377 /**
2378 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame
2379 * on and off.
2380 *
2381 * @param {boolean} [framed] Make button framed, omit to toggle
2382 * @chainable
2383 * @return {OO.ui.Element} The element, for chaining
2384 */
2385 OO.ui.mixin.ButtonElement.prototype.toggleFramed = function ( framed ) {
2386 framed = framed === undefined ? !this.framed : !!framed;
2387 if ( framed !== this.framed ) {
2388 this.framed = framed;
2389 this.$element
2390 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
2391 .toggleClass( 'oo-ui-buttonElement-framed', framed );
2392 this.updateThemeClasses();
2393 }
2394
2395 return this;
2396 };
2397
2398 /**
2399 * Set the button's active state.
2400 *
2401 * The active state can be set on:
2402 *
2403 * - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected
2404 * - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on
2405 * - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page
2406 *
2407 * @protected
2408 * @param {boolean} value Make button active
2409 * @chainable
2410 * @return {OO.ui.Element} The element, for chaining
2411 */
2412 OO.ui.mixin.ButtonElement.prototype.setActive = function ( value ) {
2413 this.active = !!value;
2414 this.$element.toggleClass( 'oo-ui-buttonElement-active', this.active );
2415 this.updateThemeClasses();
2416 return this;
2417 };
2418
2419 /**
2420 * Check if the button is active
2421 *
2422 * @protected
2423 * @return {boolean} The button is active
2424 */
2425 OO.ui.mixin.ButtonElement.prototype.isActive = function () {
2426 return this.active;
2427 };
2428
2429 /**
2430 * Any OOUI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
2431 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
2432 * items from the group is done through the interface the class provides.
2433 * For more information, please see the [OOUI documentation on MediaWiki] [1].
2434 *
2435 * [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Groups
2436 *
2437 * @abstract
2438 * @mixins OO.EmitterList
2439 * @class
2440 *
2441 * @constructor
2442 * @param {Object} [config] Configuration options
2443 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
2444 * is omitted, the group element will use a generated `<div>`.
2445 */
2446 OO.ui.mixin.GroupElement = function OoUiMixinGroupElement( config ) {
2447 // Configuration initialization
2448 config = config || {};
2449
2450 // Mixin constructors
2451 OO.EmitterList.call( this, config );
2452
2453 // Properties
2454 this.$group = null;
2455
2456 // Initialization
2457 this.setGroupElement( config.$group || $( '<div>' ) );
2458 };
2459
2460 /* Setup */
2461
2462 OO.mixinClass( OO.ui.mixin.GroupElement, OO.EmitterList );
2463
2464 /* Events */
2465
2466 /**
2467 * @event change
2468 *
2469 * A change event is emitted when the set of selected items changes.
2470 *
2471 * @param {OO.ui.Element[]} items Items currently in the group
2472 */
2473
2474 /* Methods */
2475
2476 /**
2477 * Set the group element.
2478 *
2479 * If an element is already set, items will be moved to the new element.
2480 *
2481 * @param {jQuery} $group Element to use as group
2482 */
2483 OO.ui.mixin.GroupElement.prototype.setGroupElement = function ( $group ) {
2484 var i, len;
2485
2486 this.$group = $group;
2487 for ( i = 0, len = this.items.length; i < len; i++ ) {
2488 this.$group.append( this.items[ i ].$element );
2489 }
2490 };
2491
2492 /**
2493 * Find an item by its data.
2494 *
2495 * Only the first item with matching data will be returned. To return all matching items,
2496 * use the #findItemsFromData method.
2497 *
2498 * @param {Object} data Item data to search for
2499 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2500 */
2501 OO.ui.mixin.GroupElement.prototype.findItemFromData = function ( data ) {
2502 var i, len, item,
2503 hash = OO.getHash( data );
2504
2505 for ( i = 0, len = this.items.length; i < len; i++ ) {
2506 item = this.items[ i ];
2507 if ( hash === OO.getHash( item.getData() ) ) {
2508 return item;
2509 }
2510 }
2511
2512 return null;
2513 };
2514
2515 /**
2516 * Find items by their data.
2517 *
2518 * All items with matching data will be returned. To return only the first match, use the
2519 * #findItemFromData method instead.
2520 *
2521 * @param {Object} data Item data to search for
2522 * @return {OO.ui.Element[]} Items with equivalent data
2523 */
2524 OO.ui.mixin.GroupElement.prototype.findItemsFromData = function ( data ) {
2525 var i, len, item,
2526 hash = OO.getHash( data ),
2527 items = [];
2528
2529 for ( i = 0, len = this.items.length; i < len; i++ ) {
2530 item = this.items[ i ];
2531 if ( hash === OO.getHash( item.getData() ) ) {
2532 items.push( item );
2533 }
2534 }
2535
2536 return items;
2537 };
2538
2539 /**
2540 * Add items to the group.
2541 *
2542 * Items will be added to the end of the group array unless the optional `index` parameter
2543 * specifies a different insertion point. Adding an existing item will move it to the end of the
2544 * array or the point specified by the `index`.
2545 *
2546 * @param {OO.ui.Element[]} items An array of items to add to the group
2547 * @param {number} [index] Index of the insertion point
2548 * @chainable
2549 * @return {OO.ui.Element} The element, for chaining
2550 */
2551 OO.ui.mixin.GroupElement.prototype.addItems = function ( items, index ) {
2552
2553 if ( items.length === 0 ) {
2554 return this;
2555 }
2556
2557 // Mixin method
2558 OO.EmitterList.prototype.addItems.call( this, items, index );
2559
2560 this.emit( 'change', this.getItems() );
2561 return this;
2562 };
2563
2564 /**
2565 * @inheritdoc
2566 */
2567 OO.ui.mixin.GroupElement.prototype.moveItem = function ( items, newIndex ) {
2568 // insertItemElements expects this.items to not have been modified yet, so call before the mixin
2569 this.insertItemElements( items, newIndex );
2570
2571 // Mixin method
2572 newIndex = OO.EmitterList.prototype.moveItem.call( this, items, newIndex );
2573
2574 return newIndex;
2575 };
2576
2577 /**
2578 * @inheritdoc
2579 */
2580 OO.ui.mixin.GroupElement.prototype.insertItem = function ( item, index ) {
2581 item.setElementGroup( this );
2582 this.insertItemElements( item, index );
2583
2584 // Mixin method
2585 index = OO.EmitterList.prototype.insertItem.call( this, item, index );
2586
2587 return index;
2588 };
2589
2590 /**
2591 * Insert elements into the group
2592 *
2593 * @private
2594 * @param {OO.ui.Element} itemWidget Item to insert
2595 * @param {number} index Insertion index
2596 */
2597 OO.ui.mixin.GroupElement.prototype.insertItemElements = function ( itemWidget, index ) {
2598 if ( index === undefined || index < 0 || index >= this.items.length ) {
2599 this.$group.append( itemWidget.$element );
2600 } else if ( index === 0 ) {
2601 this.$group.prepend( itemWidget.$element );
2602 } else {
2603 this.items[ index ].$element.before( itemWidget.$element );
2604 }
2605 };
2606
2607 /**
2608 * Remove the specified items from a group.
2609 *
2610 * Removed items are detached (not removed) from the DOM so that they may be reused.
2611 * To remove all items from a group, you may wish to use the #clearItems method instead.
2612 *
2613 * @param {OO.ui.Element[]} items An array of items to remove
2614 * @chainable
2615 * @return {OO.ui.Element} The element, for chaining
2616 */
2617 OO.ui.mixin.GroupElement.prototype.removeItems = function ( items ) {
2618 var i, len, item, index;
2619
2620 if ( items.length === 0 ) {
2621 return this;
2622 }
2623
2624 // Remove specific items elements
2625 for ( i = 0, len = items.length; i < len; i++ ) {
2626 item = items[ i ];
2627 index = this.items.indexOf( item );
2628 if ( index !== -1 ) {
2629 item.setElementGroup( null );
2630 item.$element.detach();
2631 }
2632 }
2633
2634 // Mixin method
2635 OO.EmitterList.prototype.removeItems.call( this, items );
2636
2637 this.emit( 'change', this.getItems() );
2638 return this;
2639 };
2640
2641 /**
2642 * Clear all items from the group.
2643 *
2644 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2645 * To remove only a subset of items from a group, use the #removeItems method.
2646 *
2647 * @chainable
2648 * @return {OO.ui.Element} The element, for chaining
2649 */
2650 OO.ui.mixin.GroupElement.prototype.clearItems = function () {
2651 var i, len;
2652
2653 // Remove all item elements
2654 for ( i = 0, len = this.items.length; i < len; i++ ) {
2655 this.items[ i ].setElementGroup( null );
2656 this.items[ i ].$element.detach();
2657 }
2658
2659 // Mixin method
2660 OO.EmitterList.prototype.clearItems.call( this );
2661
2662 this.emit( 'change', this.getItems() );
2663 return this;
2664 };
2665
2666 /**
2667 * LabelElement is often mixed into other classes to generate a label, which
2668 * helps identify the function of an interface element.
2669 * See the [OOUI documentation on MediaWiki] [1] for more information.
2670 *
2671 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
2672 *
2673 * @abstract
2674 * @class
2675 *
2676 * @constructor
2677 * @param {Object} [config] Configuration options
2678 * @cfg {jQuery} [$label] The label element created by the class. If this
2679 * configuration is omitted, the label element will use a generated `<span>`.
2680 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be
2681 * specified as a plaintext string, a jQuery selection of elements, or a function that will
2682 * produce a string in the future. See the [OOUI documentation on MediaWiki] [2] for examples.
2683 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
2684 * @cfg {boolean} [invisibleLabel] Whether the label should be visually hidden (but still
2685 * accessible to screen-readers).
2686 */
2687 OO.ui.mixin.LabelElement = function OoUiMixinLabelElement( config ) {
2688 // Configuration initialization
2689 config = config || {};
2690
2691 // Properties
2692 this.$label = null;
2693 this.label = null;
2694 this.invisibleLabel = null;
2695
2696 // Initialization
2697 this.setLabel( config.label || this.constructor.static.label );
2698 this.setLabelElement( config.$label || $( '<span>' ) );
2699 this.setInvisibleLabel( config.invisibleLabel );
2700 };
2701
2702 /* Setup */
2703
2704 OO.initClass( OO.ui.mixin.LabelElement );
2705
2706 /* Events */
2707
2708 /**
2709 * @event labelChange
2710 * @param {string} value
2711 */
2712
2713 /* Static Properties */
2714
2715 /**
2716 * The label text. The label can be specified as a plaintext string, a function that will
2717 * produce a string in the future, or `null` for no label. The static value will
2718 * be overridden if a label is specified with the #label config option.
2719 *
2720 * @static
2721 * @inheritable
2722 * @property {string|Function|null}
2723 */
2724 OO.ui.mixin.LabelElement.static.label = null;
2725
2726 /* Static methods */
2727
2728 /**
2729 * Highlight the first occurrence of the query in the given text
2730 *
2731 * @param {string} text Text
2732 * @param {string} query Query to find
2733 * @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
2734 * @return {jQuery} Text with the first match of the query
2735 * sub-string wrapped in highlighted span
2736 */
2737 OO.ui.mixin.LabelElement.static.highlightQuery = function ( text, query, compare ) {
2738 var i, tLen, qLen,
2739 offset = -1,
2740 $result = $( '<span>' );
2741
2742 if ( compare ) {
2743 tLen = text.length;
2744 qLen = query.length;
2745 for ( i = 0; offset === -1 && i <= tLen - qLen; i++ ) {
2746 if ( compare( query, text.slice( i, i + qLen ) ) === 0 ) {
2747 offset = i;
2748 }
2749 }
2750 } else {
2751 offset = text.toLowerCase().indexOf( query.toLowerCase() );
2752 }
2753
2754 if ( !query.length || offset === -1 ) {
2755 $result.text( text );
2756 } else {
2757 $result.append(
2758 document.createTextNode( text.slice( 0, offset ) ),
2759 $( '<span>' )
2760 .addClass( 'oo-ui-labelElement-label-highlight' )
2761 .text( text.slice( offset, offset + query.length ) ),
2762 document.createTextNode( text.slice( offset + query.length ) )
2763 );
2764 }
2765 return $result.contents();
2766 };
2767
2768 /* Methods */
2769
2770 /**
2771 * Set the label element.
2772 *
2773 * If an element is already set, it will be cleaned up before setting up the new element.
2774 *
2775 * @param {jQuery} $label Element to use as label
2776 */
2777 OO.ui.mixin.LabelElement.prototype.setLabelElement = function ( $label ) {
2778 if ( this.$label ) {
2779 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
2780 }
2781
2782 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
2783 this.setLabelContent( this.label );
2784 };
2785
2786 /**
2787 * Set the label.
2788 *
2789 * An empty string will result in the label being hidden. A string containing only whitespace will
2790 * be converted to a single `&nbsp;`.
2791 *
2792 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that
2793 * returns nodes or text; or null for no label
2794 * @chainable
2795 * @return {OO.ui.Element} The element, for chaining
2796 */
2797 OO.ui.mixin.LabelElement.prototype.setLabel = function ( label ) {
2798 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
2799 label = ( ( typeof label === 'string' || label instanceof $ ) && label.length ) || ( label instanceof OO.ui.HtmlSnippet && label.toString().length ) ? label : null;
2800
2801 if ( this.label !== label ) {
2802 if ( this.$label ) {
2803 this.setLabelContent( label );
2804 }
2805 this.label = label;
2806 this.emit( 'labelChange' );
2807 }
2808
2809 this.$element.toggleClass( 'oo-ui-labelElement', !!this.label && !this.invisibleLabel );
2810
2811 return this;
2812 };
2813
2814 /**
2815 * Set whether the label should be visually hidden (but still accessible to screen-readers).
2816 *
2817 * @param {boolean} invisibleLabel
2818 * @chainable
2819 * @return {OO.ui.Element} The element, for chaining
2820 */
2821 OO.ui.mixin.LabelElement.prototype.setInvisibleLabel = function ( invisibleLabel ) {
2822 invisibleLabel = !!invisibleLabel;
2823
2824 if ( this.invisibleLabel !== invisibleLabel ) {
2825 this.invisibleLabel = invisibleLabel;
2826 this.emit( 'labelChange' );
2827 }
2828
2829 this.$label.toggleClass( 'oo-ui-labelElement-invisible', this.invisibleLabel );
2830 // Pretend that there is no label, a lot of CSS has been written with this assumption
2831 this.$element.toggleClass( 'oo-ui-labelElement', !!this.label && !this.invisibleLabel );
2832
2833 return this;
2834 };
2835
2836 /**
2837 * Set the label as plain text with a highlighted query
2838 *
2839 * @param {string} text Text label to set
2840 * @param {string} query Substring of text to highlight
2841 * @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
2842 * @chainable
2843 * @return {OO.ui.Element} The element, for chaining
2844 */
2845 OO.ui.mixin.LabelElement.prototype.setHighlightedQuery = function ( text, query, compare ) {
2846 return this.setLabel( this.constructor.static.highlightQuery( text, query, compare ) );
2847 };
2848
2849 /**
2850 * Get the label.
2851 *
2852 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
2853 * text; or null for no label
2854 */
2855 OO.ui.mixin.LabelElement.prototype.getLabel = function () {
2856 return this.label;
2857 };
2858
2859 /**
2860 * Set the content of the label.
2861 *
2862 * Do not call this method until after the label element has been set by #setLabelElement.
2863 *
2864 * @private
2865 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
2866 * text; or null for no label
2867 */
2868 OO.ui.mixin.LabelElement.prototype.setLabelContent = function ( label ) {
2869 if ( typeof label === 'string' ) {
2870 if ( label.match( /^\s*$/ ) ) {
2871 // Convert whitespace only string to a single non-breaking space
2872 this.$label.html( '&nbsp;' );
2873 } else {
2874 this.$label.text( label );
2875 }
2876 } else if ( label instanceof OO.ui.HtmlSnippet ) {
2877 this.$label.html( label.toString() );
2878 } else if ( label instanceof $ ) {
2879 this.$label.empty().append( label );
2880 } else {
2881 this.$label.empty();
2882 }
2883 };
2884
2885 /**
2886 * IconElement is often mixed into other classes to generate an icon.
2887 * Icons are graphics, about the size of normal text. They are used to aid the user
2888 * in locating a control or to convey information in a space-efficient way. See the
2889 * [OOUI documentation on MediaWiki] [1] for a list of icons
2890 * included in the library.
2891 *
2892 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
2893 *
2894 * @abstract
2895 * @class
2896 *
2897 * @constructor
2898 * @param {Object} [config] Configuration options
2899 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2900 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2901 * the icon element be set to an existing icon instead of the one generated by this class, set a
2902 * value using a jQuery selection. For example:
2903 *
2904 * // Use a <div> tag instead of a <span>
2905 * $icon: $( '<div>' )
2906 * // Use an existing icon element instead of the one generated by the class
2907 * $icon: this.$element
2908 * // Use an icon element from a child widget
2909 * $icon: this.childwidget.$element
2910 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a
2911 * map of symbolic names. A map is used for i18n purposes and contains a `default` icon
2912 * name and additional names keyed by language code. The `default` name is used when no icon is
2913 * keyed by the user's language.
2914 *
2915 * Example of an i18n map:
2916 *
2917 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2918 * See the [OOUI documentation on MediaWiki] [2] for a list of icons included in the library.
2919 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
2920 */
2921 OO.ui.mixin.IconElement = function OoUiMixinIconElement( config ) {
2922 // Configuration initialization
2923 config = config || {};
2924
2925 // Properties
2926 this.$icon = null;
2927 this.icon = null;
2928
2929 // Initialization
2930 this.setIcon( config.icon || this.constructor.static.icon );
2931 this.setIconElement( config.$icon || $( '<span>' ) );
2932 };
2933
2934 /* Setup */
2935
2936 OO.initClass( OO.ui.mixin.IconElement );
2937
2938 /* Static Properties */
2939
2940 /**
2941 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map
2942 * is used for i18n purposes and contains a `default` icon name and additional names keyed by
2943 * language code. The `default` name is used when no icon is keyed by the user's language.
2944 *
2945 * Example of an i18n map:
2946 *
2947 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2948 *
2949 * Note: the static property will be overridden if the #icon configuration is used.
2950 *
2951 * @static
2952 * @inheritable
2953 * @property {Object|string}
2954 */
2955 OO.ui.mixin.IconElement.static.icon = null;
2956
2957 /**
2958 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2959 * function that returns title text, or `null` for no title.
2960 *
2961 * The static property will be overridden if the #iconTitle configuration is used.
2962 *
2963 * @static
2964 * @inheritable
2965 * @property {string|Function|null}
2966 */
2967 OO.ui.mixin.IconElement.static.iconTitle = null;
2968
2969 /* Methods */
2970
2971 /**
2972 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2973 * applies to the specified icon element instead of the one created by the class. If an icon
2974 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2975 * and mixin methods will no longer affect the element.
2976 *
2977 * @param {jQuery} $icon Element to use as icon
2978 */
2979 OO.ui.mixin.IconElement.prototype.setIconElement = function ( $icon ) {
2980 if ( this.$icon ) {
2981 this.$icon
2982 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
2983 .removeAttr( 'title' );
2984 }
2985
2986 this.$icon = $icon
2987 .addClass( 'oo-ui-iconElement-icon' )
2988 .toggleClass( 'oo-ui-iconElement-noIcon', !this.icon )
2989 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
2990 if ( this.iconTitle !== null ) {
2991 this.$icon.attr( 'title', this.iconTitle );
2992 }
2993
2994 this.updateThemeClasses();
2995 };
2996
2997 /**
2998 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
2999 * The icon parameter can also be set to a map of icon names. See the #icon config setting
3000 * for an example.
3001 *
3002 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
3003 * by language code, or `null` to remove the icon.
3004 * @chainable
3005 * @return {OO.ui.Element} The element, for chaining
3006 */
3007 OO.ui.mixin.IconElement.prototype.setIcon = function ( icon ) {
3008 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
3009 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
3010
3011 if ( this.icon !== icon ) {
3012 if ( this.$icon ) {
3013 if ( this.icon !== null ) {
3014 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
3015 }
3016 if ( icon !== null ) {
3017 this.$icon.addClass( 'oo-ui-icon-' + icon );
3018 }
3019 }
3020 this.icon = icon;
3021 }
3022
3023 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
3024 if ( this.$icon ) {
3025 this.$icon.toggleClass( 'oo-ui-iconElement-noIcon', !this.icon );
3026 }
3027 this.updateThemeClasses();
3028
3029 return this;
3030 };
3031
3032 /**
3033 * Get the symbolic name of the icon.
3034 *
3035 * @return {string} Icon name
3036 */
3037 OO.ui.mixin.IconElement.prototype.getIcon = function () {
3038 return this.icon;
3039 };
3040
3041 /**
3042 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
3043 *
3044 * @return {string} Icon title text
3045 * @deprecated
3046 */
3047 OO.ui.mixin.IconElement.prototype.getIconTitle = function () {
3048 return this.iconTitle;
3049 };
3050
3051 /**
3052 * IndicatorElement is often mixed into other classes to generate an indicator.
3053 * Indicators are small graphics that are generally used in two ways:
3054 *
3055 * - To draw attention to the status of an item. For example, an indicator might be
3056 * used to show that an item in a list has errors that need to be resolved.
3057 * - To clarify the function of a control that acts in an exceptional way (a button
3058 * that opens a menu instead of performing an action directly, for example).
3059 *
3060 * For a list of indicators included in the library, please see the
3061 * [OOUI documentation on MediaWiki] [1].
3062 *
3063 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3064 *
3065 * @abstract
3066 * @class
3067 *
3068 * @constructor
3069 * @param {Object} [config] Configuration options
3070 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
3071 * configuration is omitted, the indicator element will use a generated `<span>`.
3072 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3073 * See the [OOUI documentation on MediaWiki][2] for a list of indicators included
3074 * in the library.
3075 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3076 */
3077 OO.ui.mixin.IndicatorElement = function OoUiMixinIndicatorElement( config ) {
3078 // Configuration initialization
3079 config = config || {};
3080
3081 // Properties
3082 this.$indicator = null;
3083 this.indicator = null;
3084
3085 // Initialization
3086 this.setIndicator( config.indicator || this.constructor.static.indicator );
3087 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
3088 };
3089
3090 /* Setup */
3091
3092 OO.initClass( OO.ui.mixin.IndicatorElement );
3093
3094 /* Static Properties */
3095
3096 /**
3097 * Symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3098 * The static property will be overridden if the #indicator configuration is used.
3099 *
3100 * @static
3101 * @inheritable
3102 * @property {string|null}
3103 */
3104 OO.ui.mixin.IndicatorElement.static.indicator = null;
3105
3106 /**
3107 * A text string used as the indicator title, a function that returns title text, or `null`
3108 * for no title. The static property will be overridden if the #indicatorTitle configuration is
3109 * used.
3110 *
3111 * @static
3112 * @inheritable
3113 * @property {string|Function|null}
3114 */
3115 OO.ui.mixin.IndicatorElement.static.indicatorTitle = null;
3116
3117 /* Methods */
3118
3119 /**
3120 * Set the indicator element.
3121 *
3122 * If an element is already set, it will be cleaned up before setting up the new element.
3123 *
3124 * @param {jQuery} $indicator Element to use as indicator
3125 */
3126 OO.ui.mixin.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
3127 if ( this.$indicator ) {
3128 this.$indicator
3129 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
3130 .removeAttr( 'title' );
3131 }
3132
3133 this.$indicator = $indicator
3134 .addClass( 'oo-ui-indicatorElement-indicator' )
3135 .toggleClass( 'oo-ui-indicatorElement-noIndicator', !this.indicator )
3136 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
3137 if ( this.indicatorTitle !== null ) {
3138 this.$indicator.attr( 'title', this.indicatorTitle );
3139 }
3140
3141 this.updateThemeClasses();
3142 };
3143
3144 /**
3145 * Set the indicator by its symbolic name: ‘clear’, ‘down’, ‘required’, ‘search’, ‘up’. Use `null`
3146 * to remove the indicator.
3147 *
3148 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
3149 * @chainable
3150 * @return {OO.ui.Element} The element, for chaining
3151 */
3152 OO.ui.mixin.IndicatorElement.prototype.setIndicator = function ( indicator ) {
3153 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
3154
3155 if ( this.indicator !== indicator ) {
3156 if ( this.$indicator ) {
3157 if ( this.indicator !== null ) {
3158 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
3159 }
3160 if ( indicator !== null ) {
3161 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
3162 }
3163 }
3164 this.indicator = indicator;
3165 }
3166
3167 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
3168 if ( this.$indicator ) {
3169 this.$indicator.toggleClass( 'oo-ui-indicatorElement-noIndicator', !this.indicator );
3170 }
3171 this.updateThemeClasses();
3172
3173 return this;
3174 };
3175
3176 /**
3177 * Get the symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3178 *
3179 * @return {string} Symbolic name of indicator
3180 */
3181 OO.ui.mixin.IndicatorElement.prototype.getIndicator = function () {
3182 return this.indicator;
3183 };
3184
3185 /**
3186 * Get the indicator title.
3187 *
3188 * The title is displayed when a user moves the mouse over the indicator.
3189 *
3190 * @return {string} Indicator title text
3191 * @deprecated
3192 */
3193 OO.ui.mixin.IndicatorElement.prototype.getIndicatorTitle = function () {
3194 return this.indicatorTitle;
3195 };
3196
3197 /**
3198 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
3199 * additional functionality to an element created by another class. The class provides
3200 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
3201 * which are used to customize the look and feel of a widget to better describe its
3202 * importance and functionality.
3203 *
3204 * The library currently contains the following styling flags for general use:
3205 *
3206 * - **progressive**: Progressive styling is applied to convey that the widget will move the user
3207 * forward in a process.
3208 * - **destructive**: Destructive styling is applied to convey that the widget will remove
3209 * something.
3210 *
3211 * The flags affect the appearance of the buttons:
3212 *
3213 * @example
3214 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
3215 * var button1 = new OO.ui.ButtonWidget( {
3216 * label: 'Progressive',
3217 * flags: 'progressive'
3218 * } ),
3219 * button2 = new OO.ui.ButtonWidget( {
3220 * label: 'Destructive',
3221 * flags: 'destructive'
3222 * } );
3223 * $( document.body ).append( button1.$element, button2.$element );
3224 *
3225 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an
3226 * action, use these flags: **primary** and **safe**.
3227 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
3228 *
3229 * [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
3230 *
3231 * @abstract
3232 * @class
3233 *
3234 * @constructor
3235 * @param {Object} [config] Configuration options
3236 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'progressive' or 'primary')
3237 * to apply.
3238 * Please see the [OOUI documentation on MediaWiki] [2] for more information about available flags.
3239 * [2]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
3240 * @cfg {jQuery} [$flagged] The flagged element. By default,
3241 * the flagged functionality is applied to the element created by the class ($element).
3242 * If a different element is specified, the flagged functionality will be applied to it instead.
3243 */
3244 OO.ui.mixin.FlaggedElement = function OoUiMixinFlaggedElement( config ) {
3245 // Configuration initialization
3246 config = config || {};
3247
3248 // Properties
3249 this.flags = {};
3250 this.$flagged = null;
3251
3252 // Initialization
3253 this.setFlags( config.flags );
3254 this.setFlaggedElement( config.$flagged || this.$element );
3255 };
3256
3257 /* Events */
3258
3259 /**
3260 * @event flag
3261 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
3262 * parameter contains the name of each modified flag and indicates whether it was
3263 * added or removed.
3264 *
3265 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
3266 * that the flag was added, `false` that the flag was removed.
3267 */
3268
3269 /* Methods */
3270
3271 /**
3272 * Set the flagged element.
3273 *
3274 * This method is used to retarget a flagged mixin so that its functionality applies to the
3275 * specified element.
3276 * If an element is already set, the method will remove the mixin’s effect on that element.
3277 *
3278 * @param {jQuery} $flagged Element that should be flagged
3279 */
3280 OO.ui.mixin.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
3281 var classNames = Object.keys( this.flags ).map( function ( flag ) {
3282 return 'oo-ui-flaggedElement-' + flag;
3283 } );
3284
3285 if ( this.$flagged ) {
3286 this.$flagged.removeClass( classNames );
3287 }
3288
3289 this.$flagged = $flagged.addClass( classNames );
3290 };
3291
3292 /**
3293 * Check if the specified flag is set.
3294 *
3295 * @param {string} flag Name of flag
3296 * @return {boolean} The flag is set
3297 */
3298 OO.ui.mixin.FlaggedElement.prototype.hasFlag = function ( flag ) {
3299 // This may be called before the constructor, thus before this.flags is set
3300 return this.flags && ( flag in this.flags );
3301 };
3302
3303 /**
3304 * Get the names of all flags set.
3305 *
3306 * @return {string[]} Flag names
3307 */
3308 OO.ui.mixin.FlaggedElement.prototype.getFlags = function () {
3309 // This may be called before the constructor, thus before this.flags is set
3310 return Object.keys( this.flags || {} );
3311 };
3312
3313 /**
3314 * Clear all flags.
3315 *
3316 * @chainable
3317 * @return {OO.ui.Element} The element, for chaining
3318 * @fires flag
3319 */
3320 OO.ui.mixin.FlaggedElement.prototype.clearFlags = function () {
3321 var flag, className,
3322 changes = {},
3323 remove = [],
3324 classPrefix = 'oo-ui-flaggedElement-';
3325
3326 for ( flag in this.flags ) {
3327 className = classPrefix + flag;
3328 changes[ flag ] = false;
3329 delete this.flags[ flag ];
3330 remove.push( className );
3331 }
3332
3333 if ( this.$flagged ) {
3334 this.$flagged.removeClass( remove );
3335 }
3336
3337 this.updateThemeClasses();
3338 this.emit( 'flag', changes );
3339
3340 return this;
3341 };
3342
3343 /**
3344 * Add one or more flags.
3345 *
3346 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
3347 * or an object keyed by flag name with a boolean value that indicates whether the flag should
3348 * be added (`true`) or removed (`false`).
3349 * @chainable
3350 * @return {OO.ui.Element} The element, for chaining
3351 * @fires flag
3352 */
3353 OO.ui.mixin.FlaggedElement.prototype.setFlags = function ( flags ) {
3354 var i, len, flag, className,
3355 changes = {},
3356 add = [],
3357 remove = [],
3358 classPrefix = 'oo-ui-flaggedElement-';
3359
3360 if ( typeof flags === 'string' ) {
3361 className = classPrefix + flags;
3362 // Set
3363 if ( !this.flags[ flags ] ) {
3364 this.flags[ flags ] = true;
3365 add.push( className );
3366 }
3367 } else if ( Array.isArray( flags ) ) {
3368 for ( i = 0, len = flags.length; i < len; i++ ) {
3369 flag = flags[ i ];
3370 className = classPrefix + flag;
3371 // Set
3372 if ( !this.flags[ flag ] ) {
3373 changes[ flag ] = true;
3374 this.flags[ flag ] = true;
3375 add.push( className );
3376 }
3377 }
3378 } else if ( OO.isPlainObject( flags ) ) {
3379 for ( flag in flags ) {
3380 className = classPrefix + flag;
3381 if ( flags[ flag ] ) {
3382 // Set
3383 if ( !this.flags[ flag ] ) {
3384 changes[ flag ] = true;
3385 this.flags[ flag ] = true;
3386 add.push( className );
3387 }
3388 } else {
3389 // Remove
3390 if ( this.flags[ flag ] ) {
3391 changes[ flag ] = false;
3392 delete this.flags[ flag ];
3393 remove.push( className );
3394 }
3395 }
3396 }
3397 }
3398
3399 if ( this.$flagged ) {
3400 this.$flagged
3401 .addClass( add )
3402 .removeClass( remove );
3403 }
3404
3405 this.updateThemeClasses();
3406 this.emit( 'flag', changes );
3407
3408 return this;
3409 };
3410
3411 /**
3412 * TitledElement is mixed into other classes to provide a `title` attribute.
3413 * Titles are rendered by the browser and are made visible when the user moves
3414 * the mouse over the element. Titles are not visible on touch devices.
3415 *
3416 * @example
3417 * // TitledElement provides a `title` attribute to the
3418 * // ButtonWidget class.
3419 * var button = new OO.ui.ButtonWidget( {
3420 * label: 'Button with Title',
3421 * title: 'I am a button'
3422 * } );
3423 * $( document.body ).append( button.$element );
3424 *
3425 * @abstract
3426 * @class
3427 *
3428 * @constructor
3429 * @param {Object} [config] Configuration options
3430 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
3431 * If this config is omitted, the title functionality is applied to $element, the
3432 * element created by the class.
3433 * @cfg {string|Function} [title] The title text or a function that returns text. If
3434 * this config is omitted, the value of the {@link #static-title static title} property is used.
3435 */
3436 OO.ui.mixin.TitledElement = function OoUiMixinTitledElement( config ) {
3437 // Configuration initialization
3438 config = config || {};
3439
3440 // Properties
3441 this.$titled = null;
3442 this.title = null;
3443
3444 // Initialization
3445 this.setTitle( config.title !== undefined ? config.title : this.constructor.static.title );
3446 this.setTitledElement( config.$titled || this.$element );
3447 };
3448
3449 /* Setup */
3450
3451 OO.initClass( OO.ui.mixin.TitledElement );
3452
3453 /* Static Properties */
3454
3455 /**
3456 * The title text, a function that returns text, or `null` for no title. The value of the static
3457 * property is overridden if the #title config option is used.
3458 *
3459 * @static
3460 * @inheritable
3461 * @property {string|Function|null}
3462 */
3463 OO.ui.mixin.TitledElement.static.title = null;
3464
3465 /* Methods */
3466
3467 /**
3468 * Set the titled element.
3469 *
3470 * This method is used to retarget a TitledElement mixin so that its functionality applies to the
3471 * specified element.
3472 * If an element is already set, the mixin’s effect on that element is removed before the new
3473 * element is set up.
3474 *
3475 * @param {jQuery} $titled Element that should use the 'titled' functionality
3476 */
3477 OO.ui.mixin.TitledElement.prototype.setTitledElement = function ( $titled ) {
3478 if ( this.$titled ) {
3479 this.$titled.removeAttr( 'title' );
3480 }
3481
3482 this.$titled = $titled;
3483 if ( this.title ) {
3484 this.updateTitle();
3485 }
3486 };
3487
3488 /**
3489 * Set title.
3490 *
3491 * @param {string|Function|null} title Title text, a function that returns text, or `null`
3492 * for no title
3493 * @chainable
3494 * @return {OO.ui.Element} The element, for chaining
3495 */
3496 OO.ui.mixin.TitledElement.prototype.setTitle = function ( title ) {
3497 title = typeof title === 'function' ? OO.ui.resolveMsg( title ) : title;
3498 title = ( typeof title === 'string' && title.length ) ? title : null;
3499
3500 if ( this.title !== title ) {
3501 this.title = title;
3502 this.updateTitle();
3503 }
3504
3505 return this;
3506 };
3507
3508 /**
3509 * Update the title attribute, in case of changes to title or accessKey.
3510 *
3511 * @protected
3512 * @chainable
3513 * @return {OO.ui.Element} The element, for chaining
3514 */
3515 OO.ui.mixin.TitledElement.prototype.updateTitle = function () {
3516 var title = this.getTitle();
3517 if ( this.$titled ) {
3518 if ( title !== null ) {
3519 // Only if this is an AccessKeyedElement
3520 if ( this.formatTitleWithAccessKey ) {
3521 title = this.formatTitleWithAccessKey( title );
3522 }
3523 this.$titled.attr( 'title', title );
3524 } else {
3525 this.$titled.removeAttr( 'title' );
3526 }
3527 }
3528 return this;
3529 };
3530
3531 /**
3532 * Get title.
3533 *
3534 * @return {string} Title string
3535 */
3536 OO.ui.mixin.TitledElement.prototype.getTitle = function () {
3537 return this.title;
3538 };
3539
3540 /**
3541 * AccessKeyedElement is mixed into other classes to provide an `accesskey` HTML attribute.
3542 * Access keys allow an user to go to a specific element by using
3543 * a shortcut combination of a browser specific keys + the key
3544 * set to the field.
3545 *
3546 * @example
3547 * // AccessKeyedElement provides an `accesskey` attribute to the
3548 * // ButtonWidget class.
3549 * var button = new OO.ui.ButtonWidget( {
3550 * label: 'Button with access key',
3551 * accessKey: 'k'
3552 * } );
3553 * $( document.body ).append( button.$element );
3554 *
3555 * @abstract
3556 * @class
3557 *
3558 * @constructor
3559 * @param {Object} [config] Configuration options
3560 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3561 * If this config is omitted, the access key functionality is applied to $element, the
3562 * element created by the class.
3563 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3564 * this config is omitted, no access key will be added.
3565 */
3566 OO.ui.mixin.AccessKeyedElement = function OoUiMixinAccessKeyedElement( config ) {
3567 // Configuration initialization
3568 config = config || {};
3569
3570 // Properties
3571 this.$accessKeyed = null;
3572 this.accessKey = null;
3573
3574 // Initialization
3575 this.setAccessKey( config.accessKey || null );
3576 this.setAccessKeyedElement( config.$accessKeyed || this.$element );
3577
3578 // If this is also a TitledElement and it initialized before we did, we may have
3579 // to update the title with the access key
3580 if ( this.updateTitle ) {
3581 this.updateTitle();
3582 }
3583 };
3584
3585 /* Setup */
3586
3587 OO.initClass( OO.ui.mixin.AccessKeyedElement );
3588
3589 /* Static Properties */
3590
3591 /**
3592 * The access key, a function that returns a key, or `null` for no access key.
3593 *
3594 * @static
3595 * @inheritable
3596 * @property {string|Function|null}
3597 */
3598 OO.ui.mixin.AccessKeyedElement.static.accessKey = null;
3599
3600 /* Methods */
3601
3602 /**
3603 * Set the access keyed element.
3604 *
3605 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to
3606 * the specified element.
3607 * If an element is already set, the mixin's effect on that element is removed before the new
3608 * element is set up.
3609 *
3610 * @param {jQuery} $accessKeyed Element that should use the 'access keyed' functionality
3611 */
3612 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKeyedElement = function ( $accessKeyed ) {
3613 if ( this.$accessKeyed ) {
3614 this.$accessKeyed.removeAttr( 'accesskey' );
3615 }
3616
3617 this.$accessKeyed = $accessKeyed;
3618 if ( this.accessKey ) {
3619 this.$accessKeyed.attr( 'accesskey', this.accessKey );
3620 }
3621 };
3622
3623 /**
3624 * Set access key.
3625 *
3626 * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no
3627 * access key
3628 * @chainable
3629 * @return {OO.ui.Element} The element, for chaining
3630 */
3631 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKey = function ( accessKey ) {
3632 accessKey = typeof accessKey === 'string' ? OO.ui.resolveMsg( accessKey ) : null;
3633
3634 if ( this.accessKey !== accessKey ) {
3635 if ( this.$accessKeyed ) {
3636 if ( accessKey !== null ) {
3637 this.$accessKeyed.attr( 'accesskey', accessKey );
3638 } else {
3639 this.$accessKeyed.removeAttr( 'accesskey' );
3640 }
3641 }
3642 this.accessKey = accessKey;
3643
3644 // Only if this is a TitledElement
3645 if ( this.updateTitle ) {
3646 this.updateTitle();
3647 }
3648 }
3649
3650 return this;
3651 };
3652
3653 /**
3654 * Get access key.
3655 *
3656 * @return {string} accessKey string
3657 */
3658 OO.ui.mixin.AccessKeyedElement.prototype.getAccessKey = function () {
3659 return this.accessKey;
3660 };
3661
3662 /**
3663 * Add information about the access key to the element's tooltip label.
3664 * (This is only public for hacky usage in FieldLayout.)
3665 *
3666 * @param {string} title Tooltip label for `title` attribute
3667 * @return {string}
3668 */
3669 OO.ui.mixin.AccessKeyedElement.prototype.formatTitleWithAccessKey = function ( title ) {
3670 var accessKey;
3671
3672 if ( !this.$accessKeyed ) {
3673 // Not initialized yet; the constructor will call updateTitle() which will rerun this
3674 // function.
3675 return title;
3676 }
3677 // Use jquery.accessKeyLabel if available to show modifiers, otherwise just display the
3678 // single key.
3679 if ( $.fn.updateTooltipAccessKeys && $.fn.updateTooltipAccessKeys.getAccessKeyLabel ) {
3680 accessKey = $.fn.updateTooltipAccessKeys.getAccessKeyLabel( this.$accessKeyed[ 0 ] );
3681 } else {
3682 accessKey = this.getAccessKey();
3683 }
3684 if ( accessKey ) {
3685 title += ' [' + accessKey + ']';
3686 }
3687 return title;
3688 };
3689
3690 /**
3691 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3692 * feels, and functionality can be customized via the class’s configuration options
3693 * and methods. Please see the [OOUI documentation on MediaWiki] [1] for more information
3694 * and examples.
3695 *
3696 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches
3697 *
3698 * @example
3699 * // A button widget.
3700 * var button = new OO.ui.ButtonWidget( {
3701 * label: 'Button with Icon',
3702 * icon: 'trash',
3703 * title: 'Remove'
3704 * } );
3705 * $( document.body ).append( button.$element );
3706 *
3707 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3708 *
3709 * @class
3710 * @extends OO.ui.Widget
3711 * @mixins OO.ui.mixin.ButtonElement
3712 * @mixins OO.ui.mixin.IconElement
3713 * @mixins OO.ui.mixin.IndicatorElement
3714 * @mixins OO.ui.mixin.LabelElement
3715 * @mixins OO.ui.mixin.TitledElement
3716 * @mixins OO.ui.mixin.FlaggedElement
3717 * @mixins OO.ui.mixin.TabIndexedElement
3718 * @mixins OO.ui.mixin.AccessKeyedElement
3719 *
3720 * @constructor
3721 * @param {Object} [config] Configuration options
3722 * @cfg {boolean} [active=false] Whether button should be shown as active
3723 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3724 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3725 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3726 */
3727 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
3728 // Configuration initialization
3729 config = config || {};
3730
3731 // Parent constructor
3732 OO.ui.ButtonWidget.parent.call( this, config );
3733
3734 // Mixin constructors
3735 OO.ui.mixin.ButtonElement.call( this, config );
3736 OO.ui.mixin.IconElement.call( this, config );
3737 OO.ui.mixin.IndicatorElement.call( this, config );
3738 OO.ui.mixin.LabelElement.call( this, config );
3739 OO.ui.mixin.TitledElement.call( this, $.extend( {
3740 $titled: this.$button
3741 }, config ) );
3742 OO.ui.mixin.FlaggedElement.call( this, config );
3743 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {
3744 $tabIndexed: this.$button
3745 }, config ) );
3746 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {
3747 $accessKeyed: this.$button
3748 }, config ) );
3749
3750 // Properties
3751 this.href = null;
3752 this.target = null;
3753 this.noFollow = false;
3754
3755 // Events
3756 this.connect( this, {
3757 disable: 'onDisable'
3758 } );
3759
3760 // Initialization
3761 this.$button.append( this.$icon, this.$label, this.$indicator );
3762 this.$element
3763 .addClass( 'oo-ui-buttonWidget' )
3764 .append( this.$button );
3765 this.setActive( config.active );
3766 this.setHref( config.href );
3767 this.setTarget( config.target );
3768 this.setNoFollow( config.noFollow );
3769 };
3770
3771 /* Setup */
3772
3773 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
3774 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.ButtonElement );
3775 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IconElement );
3776 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IndicatorElement );
3777 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.LabelElement );
3778 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TitledElement );
3779 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.FlaggedElement );
3780 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TabIndexedElement );
3781 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.AccessKeyedElement );
3782
3783 /* Static Properties */
3784
3785 /**
3786 * @static
3787 * @inheritdoc
3788 */
3789 OO.ui.ButtonWidget.static.cancelButtonMouseDownEvents = false;
3790
3791 /**
3792 * @static
3793 * @inheritdoc
3794 */
3795 OO.ui.ButtonWidget.static.tagName = 'span';
3796
3797 /* Methods */
3798
3799 /**
3800 * Get hyperlink location.
3801 *
3802 * @return {string} Hyperlink location
3803 */
3804 OO.ui.ButtonWidget.prototype.getHref = function () {
3805 return this.href;
3806 };
3807
3808 /**
3809 * Get hyperlink target.
3810 *
3811 * @return {string} Hyperlink target
3812 */
3813 OO.ui.ButtonWidget.prototype.getTarget = function () {
3814 return this.target;
3815 };
3816
3817 /**
3818 * Get search engine traversal hint.
3819 *
3820 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3821 */
3822 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
3823 return this.noFollow;
3824 };
3825
3826 /**
3827 * Set hyperlink location.
3828 *
3829 * @param {string|null} href Hyperlink location, null to remove
3830 * @chainable
3831 * @return {OO.ui.Widget} The widget, for chaining
3832 */
3833 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
3834 href = typeof href === 'string' ? href : null;
3835 if ( href !== null && !OO.ui.isSafeUrl( href ) ) {
3836 href = './' + href;
3837 }
3838
3839 if ( href !== this.href ) {
3840 this.href = href;
3841 this.updateHref();
3842 }
3843
3844 return this;
3845 };
3846
3847 /**
3848 * Update the `href` attribute, in case of changes to href or
3849 * disabled state.
3850 *
3851 * @private
3852 * @chainable
3853 * @return {OO.ui.Widget} The widget, for chaining
3854 */
3855 OO.ui.ButtonWidget.prototype.updateHref = function () {
3856 if ( this.href !== null && !this.isDisabled() ) {
3857 this.$button.attr( 'href', this.href );
3858 } else {
3859 this.$button.removeAttr( 'href' );
3860 }
3861
3862 return this;
3863 };
3864
3865 /**
3866 * Handle disable events.
3867 *
3868 * @private
3869 * @param {boolean} disabled Element is disabled
3870 */
3871 OO.ui.ButtonWidget.prototype.onDisable = function () {
3872 this.updateHref();
3873 };
3874
3875 /**
3876 * Set hyperlink target.
3877 *
3878 * @param {string|null} target Hyperlink target, null to remove
3879 * @return {OO.ui.Widget} The widget, for chaining
3880 */
3881 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
3882 target = typeof target === 'string' ? target : null;
3883
3884 if ( target !== this.target ) {
3885 this.target = target;
3886 if ( target !== null ) {
3887 this.$button.attr( 'target', target );
3888 } else {
3889 this.$button.removeAttr( 'target' );
3890 }
3891 }
3892
3893 return this;
3894 };
3895
3896 /**
3897 * Set search engine traversal hint.
3898 *
3899 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3900 * @return {OO.ui.Widget} The widget, for chaining
3901 */
3902 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
3903 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
3904
3905 if ( noFollow !== this.noFollow ) {
3906 this.noFollow = noFollow;
3907 if ( noFollow ) {
3908 this.$button.attr( 'rel', 'nofollow' );
3909 } else {
3910 this.$button.removeAttr( 'rel' );
3911 }
3912 }
3913
3914 return this;
3915 };
3916
3917 // Override method visibility hints from ButtonElement
3918 /**
3919 * @method setActive
3920 * @inheritdoc
3921 */
3922 /**
3923 * @method isActive
3924 * @inheritdoc
3925 */
3926
3927 /**
3928 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3929 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3930 * removed, and cleared from the group.
3931 *
3932 * @example
3933 * // A ButtonGroupWidget with two buttons.
3934 * var button1 = new OO.ui.PopupButtonWidget( {
3935 * label: 'Select a category',
3936 * icon: 'menu',
3937 * popup: {
3938 * $content: $( '<p>List of categories…</p>' ),
3939 * padded: true,
3940 * align: 'left'
3941 * }
3942 * } ),
3943 * button2 = new OO.ui.ButtonWidget( {
3944 * label: 'Add item'
3945 * } ),
3946 * buttonGroup = new OO.ui.ButtonGroupWidget( {
3947 * items: [ button1, button2 ]
3948 * } );
3949 * $( document.body ).append( buttonGroup.$element );
3950 *
3951 * @class
3952 * @extends OO.ui.Widget
3953 * @mixins OO.ui.mixin.GroupElement
3954 * @mixins OO.ui.mixin.TitledElement
3955 *
3956 * @constructor
3957 * @param {Object} [config] Configuration options
3958 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
3959 */
3960 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
3961 // Configuration initialization
3962 config = config || {};
3963
3964 // Parent constructor
3965 OO.ui.ButtonGroupWidget.parent.call( this, config );
3966
3967 // Mixin constructors
3968 OO.ui.mixin.GroupElement.call( this, $.extend( {
3969 $group: this.$element
3970 }, config ) );
3971 OO.ui.mixin.TitledElement.call( this, config );
3972
3973 // Initialization
3974 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
3975 if ( Array.isArray( config.items ) ) {
3976 this.addItems( config.items );
3977 }
3978 };
3979
3980 /* Setup */
3981
3982 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
3983 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.GroupElement );
3984 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.TitledElement );
3985
3986 /* Static Properties */
3987
3988 /**
3989 * @static
3990 * @inheritdoc
3991 */
3992 OO.ui.ButtonGroupWidget.static.tagName = 'span';
3993
3994 /* Methods */
3995
3996 /**
3997 * Focus the widget
3998 *
3999 * @chainable
4000 * @return {OO.ui.Widget} The widget, for chaining
4001 */
4002 OO.ui.ButtonGroupWidget.prototype.focus = function () {
4003 if ( !this.isDisabled() ) {
4004 if ( this.items[ 0 ] ) {
4005 this.items[ 0 ].focus();
4006 }
4007 }
4008 return this;
4009 };
4010
4011 /**
4012 * @inheritdoc
4013 */
4014 OO.ui.ButtonGroupWidget.prototype.simulateLabelClick = function () {
4015 this.focus();
4016 };
4017
4018 /**
4019 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}.
4020 * In general, IconWidgets should be used with OO.ui.LabelWidget, which creates a label that
4021 * identifies the icon’s function. See the [OOUI documentation on MediaWiki] [1]
4022 * for a list of icons included in the library.
4023 *
4024 * @example
4025 * // An IconWidget with a label via LabelWidget.
4026 * var myIcon = new OO.ui.IconWidget( {
4027 * icon: 'help',
4028 * title: 'Help'
4029 * } ),
4030 * // Create a label.
4031 * iconLabel = new OO.ui.LabelWidget( {
4032 * label: 'Help'
4033 * } );
4034 * $( document.body ).append( myIcon.$element, iconLabel.$element );
4035 *
4036 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
4037 *
4038 * @class
4039 * @extends OO.ui.Widget
4040 * @mixins OO.ui.mixin.IconElement
4041 * @mixins OO.ui.mixin.TitledElement
4042 * @mixins OO.ui.mixin.LabelElement
4043 * @mixins OO.ui.mixin.FlaggedElement
4044 *
4045 * @constructor
4046 * @param {Object} [config] Configuration options
4047 */
4048 OO.ui.IconWidget = function OoUiIconWidget( config ) {
4049 // Configuration initialization
4050 config = config || {};
4051
4052 // Parent constructor
4053 OO.ui.IconWidget.parent.call( this, config );
4054
4055 // Mixin constructors
4056 OO.ui.mixin.IconElement.call( this, $.extend( {
4057 $icon: this.$element
4058 }, config ) );
4059 OO.ui.mixin.TitledElement.call( this, $.extend( {
4060 $titled: this.$element
4061 }, config ) );
4062 OO.ui.mixin.LabelElement.call( this, $.extend( {
4063 $label: this.$element,
4064 invisibleLabel: true
4065 }, config ) );
4066 OO.ui.mixin.FlaggedElement.call( this, $.extend( {
4067 $flagged: this.$element
4068 }, config ) );
4069
4070 // Initialization
4071 this.$element.addClass( 'oo-ui-iconWidget' );
4072 // Remove class added by LabelElement initialization. It causes unexpected CSS to apply when
4073 // nested in other widgets, because this widget used to not mix in LabelElement.
4074 this.$element.removeClass( 'oo-ui-labelElement-label' );
4075 };
4076
4077 /* Setup */
4078
4079 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
4080 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.IconElement );
4081 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.TitledElement );
4082 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.LabelElement );
4083 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.FlaggedElement );
4084
4085 /* Static Properties */
4086
4087 /**
4088 * @static
4089 * @inheritdoc
4090 */
4091 OO.ui.IconWidget.static.tagName = 'span';
4092
4093 /**
4094 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
4095 * attention to the status of an item or to clarify the function within a control. For a list of
4096 * indicators included in the library, please see the [OOUI documentation on MediaWiki][1].
4097 *
4098 * @example
4099 * // An indicator widget.
4100 * var indicator1 = new OO.ui.IndicatorWidget( {
4101 * indicator: 'required'
4102 * } ),
4103 * // Create a fieldset layout to add a label.
4104 * fieldset = new OO.ui.FieldsetLayout();
4105 * fieldset.addItems( [
4106 * new OO.ui.FieldLayout( indicator1, {
4107 * label: 'A required indicator:'
4108 * } )
4109 * ] );
4110 * $( document.body ).append( fieldset.$element );
4111 *
4112 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
4113 *
4114 * @class
4115 * @extends OO.ui.Widget
4116 * @mixins OO.ui.mixin.IndicatorElement
4117 * @mixins OO.ui.mixin.TitledElement
4118 * @mixins OO.ui.mixin.LabelElement
4119 *
4120 * @constructor
4121 * @param {Object} [config] Configuration options
4122 */
4123 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
4124 // Configuration initialization
4125 config = config || {};
4126
4127 // Parent constructor
4128 OO.ui.IndicatorWidget.parent.call( this, config );
4129
4130 // Mixin constructors
4131 OO.ui.mixin.IndicatorElement.call( this, $.extend( {
4132 $indicator: this.$element
4133 }, config ) );
4134 OO.ui.mixin.TitledElement.call( this, $.extend( {
4135 $titled: this.$element
4136 }, config ) );
4137 OO.ui.mixin.LabelElement.call( this, $.extend( {
4138 $label: this.$element,
4139 invisibleLabel: true
4140 }, config ) );
4141
4142 // Initialization
4143 this.$element.addClass( 'oo-ui-indicatorWidget' );
4144 // Remove class added by LabelElement initialization. It causes unexpected CSS to apply when
4145 // nested in other widgets, because this widget used to not mix in LabelElement.
4146 this.$element.removeClass( 'oo-ui-labelElement-label' );
4147 };
4148
4149 /* Setup */
4150
4151 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
4152 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.IndicatorElement );
4153 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.TitledElement );
4154 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.LabelElement );
4155
4156 /* Static Properties */
4157
4158 /**
4159 * @static
4160 * @inheritdoc
4161 */
4162 OO.ui.IndicatorWidget.static.tagName = 'span';
4163
4164 /**
4165 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
4166 * be configured with a `label` option that is set to a string, a label node, or a function:
4167 *
4168 * - String: a plaintext string
4169 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
4170 * label that includes a link or special styling, such as a gray color or additional
4171 * graphical elements.
4172 * - Function: a function that will produce a string in the future. Functions are used
4173 * in cases where the value of the label is not currently defined.
4174 *
4175 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget},
4176 * which will come into focus when the label is clicked.
4177 *
4178 * @example
4179 * // Two LabelWidgets.
4180 * var label1 = new OO.ui.LabelWidget( {
4181 * label: 'plaintext label'
4182 * } ),
4183 * label2 = new OO.ui.LabelWidget( {
4184 * label: $( '<a>' ).attr( 'href', 'default.html' ).text( 'jQuery label' )
4185 * } ),
4186 * // Create a fieldset layout with fields for each example.
4187 * fieldset = new OO.ui.FieldsetLayout();
4188 * fieldset.addItems( [
4189 * new OO.ui.FieldLayout( label1 ),
4190 * new OO.ui.FieldLayout( label2 )
4191 * ] );
4192 * $( document.body ).append( fieldset.$element );
4193 *
4194 * @class
4195 * @extends OO.ui.Widget
4196 * @mixins OO.ui.mixin.LabelElement
4197 * @mixins OO.ui.mixin.TitledElement
4198 *
4199 * @constructor
4200 * @param {Object} [config] Configuration options
4201 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
4202 * Clicking the label will focus the specified input field.
4203 */
4204 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
4205 // Configuration initialization
4206 config = config || {};
4207
4208 // Parent constructor
4209 OO.ui.LabelWidget.parent.call( this, config );
4210
4211 // Mixin constructors
4212 OO.ui.mixin.LabelElement.call( this, $.extend( {
4213 $label: this.$element
4214 }, config ) );
4215 OO.ui.mixin.TitledElement.call( this, config );
4216
4217 // Properties
4218 this.input = config.input;
4219
4220 // Initialization
4221 if ( this.input ) {
4222 if ( this.input.getInputId() ) {
4223 this.$element.attr( 'for', this.input.getInputId() );
4224 } else {
4225 this.$label.on( 'click', function () {
4226 this.input.simulateLabelClick();
4227 }.bind( this ) );
4228 }
4229 }
4230 this.$element.addClass( 'oo-ui-labelWidget' );
4231 };
4232
4233 /* Setup */
4234
4235 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
4236 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.LabelElement );
4237 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.TitledElement );
4238
4239 /* Static Properties */
4240
4241 /**
4242 * @static
4243 * @inheritdoc
4244 */
4245 OO.ui.LabelWidget.static.tagName = 'label';
4246
4247 /**
4248 * PendingElement is a mixin that is used to create elements that notify users that something is
4249 * happening and that they should wait before proceeding. The pending state is visually represented
4250 * with a pending texture that appears in the head of a pending
4251 * {@link OO.ui.ProcessDialog process dialog} or in the input field of a
4252 * {@link OO.ui.TextInputWidget text input widget}.
4253 *
4254 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked
4255 * as pending, but only when used in {@link OO.ui.MessageDialog message dialogs}. The behavior is
4256 * not currently supported for action widgets used in process dialogs.
4257 *
4258 * @example
4259 * function MessageDialog( config ) {
4260 * MessageDialog.parent.call( this, config );
4261 * }
4262 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
4263 *
4264 * MessageDialog.static.name = 'myMessageDialog';
4265 * MessageDialog.static.actions = [
4266 * { action: 'save', label: 'Done', flags: 'primary' },
4267 * { label: 'Cancel', flags: 'safe' }
4268 * ];
4269 *
4270 * MessageDialog.prototype.initialize = function () {
4271 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
4272 * this.content = new OO.ui.PanelLayout( { padded: true } );
4273 * this.content.$element.append( '<p>Click the \'Done\' action widget to see its pending ' +
4274 * 'state. Note that action widgets can be marked pending in message dialogs but not ' +
4275 * 'process dialogs.</p>' );
4276 * this.$body.append( this.content.$element );
4277 * };
4278 * MessageDialog.prototype.getBodyHeight = function () {
4279 * return 100;
4280 * }
4281 * MessageDialog.prototype.getActionProcess = function ( action ) {
4282 * var dialog = this;
4283 * if ( action === 'save' ) {
4284 * dialog.getActions().get({actions: 'save'})[0].pushPending();
4285 * return new OO.ui.Process()
4286 * .next( 1000 )
4287 * .next( function () {
4288 * dialog.getActions().get({actions: 'save'})[0].popPending();
4289 * } );
4290 * }
4291 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
4292 * };
4293 *
4294 * var windowManager = new OO.ui.WindowManager();
4295 * $( document.body ).append( windowManager.$element );
4296 *
4297 * var dialog = new MessageDialog();
4298 * windowManager.addWindows( [ dialog ] );
4299 * windowManager.openWindow( dialog );
4300 *
4301 * @abstract
4302 * @class
4303 *
4304 * @constructor
4305 * @param {Object} [config] Configuration options
4306 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
4307 */
4308 OO.ui.mixin.PendingElement = function OoUiMixinPendingElement( config ) {
4309 // Configuration initialization
4310 config = config || {};
4311
4312 // Properties
4313 this.pending = 0;
4314 this.$pending = null;
4315
4316 // Initialisation
4317 this.setPendingElement( config.$pending || this.$element );
4318 };
4319
4320 /* Setup */
4321
4322 OO.initClass( OO.ui.mixin.PendingElement );
4323
4324 /* Methods */
4325
4326 /**
4327 * Set the pending element (and clean up any existing one).
4328 *
4329 * @param {jQuery} $pending The element to set to pending.
4330 */
4331 OO.ui.mixin.PendingElement.prototype.setPendingElement = function ( $pending ) {
4332 if ( this.$pending ) {
4333 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
4334 }
4335
4336 this.$pending = $pending;
4337 if ( this.pending > 0 ) {
4338 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
4339 }
4340 };
4341
4342 /**
4343 * Check if an element is pending.
4344 *
4345 * @return {boolean} Element is pending
4346 */
4347 OO.ui.mixin.PendingElement.prototype.isPending = function () {
4348 return !!this.pending;
4349 };
4350
4351 /**
4352 * Increase the pending counter. The pending state will remain active until the counter is zero
4353 * (i.e., the number of calls to #pushPending and #popPending is the same).
4354 *
4355 * @chainable
4356 * @return {OO.ui.Element} The element, for chaining
4357 */
4358 OO.ui.mixin.PendingElement.prototype.pushPending = function () {
4359 if ( this.pending === 0 ) {
4360 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
4361 this.updateThemeClasses();
4362 }
4363 this.pending++;
4364
4365 return this;
4366 };
4367
4368 /**
4369 * Decrease the pending counter. The pending state will remain active until the counter is zero
4370 * (i.e., the number of calls to #pushPending and #popPending is the same).
4371 *
4372 * @chainable
4373 * @return {OO.ui.Element} The element, for chaining
4374 */
4375 OO.ui.mixin.PendingElement.prototype.popPending = function () {
4376 if ( this.pending === 1 ) {
4377 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
4378 this.updateThemeClasses();
4379 }
4380 this.pending = Math.max( 0, this.pending - 1 );
4381
4382 return this;
4383 };
4384
4385 /**
4386 * Element that will stick adjacent to a specified container, even when it is inserted elsewhere
4387 * in the document (for example, in an OO.ui.Window's $overlay).
4388 *
4389 * The elements's position is automatically calculated and maintained when window is resized or the
4390 * page is scrolled. If you reposition the container manually, you have to call #position to make
4391 * sure the element is still placed correctly.
4392 *
4393 * As positioning is only possible when both the element and the container are attached to the DOM
4394 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
4395 * the #toggle method to display a floating popup, for example.
4396 *
4397 * @abstract
4398 * @class
4399 *
4400 * @constructor
4401 * @param {Object} [config] Configuration options
4402 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
4403 * @cfg {jQuery} [$floatableContainer] Node to position adjacent to
4404 * @cfg {string} [verticalPosition='below'] Where to position $floatable vertically:
4405 * 'below': Directly below $floatableContainer, aligning f's top edge with fC's bottom edge
4406 * 'above': Directly above $floatableContainer, aligning f's bottom edge with fC's top edge
4407 * 'top': Align the top edge with $floatableContainer's top edge
4408 * 'bottom': Align the bottom edge with $floatableContainer's bottom edge
4409 * 'center': Vertically align the center with $floatableContainer's center
4410 * @cfg {string} [horizontalPosition='start'] Where to position $floatable horizontally:
4411 * 'before': Directly before $floatableContainer, aligning f's end edge with fC's start edge
4412 * 'after': Directly after $floatableContainer, aligning f's start edge with fC's end edge
4413 * 'start': Align the start (left in LTR, right in RTL) edge with $floatableContainer's start edge
4414 * 'end': Align the end (right in LTR, left in RTL) edge with $floatableContainer's end edge
4415 * 'center': Horizontally align the center with $floatableContainer's center
4416 * @cfg {boolean} [hideWhenOutOfView=true] Whether to hide the floatable element if the container
4417 * is out of view
4418 */
4419 OO.ui.mixin.FloatableElement = function OoUiMixinFloatableElement( config ) {
4420 // Configuration initialization
4421 config = config || {};
4422
4423 // Properties
4424 this.$floatable = null;
4425 this.$floatableContainer = null;
4426 this.$floatableWindow = null;
4427 this.$floatableClosestScrollable = null;
4428 this.floatableOutOfView = false;
4429 this.onFloatableScrollHandler = this.position.bind( this );
4430 this.onFloatableWindowResizeHandler = this.position.bind( this );
4431
4432 // Initialization
4433 this.setFloatableContainer( config.$floatableContainer );
4434 this.setFloatableElement( config.$floatable || this.$element );
4435 this.setVerticalPosition( config.verticalPosition || 'below' );
4436 this.setHorizontalPosition( config.horizontalPosition || 'start' );
4437 this.hideWhenOutOfView = config.hideWhenOutOfView === undefined ?
4438 true : !!config.hideWhenOutOfView;
4439 };
4440
4441 /* Methods */
4442
4443 /**
4444 * Set floatable element.
4445 *
4446 * If an element is already set, it will be cleaned up before setting up the new element.
4447 *
4448 * @param {jQuery} $floatable Element to make floatable
4449 */
4450 OO.ui.mixin.FloatableElement.prototype.setFloatableElement = function ( $floatable ) {
4451 if ( this.$floatable ) {
4452 this.$floatable.removeClass( 'oo-ui-floatableElement-floatable' );
4453 this.$floatable.css( { left: '', top: '' } );
4454 }
4455
4456 this.$floatable = $floatable.addClass( 'oo-ui-floatableElement-floatable' );
4457 this.position();
4458 };
4459
4460 /**
4461 * Set floatable container.
4462 *
4463 * The element will be positioned relative to the specified container.
4464 *
4465 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
4466 */
4467 OO.ui.mixin.FloatableElement.prototype.setFloatableContainer = function ( $floatableContainer ) {
4468 this.$floatableContainer = $floatableContainer;
4469 if ( this.$floatable ) {
4470 this.position();
4471 }
4472 };
4473
4474 /**
4475 * Change how the element is positioned vertically.
4476 *
4477 * @param {string} position 'below', 'above', 'top', 'bottom' or 'center'
4478 */
4479 OO.ui.mixin.FloatableElement.prototype.setVerticalPosition = function ( position ) {
4480 if ( [ 'below', 'above', 'top', 'bottom', 'center' ].indexOf( position ) === -1 ) {
4481 throw new Error( 'Invalid value for vertical position: ' + position );
4482 }
4483 if ( this.verticalPosition !== position ) {
4484 this.verticalPosition = position;
4485 if ( this.$floatable ) {
4486 this.position();
4487 }
4488 }
4489 };
4490
4491 /**
4492 * Change how the element is positioned horizontally.
4493 *
4494 * @param {string} position 'before', 'after', 'start', 'end' or 'center'
4495 */
4496 OO.ui.mixin.FloatableElement.prototype.setHorizontalPosition = function ( position ) {
4497 if ( [ 'before', 'after', 'start', 'end', 'center' ].indexOf( position ) === -1 ) {
4498 throw new Error( 'Invalid value for horizontal position: ' + position );
4499 }
4500 if ( this.horizontalPosition !== position ) {
4501 this.horizontalPosition = position;
4502 if ( this.$floatable ) {
4503 this.position();
4504 }
4505 }
4506 };
4507
4508 /**
4509 * Toggle positioning.
4510 *
4511 * Do not turn positioning on until after the element is attached to the DOM and visible.
4512 *
4513 * @param {boolean} [positioning] Enable positioning, omit to toggle
4514 * @chainable
4515 * @return {OO.ui.Element} The element, for chaining
4516 */
4517 OO.ui.mixin.FloatableElement.prototype.togglePositioning = function ( positioning ) {
4518 var closestScrollableOfContainer;
4519
4520 if ( !this.$floatable || !this.$floatableContainer ) {
4521 return this;
4522 }
4523
4524 positioning = positioning === undefined ? !this.positioning : !!positioning;
4525
4526 if ( positioning && !this.warnedUnattached && !this.isElementAttached() ) {
4527 OO.ui.warnDeprecation( 'FloatableElement#togglePositioning: Before calling this method, the element must be attached to the DOM.' );
4528 this.warnedUnattached = true;
4529 }
4530
4531 if ( this.positioning !== positioning ) {
4532 this.positioning = positioning;
4533
4534 closestScrollableOfContainer = OO.ui.Element.static.getClosestScrollableContainer(
4535 this.$floatableContainer[ 0 ]
4536 );
4537 // If the scrollable is the root, we have to listen to scroll events
4538 // on the window because of browser inconsistencies.
4539 if ( $( closestScrollableOfContainer ).is( 'html, body' ) ) {
4540 closestScrollableOfContainer = OO.ui.Element.static.getWindow(
4541 closestScrollableOfContainer
4542 );
4543 }
4544
4545 if ( positioning ) {
4546 this.$floatableWindow = $( this.getElementWindow() );
4547 this.$floatableWindow.on( 'resize', this.onFloatableWindowResizeHandler );
4548
4549 this.$floatableClosestScrollable = $( closestScrollableOfContainer );
4550 this.$floatableClosestScrollable.on( 'scroll', this.onFloatableScrollHandler );
4551
4552 // Initial position after visible
4553 this.position();
4554 } else {
4555 if ( this.$floatableWindow ) {
4556 this.$floatableWindow.off( 'resize', this.onFloatableWindowResizeHandler );
4557 this.$floatableWindow = null;
4558 }
4559
4560 if ( this.$floatableClosestScrollable ) {
4561 this.$floatableClosestScrollable.off( 'scroll', this.onFloatableScrollHandler );
4562 this.$floatableClosestScrollable = null;
4563 }
4564
4565 this.$floatable.css( { left: '', right: '', top: '' } );
4566 }
4567 }
4568
4569 return this;
4570 };
4571
4572 /**
4573 * Check whether the bottom edge of the given element is within the viewport of the given
4574 * container.
4575 *
4576 * @private
4577 * @param {jQuery} $element
4578 * @param {jQuery} $container
4579 * @return {boolean}
4580 */
4581 OO.ui.mixin.FloatableElement.prototype.isElementInViewport = function ( $element, $container ) {
4582 var elemRect, contRect, topEdgeInBounds, bottomEdgeInBounds, leftEdgeInBounds,
4583 rightEdgeInBounds, startEdgeInBounds, endEdgeInBounds, viewportSpacing,
4584 direction = $element.css( 'direction' );
4585
4586 elemRect = $element[ 0 ].getBoundingClientRect();
4587 if ( $container[ 0 ] === window ) {
4588 viewportSpacing = OO.ui.getViewportSpacing();
4589 contRect = {
4590 top: 0,
4591 left: 0,
4592 right: document.documentElement.clientWidth,
4593 bottom: document.documentElement.clientHeight
4594 };
4595 contRect.top += viewportSpacing.top;
4596 contRect.left += viewportSpacing.left;
4597 contRect.right -= viewportSpacing.right;
4598 contRect.bottom -= viewportSpacing.bottom;
4599 } else {
4600 contRect = $container[ 0 ].getBoundingClientRect();
4601 }
4602
4603 topEdgeInBounds = elemRect.top >= contRect.top && elemRect.top <= contRect.bottom;
4604 bottomEdgeInBounds = elemRect.bottom >= contRect.top && elemRect.bottom <= contRect.bottom;
4605 leftEdgeInBounds = elemRect.left >= contRect.left && elemRect.left <= contRect.right;
4606 rightEdgeInBounds = elemRect.right >= contRect.left && elemRect.right <= contRect.right;
4607 if ( direction === 'rtl' ) {
4608 startEdgeInBounds = rightEdgeInBounds;
4609 endEdgeInBounds = leftEdgeInBounds;
4610 } else {
4611 startEdgeInBounds = leftEdgeInBounds;
4612 endEdgeInBounds = rightEdgeInBounds;
4613 }
4614
4615 if ( this.verticalPosition === 'below' && !bottomEdgeInBounds ) {
4616 return false;
4617 }
4618 if ( this.verticalPosition === 'above' && !topEdgeInBounds ) {
4619 return false;
4620 }
4621 if ( this.horizontalPosition === 'before' && !startEdgeInBounds ) {
4622 return false;
4623 }
4624 if ( this.horizontalPosition === 'after' && !endEdgeInBounds ) {
4625 return false;
4626 }
4627
4628 // The other positioning values are all about being inside the container,
4629 // so in those cases all we care about is that any part of the container is visible.
4630 return elemRect.top <= contRect.bottom && elemRect.bottom >= contRect.top &&
4631 elemRect.left <= contRect.right && elemRect.right >= contRect.left;
4632 };
4633
4634 /**
4635 * Check if the floatable is hidden to the user because it was offscreen.
4636 *
4637 * @return {boolean} Floatable is out of view
4638 */
4639 OO.ui.mixin.FloatableElement.prototype.isFloatableOutOfView = function () {
4640 return this.floatableOutOfView;
4641 };
4642
4643 /**
4644 * Position the floatable below its container.
4645 *
4646 * This should only be done when both of them are attached to the DOM and visible.
4647 *
4648 * @chainable
4649 * @return {OO.ui.Element} The element, for chaining
4650 */
4651 OO.ui.mixin.FloatableElement.prototype.position = function () {
4652 if ( !this.positioning ) {
4653 return this;
4654 }
4655
4656 if ( !(
4657 // To continue, some things need to be true:
4658 // The element must actually be in the DOM
4659 this.isElementAttached() && (
4660 // The closest scrollable is the current window
4661 this.$floatableClosestScrollable[ 0 ] === this.getElementWindow() ||
4662 // OR is an element in the element's DOM
4663 $.contains( this.getElementDocument(), this.$floatableClosestScrollable[ 0 ] )
4664 )
4665 ) ) {
4666 // Abort early if important parts of the widget are no longer attached to the DOM
4667 return this;
4668 }
4669
4670 this.floatableOutOfView = this.hideWhenOutOfView &&
4671 !this.isElementInViewport( this.$floatableContainer, this.$floatableClosestScrollable );
4672 if ( this.floatableOutOfView ) {
4673 this.$floatable.addClass( 'oo-ui-element-hidden' );
4674 return this;
4675 } else {
4676 this.$floatable.removeClass( 'oo-ui-element-hidden' );
4677 }
4678
4679 this.$floatable.css( this.computePosition() );
4680
4681 // We updated the position, so re-evaluate the clipping state.
4682 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
4683 // will not notice the need to update itself.)
4684 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here.
4685 // Why does it not listen to the right events in the right places?
4686 if ( this.clip ) {
4687 this.clip();
4688 }
4689
4690 return this;
4691 };
4692
4693 /**
4694 * Compute how #$floatable should be positioned based on the position of #$floatableContainer
4695 * and the positioning settings. This is a helper for #position that shouldn't be called directly,
4696 * but may be overridden by subclasses if they want to change or add to the positioning logic.
4697 *
4698 * @return {Object} New position to apply with .css(). Keys are 'top', 'left', 'bottom' and 'right'.
4699 */
4700 OO.ui.mixin.FloatableElement.prototype.computePosition = function () {
4701 var isBody, scrollableX, scrollableY, containerPos,
4702 horizScrollbarHeight, vertScrollbarWidth, scrollTop, scrollLeft,
4703 newPos = { top: '', left: '', bottom: '', right: '' },
4704 direction = this.$floatableContainer.css( 'direction' ),
4705 $offsetParent = this.$floatable.offsetParent();
4706
4707 if ( $offsetParent.is( 'html' ) ) {
4708 // The innerHeight/Width and clientHeight/Width calculations don't work well on the
4709 // <html> element, but they do work on the <body>
4710 $offsetParent = $( $offsetParent[ 0 ].ownerDocument.body );
4711 }
4712 isBody = $offsetParent.is( 'body' );
4713 scrollableX = $offsetParent.css( 'overflow-x' ) === 'scroll' ||
4714 $offsetParent.css( 'overflow-x' ) === 'auto';
4715 scrollableY = $offsetParent.css( 'overflow-y' ) === 'scroll' ||
4716 $offsetParent.css( 'overflow-y' ) === 'auto';
4717
4718 vertScrollbarWidth = $offsetParent.innerWidth() - $offsetParent.prop( 'clientWidth' );
4719 horizScrollbarHeight = $offsetParent.innerHeight() - $offsetParent.prop( 'clientHeight' );
4720 // We don't need to compute and add scrollTop and scrollLeft if the scrollable container
4721 // is the body, or if it isn't scrollable
4722 scrollTop = scrollableY && !isBody ?
4723 $offsetParent.scrollTop() : 0;
4724 scrollLeft = scrollableX && !isBody ?
4725 OO.ui.Element.static.getScrollLeft( $offsetParent[ 0 ] ) : 0;
4726
4727 // Avoid passing the <body> to getRelativePosition(), because it won't return what we expect
4728 // if the <body> has a margin
4729 containerPos = isBody ?
4730 this.$floatableContainer.offset() :
4731 OO.ui.Element.static.getRelativePosition( this.$floatableContainer, $offsetParent );
4732 containerPos.bottom = containerPos.top + this.$floatableContainer.outerHeight();
4733 containerPos.right = containerPos.left + this.$floatableContainer.outerWidth();
4734 containerPos.start = direction === 'rtl' ? containerPos.right : containerPos.left;
4735 containerPos.end = direction === 'rtl' ? containerPos.left : containerPos.right;
4736
4737 if ( this.verticalPosition === 'below' ) {
4738 newPos.top = containerPos.bottom;
4739 } else if ( this.verticalPosition === 'above' ) {
4740 newPos.bottom = $offsetParent.outerHeight() - containerPos.top;
4741 } else if ( this.verticalPosition === 'top' ) {
4742 newPos.top = containerPos.top;
4743 } else if ( this.verticalPosition === 'bottom' ) {
4744 newPos.bottom = $offsetParent.outerHeight() - containerPos.bottom;
4745 } else if ( this.verticalPosition === 'center' ) {
4746 newPos.top = containerPos.top +
4747 ( this.$floatableContainer.height() - this.$floatable.height() ) / 2;
4748 }
4749
4750 if ( this.horizontalPosition === 'before' ) {
4751 newPos.end = containerPos.start;
4752 } else if ( this.horizontalPosition === 'after' ) {
4753 newPos.start = containerPos.end;
4754 } else if ( this.horizontalPosition === 'start' ) {
4755 newPos.start = containerPos.start;
4756 } else if ( this.horizontalPosition === 'end' ) {
4757 newPos.end = containerPos.end;
4758 } else if ( this.horizontalPosition === 'center' ) {
4759 newPos.left = containerPos.left +
4760 ( this.$floatableContainer.width() - this.$floatable.width() ) / 2;
4761 }
4762
4763 if ( newPos.start !== undefined ) {
4764 if ( direction === 'rtl' ) {
4765 newPos.right = ( isBody ? $( $offsetParent[ 0 ].ownerDocument.documentElement ) :
4766 $offsetParent ).outerWidth() - newPos.start;
4767 } else {
4768 newPos.left = newPos.start;
4769 }
4770 delete newPos.start;
4771 }
4772 if ( newPos.end !== undefined ) {
4773 if ( direction === 'rtl' ) {
4774 newPos.left = newPos.end;
4775 } else {
4776 newPos.right = ( isBody ? $( $offsetParent[ 0 ].ownerDocument.documentElement ) :
4777 $offsetParent ).outerWidth() - newPos.end;
4778 }
4779 delete newPos.end;
4780 }
4781
4782 // Account for scroll position
4783 if ( newPos.top !== '' ) {
4784 newPos.top += scrollTop;
4785 }
4786 if ( newPos.bottom !== '' ) {
4787 newPos.bottom -= scrollTop;
4788 }
4789 if ( newPos.left !== '' ) {
4790 newPos.left += scrollLeft;
4791 }
4792 if ( newPos.right !== '' ) {
4793 newPos.right -= scrollLeft;
4794 }
4795
4796 // Account for scrollbar gutter
4797 if ( newPos.bottom !== '' ) {
4798 newPos.bottom -= horizScrollbarHeight;
4799 }
4800 if ( direction === 'rtl' ) {
4801 if ( newPos.left !== '' ) {
4802 newPos.left -= vertScrollbarWidth;
4803 }
4804 } else {
4805 if ( newPos.right !== '' ) {
4806 newPos.right -= vertScrollbarWidth;
4807 }
4808 }
4809
4810 return newPos;
4811 };
4812
4813 /**
4814 * Element that can be automatically clipped to visible boundaries.
4815 *
4816 * Whenever the element's natural height changes, you have to call
4817 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
4818 * clipping correctly.
4819 *
4820 * The dimensions of #$clippableContainer will be compared to the boundaries of the
4821 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
4822 * then #$clippable will be given a fixed reduced height and/or width and will be made
4823 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
4824 * but you can build a static footer by setting #$clippableContainer to an element that contains
4825 * #$clippable and the footer.
4826 *
4827 * @abstract
4828 * @class
4829 *
4830 * @constructor
4831 * @param {Object} [config] Configuration options
4832 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
4833 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
4834 * omit to use #$clippable
4835 */
4836 OO.ui.mixin.ClippableElement = function OoUiMixinClippableElement( config ) {
4837 // Configuration initialization
4838 config = config || {};
4839
4840 // Properties
4841 this.$clippable = null;
4842 this.$clippableContainer = null;
4843 this.clipping = false;
4844 this.clippedHorizontally = false;
4845 this.clippedVertically = false;
4846 this.$clippableScrollableContainer = null;
4847 this.$clippableScroller = null;
4848 this.$clippableWindow = null;
4849 this.idealWidth = null;
4850 this.idealHeight = null;
4851 this.onClippableScrollHandler = this.clip.bind( this );
4852 this.onClippableWindowResizeHandler = this.clip.bind( this );
4853
4854 // Initialization
4855 if ( config.$clippableContainer ) {
4856 this.setClippableContainer( config.$clippableContainer );
4857 }
4858 this.setClippableElement( config.$clippable || this.$element );
4859 };
4860
4861 /* Methods */
4862
4863 /**
4864 * Set clippable element.
4865 *
4866 * If an element is already set, it will be cleaned up before setting up the new element.
4867 *
4868 * @param {jQuery} $clippable Element to make clippable
4869 */
4870 OO.ui.mixin.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
4871 if ( this.$clippable ) {
4872 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
4873 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
4874 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
4875 }
4876
4877 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
4878 this.clip();
4879 };
4880
4881 /**
4882 * Set clippable container.
4883 *
4884 * This is the container that will be measured when deciding whether to clip. When clipping,
4885 * #$clippable will be resized in order to keep the clippable container fully visible.
4886 *
4887 * If the clippable container is unset, #$clippable will be used.
4888 *
4889 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
4890 */
4891 OO.ui.mixin.ClippableElement.prototype.setClippableContainer = function ( $clippableContainer ) {
4892 this.$clippableContainer = $clippableContainer;
4893 if ( this.$clippable ) {
4894 this.clip();
4895 }
4896 };
4897
4898 /**
4899 * Toggle clipping.
4900 *
4901 * Do not turn clipping on until after the element is attached to the DOM and visible.
4902 *
4903 * @param {boolean} [clipping] Enable clipping, omit to toggle
4904 * @chainable
4905 * @return {OO.ui.Element} The element, for chaining
4906 */
4907 OO.ui.mixin.ClippableElement.prototype.toggleClipping = function ( clipping ) {
4908 clipping = clipping === undefined ? !this.clipping : !!clipping;
4909
4910 if ( clipping && !this.warnedUnattached && !this.isElementAttached() ) {
4911 OO.ui.warnDeprecation( 'ClippableElement#toggleClipping: Before calling this method, the element must be attached to the DOM.' );
4912 this.warnedUnattached = true;
4913 }
4914
4915 if ( this.clipping !== clipping ) {
4916 this.clipping = clipping;
4917 if ( clipping ) {
4918 this.$clippableScrollableContainer = $( this.getClosestScrollableElementContainer() );
4919 // If the clippable container is the root, we have to listen to scroll events and check
4920 // jQuery.scrollTop on the window because of browser inconsistencies
4921 this.$clippableScroller = this.$clippableScrollableContainer.is( 'html, body' ) ?
4922 $( OO.ui.Element.static.getWindow( this.$clippableScrollableContainer ) ) :
4923 this.$clippableScrollableContainer;
4924 this.$clippableScroller.on( 'scroll', this.onClippableScrollHandler );
4925 this.$clippableWindow = $( this.getElementWindow() )
4926 .on( 'resize', this.onClippableWindowResizeHandler );
4927 // Initial clip after visible
4928 this.clip();
4929 } else {
4930 this.$clippable.css( {
4931 width: '',
4932 height: '',
4933 maxWidth: '',
4934 maxHeight: '',
4935 overflowX: '',
4936 overflowY: ''
4937 } );
4938 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
4939
4940 this.$clippableScrollableContainer = null;
4941 this.$clippableScroller.off( 'scroll', this.onClippableScrollHandler );
4942 this.$clippableScroller = null;
4943 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
4944 this.$clippableWindow = null;
4945 }
4946 }
4947
4948 return this;
4949 };
4950
4951 /**
4952 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4953 *
4954 * @return {boolean} Element will be clipped to the visible area
4955 */
4956 OO.ui.mixin.ClippableElement.prototype.isClipping = function () {
4957 return this.clipping;
4958 };
4959
4960 /**
4961 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
4962 *
4963 * @return {boolean} Part of the element is being clipped
4964 */
4965 OO.ui.mixin.ClippableElement.prototype.isClipped = function () {
4966 return this.clippedHorizontally || this.clippedVertically;
4967 };
4968
4969 /**
4970 * Check if the right of the element is being clipped by the nearest scrollable container.
4971 *
4972 * @return {boolean} Part of the element is being clipped
4973 */
4974 OO.ui.mixin.ClippableElement.prototype.isClippedHorizontally = function () {
4975 return this.clippedHorizontally;
4976 };
4977
4978 /**
4979 * Check if the bottom of the element is being clipped by the nearest scrollable container.
4980 *
4981 * @return {boolean} Part of the element is being clipped
4982 */
4983 OO.ui.mixin.ClippableElement.prototype.isClippedVertically = function () {
4984 return this.clippedVertically;
4985 };
4986
4987 /**
4988 * Set the ideal size. These are the dimensions #$clippable will have when it's not being clipped.
4989 *
4990 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
4991 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
4992 */
4993 OO.ui.mixin.ClippableElement.prototype.setIdealSize = function ( width, height ) {
4994 this.idealWidth = width;
4995 this.idealHeight = height;
4996
4997 if ( !this.clipping ) {
4998 // Update dimensions
4999 this.$clippable.css( { width: width, height: height } );
5000 }
5001 // While clipping, idealWidth and idealHeight are not considered
5002 };
5003
5004 /**
5005 * Return the side of the clippable on which it is "anchored" (aligned to something else).
5006 * ClippableElement will clip the opposite side when reducing element's width.
5007 *
5008 * Classes that mix in ClippableElement should override this to return 'right' if their
5009 * clippable is absolutely positioned and using 'right: Npx' (and not using 'left').
5010 * If your class also mixes in FloatableElement, this is handled automatically.
5011 *
5012 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
5013 * always in pixels, even if they were unset or set to 'auto'.)
5014 *
5015 * When in doubt, 'left' (or 'right' in RTL) is a sane fallback.
5016 *
5017 * @return {string} 'left' or 'right'
5018 */
5019 OO.ui.mixin.ClippableElement.prototype.getHorizontalAnchorEdge = function () {
5020 if ( this.computePosition && this.positioning && this.computePosition().right !== '' ) {
5021 return 'right';
5022 }
5023 return 'left';
5024 };
5025
5026 /**
5027 * Return the side of the clippable on which it is "anchored" (aligned to something else).
5028 * ClippableElement will clip the opposite side when reducing element's width.
5029 *
5030 * Classes that mix in ClippableElement should override this to return 'bottom' if their
5031 * clippable is absolutely positioned and using 'bottom: Npx' (and not using 'top').
5032 * If your class also mixes in FloatableElement, this is handled automatically.
5033 *
5034 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
5035 * always in pixels, even if they were unset or set to 'auto'.)
5036 *
5037 * When in doubt, 'top' is a sane fallback.
5038 *
5039 * @return {string} 'top' or 'bottom'
5040 */
5041 OO.ui.mixin.ClippableElement.prototype.getVerticalAnchorEdge = function () {
5042 if ( this.computePosition && this.positioning && this.computePosition().bottom !== '' ) {
5043 return 'bottom';
5044 }
5045 return 'top';
5046 };
5047
5048 /**
5049 * Clip element to visible boundaries and allow scrolling when needed. You should call this method
5050 * when the element's natural height changes.
5051 *
5052 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
5053 * overlapped by, the visible area of the nearest scrollable container.
5054 *
5055 * Because calling clip() when the natural height changes isn't always possible, we also set
5056 * max-height when the element isn't being clipped. This means that if the element tries to grow
5057 * beyond the edge, something reasonable will happen before clip() is called.
5058 *
5059 * @chainable
5060 * @return {OO.ui.Element} The element, for chaining
5061 */
5062 OO.ui.mixin.ClippableElement.prototype.clip = function () {
5063 var extraHeight, extraWidth, viewportSpacing,
5064 desiredWidth, desiredHeight, allotedWidth, allotedHeight,
5065 naturalWidth, naturalHeight, clipWidth, clipHeight,
5066 $item, itemRect, $viewport, viewportRect, availableRect,
5067 direction, vertScrollbarWidth, horizScrollbarHeight,
5068 // Extra tolerance so that the sloppy code below doesn't result in results that are off
5069 // by one or two pixels. (And also so that we have space to display drop shadows.)
5070 // Chosen by fair dice roll.
5071 buffer = 7;
5072
5073 if ( !this.clipping ) {
5074 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below
5075 // will fail
5076 return this;
5077 }
5078
5079 function rectIntersection( a, b ) {
5080 var out = {};
5081 out.top = Math.max( a.top, b.top );
5082 out.left = Math.max( a.left, b.left );
5083 out.bottom = Math.min( a.bottom, b.bottom );
5084 out.right = Math.min( a.right, b.right );
5085 return out;
5086 }
5087
5088 viewportSpacing = OO.ui.getViewportSpacing();
5089
5090 if ( this.$clippableScrollableContainer.is( 'html, body' ) ) {
5091 $viewport = $( this.$clippableScrollableContainer[ 0 ].ownerDocument.body );
5092 // Dimensions of the browser window, rather than the element!
5093 viewportRect = {
5094 top: 0,
5095 left: 0,
5096 right: document.documentElement.clientWidth,
5097 bottom: document.documentElement.clientHeight
5098 };
5099 viewportRect.top += viewportSpacing.top;
5100 viewportRect.left += viewportSpacing.left;
5101 viewportRect.right -= viewportSpacing.right;
5102 viewportRect.bottom -= viewportSpacing.bottom;
5103 } else {
5104 $viewport = this.$clippableScrollableContainer;
5105 viewportRect = $viewport[ 0 ].getBoundingClientRect();
5106 // Convert into a plain object
5107 viewportRect = $.extend( {}, viewportRect );
5108 }
5109
5110 // Account for scrollbar gutter
5111 direction = $viewport.css( 'direction' );
5112 vertScrollbarWidth = $viewport.innerWidth() - $viewport.prop( 'clientWidth' );
5113 horizScrollbarHeight = $viewport.innerHeight() - $viewport.prop( 'clientHeight' );
5114 viewportRect.bottom -= horizScrollbarHeight;
5115 if ( direction === 'rtl' ) {
5116 viewportRect.left += vertScrollbarWidth;
5117 } else {
5118 viewportRect.right -= vertScrollbarWidth;
5119 }
5120
5121 // Add arbitrary tolerance
5122 viewportRect.top += buffer;
5123 viewportRect.left += buffer;
5124 viewportRect.right -= buffer;
5125 viewportRect.bottom -= buffer;
5126
5127 $item = this.$clippableContainer || this.$clippable;
5128
5129 extraHeight = $item.outerHeight() - this.$clippable.outerHeight();
5130 extraWidth = $item.outerWidth() - this.$clippable.outerWidth();
5131
5132 itemRect = $item[ 0 ].getBoundingClientRect();
5133 // Convert into a plain object
5134 itemRect = $.extend( {}, itemRect );
5135
5136 // Item might already be clipped, so we can't just use its dimensions (in case we might need to
5137 // make it larger than before). Extend the rectangle to the maximum size we are allowed to take.
5138 if ( this.getHorizontalAnchorEdge() === 'right' ) {
5139 itemRect.left = viewportRect.left;
5140 } else {
5141 itemRect.right = viewportRect.right;
5142 }
5143 if ( this.getVerticalAnchorEdge() === 'bottom' ) {
5144 itemRect.top = viewportRect.top;
5145 } else {
5146 itemRect.bottom = viewportRect.bottom;
5147 }
5148
5149 availableRect = rectIntersection( viewportRect, itemRect );
5150
5151 desiredWidth = Math.max( 0, availableRect.right - availableRect.left );
5152 desiredHeight = Math.max( 0, availableRect.bottom - availableRect.top );
5153 // It should never be desirable to exceed the dimensions of the browser viewport... right?
5154 desiredWidth = Math.min( desiredWidth,
5155 document.documentElement.clientWidth - viewportSpacing.left - viewportSpacing.right );
5156 desiredHeight = Math.min( desiredHeight,
5157 document.documentElement.clientHeight - viewportSpacing.top - viewportSpacing.right );
5158 allotedWidth = Math.ceil( desiredWidth - extraWidth );
5159 allotedHeight = Math.ceil( desiredHeight - extraHeight );
5160 naturalWidth = this.$clippable.prop( 'scrollWidth' );
5161 naturalHeight = this.$clippable.prop( 'scrollHeight' );
5162 clipWidth = allotedWidth < naturalWidth;
5163 clipHeight = allotedHeight < naturalHeight;
5164
5165 if ( clipWidth ) {
5166 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars.
5167 // See T157672.
5168 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for
5169 // this case.
5170 this.$clippable.css( 'overflowX', 'scroll' );
5171 // eslint-disable-next-line no-void
5172 void this.$clippable[ 0 ].offsetHeight; // Force reflow
5173 this.$clippable.css( {
5174 width: Math.max( 0, allotedWidth ),
5175 maxWidth: ''
5176 } );
5177 } else {
5178 this.$clippable.css( {
5179 overflowX: '',
5180 width: this.idealWidth || '',
5181 maxWidth: Math.max( 0, allotedWidth )
5182 } );
5183 }
5184 if ( clipHeight ) {
5185 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars.
5186 // See T157672.
5187 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for
5188 // this case.
5189 this.$clippable.css( 'overflowY', 'scroll' );
5190 // eslint-disable-next-line no-void
5191 void this.$clippable[ 0 ].offsetHeight; // Force reflow
5192 this.$clippable.css( {
5193 height: Math.max( 0, allotedHeight ),
5194 maxHeight: ''
5195 } );
5196 } else {
5197 this.$clippable.css( {
5198 overflowY: '',
5199 height: this.idealHeight || '',
5200 maxHeight: Math.max( 0, allotedHeight )
5201 } );
5202 }
5203
5204 // If we stopped clipping in at least one of the dimensions
5205 if ( ( this.clippedHorizontally && !clipWidth ) || ( this.clippedVertically && !clipHeight ) ) {
5206 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
5207 }
5208
5209 this.clippedHorizontally = clipWidth;
5210 this.clippedVertically = clipHeight;
5211
5212 return this;
5213 };
5214
5215 /**
5216 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
5217 * By default, each popup has an anchor that points toward its origin.
5218 * Please see the [OOUI documentation on MediaWiki.org] [1] for more information and examples.
5219 *
5220 * Unlike most widgets, PopupWidget is initially hidden and must be shown by calling #toggle.
5221 *
5222 * @example
5223 * // A PopupWidget.
5224 * var popup = new OO.ui.PopupWidget( {
5225 * $content: $( '<p>Hi there!</p>' ),
5226 * padded: true,
5227 * width: 300
5228 * } );
5229 *
5230 * $( document.body ).append( popup.$element );
5231 * // To display the popup, toggle the visibility to 'true'.
5232 * popup.toggle( true );
5233 *
5234 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups
5235 *
5236 * @class
5237 * @extends OO.ui.Widget
5238 * @mixins OO.ui.mixin.LabelElement
5239 * @mixins OO.ui.mixin.ClippableElement
5240 * @mixins OO.ui.mixin.FloatableElement
5241 *
5242 * @constructor
5243 * @param {Object} [config] Configuration options
5244 * @cfg {number|null} [width=320] Width of popup in pixels. Pass `null` to use automatic width.
5245 * @cfg {number|null} [height=null] Height of popup in pixels. Pass `null` to use automatic height.
5246 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
5247 * @cfg {string} [position='below'] Where to position the popup relative to $floatableContainer
5248 * 'above': Put popup above $floatableContainer; anchor points down to the horizontal center
5249 * of $floatableContainer
5250 * 'below': Put popup below $floatableContainer; anchor points up to the horizontal center
5251 * of $floatableContainer
5252 * 'before': Put popup to the left (LTR) / right (RTL) of $floatableContainer; anchor points
5253 * endwards (right/left) to the vertical center of $floatableContainer
5254 * 'after': Put popup to the right (LTR) / left (RTL) of $floatableContainer; anchor points
5255 * startwards (left/right) to the vertical center of $floatableContainer
5256 * @cfg {string} [align='center'] How to align the popup to $floatableContainer
5257 * 'forwards': If position is above/below, move the popup as far endwards (right in LTR, left in
5258 * RTL) as possible while still keeping the anchor within the popup; if position is before/after,
5259 * move the popup as far downwards as possible.
5260 * 'backwards': If position is above/below, move the popup as far startwards (left in LTR, right in
5261 * RTL) as possible while still keeping the anchor within the popup; if position is before/after,
5262 * move the popup as far upwards as possible.
5263 * 'center': Horizontally (if position is above/below) or vertically (before/after) align the
5264 * center of the popup with the center of $floatableContainer.
5265 * 'force-left': Alias for 'forwards' in LTR and 'backwards' in RTL
5266 * 'force-right': Alias for 'backwards' in RTL and 'forwards' in LTR
5267 * @cfg {boolean} [autoFlip=true] Whether to automatically switch the popup's position between
5268 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5269 * desired direction to display the popup without clipping
5270 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
5271 * See the [OOUI docs on MediaWiki][3] for an example.
5272 * [3]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#containerExample
5273 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a
5274 * number of pixels.
5275 * @cfg {jQuery} [$content] Content to append to the popup's body
5276 * @cfg {jQuery} [$footer] Content to append to the popup's footer
5277 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
5278 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
5279 * This config option is only relevant if #autoClose is set to `true`. See the
5280 * [OOUI documentation on MediaWiki][2] for an example.
5281 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#autocloseExample
5282 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
5283 * button.
5284 * @cfg {boolean} [padded=false] Add padding to the popup's body
5285 */
5286 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
5287 // Configuration initialization
5288 config = config || {};
5289
5290 // Parent constructor
5291 OO.ui.PopupWidget.parent.call( this, config );
5292
5293 // Properties (must be set before ClippableElement constructor call)
5294 this.$body = $( '<div>' );
5295 this.$popup = $( '<div>' );
5296
5297 // Mixin constructors
5298 OO.ui.mixin.LabelElement.call( this, config );
5299 OO.ui.mixin.ClippableElement.call( this, $.extend( {
5300 $clippable: this.$body,
5301 $clippableContainer: this.$popup
5302 }, config ) );
5303 OO.ui.mixin.FloatableElement.call( this, config );
5304
5305 // Properties
5306 this.$anchor = $( '<div>' );
5307 // If undefined, will be computed lazily in computePosition()
5308 this.$container = config.$container;
5309 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
5310 this.autoClose = !!config.autoClose;
5311 this.transitionTimeout = null;
5312 this.anchored = false;
5313 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
5314 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
5315
5316 // Initialization
5317 this.setSize( config.width, config.height );
5318 this.toggleAnchor( config.anchor === undefined || config.anchor );
5319 this.setAlignment( config.align || 'center' );
5320 this.setPosition( config.position || 'below' );
5321 this.setAutoFlip( config.autoFlip === undefined || config.autoFlip );
5322 this.setAutoCloseIgnore( config.$autoCloseIgnore );
5323 this.$body.addClass( 'oo-ui-popupWidget-body' );
5324 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
5325 this.$popup
5326 .addClass( 'oo-ui-popupWidget-popup' )
5327 .append( this.$body );
5328 this.$element
5329 .addClass( 'oo-ui-popupWidget' )
5330 .append( this.$popup, this.$anchor );
5331 // Move content, which was added to #$element by OO.ui.Widget, to the body
5332 // FIXME This is gross, we should use '$body' or something for the config
5333 if ( config.$content instanceof $ ) {
5334 this.$body.append( config.$content );
5335 }
5336
5337 if ( config.padded ) {
5338 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
5339 }
5340
5341 if ( config.head ) {
5342 this.closeButton = new OO.ui.ButtonWidget( {
5343 framed: false,
5344 icon: 'close'
5345 } );
5346 this.closeButton.connect( this, {
5347 click: 'onCloseButtonClick'
5348 } );
5349 this.$head = $( '<div>' )
5350 .addClass( 'oo-ui-popupWidget-head' )
5351 .append( this.$label, this.closeButton.$element );
5352 this.$popup.prepend( this.$head );
5353 }
5354
5355 if ( config.$footer ) {
5356 this.$footer = $( '<div>' )
5357 .addClass( 'oo-ui-popupWidget-footer' )
5358 .append( config.$footer );
5359 this.$popup.append( this.$footer );
5360 }
5361
5362 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
5363 // that reference properties not initialized at that time of parent class construction
5364 // TODO: Find a better way to handle post-constructor setup
5365 this.visible = false;
5366 this.$element.addClass( 'oo-ui-element-hidden' );
5367 };
5368
5369 /* Setup */
5370
5371 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
5372 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.LabelElement );
5373 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.ClippableElement );
5374 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.FloatableElement );
5375
5376 /* Events */
5377
5378 /**
5379 * @event ready
5380 *
5381 * The popup is ready: it is visible and has been positioned and clipped.
5382 */
5383
5384 /* Methods */
5385
5386 /**
5387 * Handles document mouse down events.
5388 *
5389 * @private
5390 * @param {MouseEvent} e Mouse down event
5391 */
5392 OO.ui.PopupWidget.prototype.onDocumentMouseDown = function ( e ) {
5393 if (
5394 this.isVisible() &&
5395 !OO.ui.contains( this.$element.add( this.$autoCloseIgnore ).get(), e.target, true )
5396 ) {
5397 this.toggle( false );
5398 }
5399 };
5400
5401 /**
5402 * Bind document mouse down listener.
5403 *
5404 * @private
5405 */
5406 OO.ui.PopupWidget.prototype.bindDocumentMouseDownListener = function () {
5407 // Capture clicks outside popup
5408 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
5409 // We add 'click' event because iOS safari needs to respond to this event.
5410 // We can't use 'touchstart' (as is usually the equivalent to 'mousedown') because
5411 // then it will trigger when scrolling. While iOS Safari has some reported behavior
5412 // of occasionally not emitting 'click' properly, that event seems to be the standard
5413 // that it should be emitting, so we add it to this and will operate the event handler
5414 // on whichever of these events was triggered first
5415 this.getElementDocument().addEventListener( 'click', this.onDocumentMouseDownHandler, true );
5416 };
5417
5418 /**
5419 * Handles close button click events.
5420 *
5421 * @private
5422 */
5423 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
5424 if ( this.isVisible() ) {
5425 this.toggle( false );
5426 }
5427 };
5428
5429 /**
5430 * Unbind document mouse down listener.
5431 *
5432 * @private
5433 */
5434 OO.ui.PopupWidget.prototype.unbindDocumentMouseDownListener = function () {
5435 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
5436 this.getElementDocument().removeEventListener( 'click', this.onDocumentMouseDownHandler, true );
5437 };
5438
5439 /**
5440 * Handles document key down events.
5441 *
5442 * @private
5443 * @param {KeyboardEvent} e Key down event
5444 */
5445 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
5446 if (
5447 e.which === OO.ui.Keys.ESCAPE &&
5448 this.isVisible()
5449 ) {
5450 this.toggle( false );
5451 e.preventDefault();
5452 e.stopPropagation();
5453 }
5454 };
5455
5456 /**
5457 * Bind document key down listener.
5458 *
5459 * @private
5460 */
5461 OO.ui.PopupWidget.prototype.bindDocumentKeyDownListener = function () {
5462 this.getElementDocument().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
5463 };
5464
5465 /**
5466 * Unbind document key down listener.
5467 *
5468 * @private
5469 */
5470 OO.ui.PopupWidget.prototype.unbindDocumentKeyDownListener = function () {
5471 this.getElementDocument().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
5472 };
5473
5474 /**
5475 * Show, hide, or toggle the visibility of the anchor.
5476 *
5477 * @param {boolean} [show] Show anchor, omit to toggle
5478 */
5479 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
5480 show = show === undefined ? !this.anchored : !!show;
5481
5482 if ( this.anchored !== show ) {
5483 if ( show ) {
5484 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
5485 this.$element.addClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge );
5486 } else {
5487 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
5488 this.$element.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge );
5489 }
5490 this.anchored = show;
5491 }
5492 };
5493
5494 /**
5495 * Change which edge the anchor appears on.
5496 *
5497 * @param {string} edge 'top', 'bottom', 'start' or 'end'
5498 */
5499 OO.ui.PopupWidget.prototype.setAnchorEdge = function ( edge ) {
5500 if ( [ 'top', 'bottom', 'start', 'end' ].indexOf( edge ) === -1 ) {
5501 throw new Error( 'Invalid value for edge: ' + edge );
5502 }
5503 if ( this.anchorEdge !== null ) {
5504 this.$element.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge );
5505 }
5506 this.anchorEdge = edge;
5507 if ( this.anchored ) {
5508 this.$element.addClass( 'oo-ui-popupWidget-anchored-' + edge );
5509 }
5510 };
5511
5512 /**
5513 * Check if the anchor is visible.
5514 *
5515 * @return {boolean} Anchor is visible
5516 */
5517 OO.ui.PopupWidget.prototype.hasAnchor = function () {
5518 return this.anchored;
5519 };
5520
5521 /**
5522 * Toggle visibility of the popup. The popup is initially hidden and must be shown by calling
5523 * `.toggle( true )` after its #$element is attached to the DOM.
5524 *
5525 * Do not show the popup while it is not attached to the DOM. The calculations required to display
5526 * it in the right place and with the right dimensions only work correctly while it is attached.
5527 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
5528 * strictly enforced, so currently it only generates a warning in the browser console.
5529 *
5530 * @fires ready
5531 * @inheritdoc
5532 */
5533 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
5534 var change, normalHeight, oppositeHeight, normalWidth, oppositeWidth;
5535 show = show === undefined ? !this.isVisible() : !!show;
5536
5537 change = show !== this.isVisible();
5538
5539 if ( show && !this.warnedUnattached && !this.isElementAttached() ) {
5540 OO.ui.warnDeprecation( 'PopupWidget#toggle: Before calling this method, the popup must be attached to the DOM.' );
5541 this.warnedUnattached = true;
5542 }
5543 if ( show && !this.$floatableContainer && this.isElementAttached() ) {
5544 // Fall back to the parent node if the floatableContainer is not set
5545 this.setFloatableContainer( this.$element.parent() );
5546 }
5547
5548 if ( change && show && this.autoFlip ) {
5549 // Reset auto-flipping before showing the popup again. It's possible we no longer need to
5550 // flip (e.g. if the user scrolled).
5551 this.isAutoFlipped = false;
5552 }
5553
5554 // Parent method
5555 OO.ui.PopupWidget.parent.prototype.toggle.call( this, show );
5556
5557 if ( change ) {
5558 this.togglePositioning( show && !!this.$floatableContainer );
5559
5560 if ( show ) {
5561 if ( this.autoClose ) {
5562 this.bindDocumentMouseDownListener();
5563 this.bindDocumentKeyDownListener();
5564 }
5565 this.updateDimensions();
5566 this.toggleClipping( true );
5567
5568 if ( this.autoFlip ) {
5569 if ( this.popupPosition === 'above' || this.popupPosition === 'below' ) {
5570 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5571 // If opening the popup in the normal direction causes it to be clipped,
5572 // open in the opposite one instead
5573 normalHeight = this.$element.height();
5574 this.isAutoFlipped = !this.isAutoFlipped;
5575 this.position();
5576 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5577 // If that also causes it to be clipped, open in whichever direction
5578 // we have more space
5579 oppositeHeight = this.$element.height();
5580 if ( oppositeHeight < normalHeight ) {
5581 this.isAutoFlipped = !this.isAutoFlipped;
5582 this.position();
5583 }
5584 }
5585 }
5586 }
5587 if ( this.popupPosition === 'before' || this.popupPosition === 'after' ) {
5588 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5589 // If opening the popup in the normal direction causes it to be clipped,
5590 // open in the opposite one instead
5591 normalWidth = this.$element.width();
5592 this.isAutoFlipped = !this.isAutoFlipped;
5593 // Due to T180173 horizontally clipped PopupWidgets have messed up
5594 // dimensions, which causes positioning to be off. Toggle clipping back and
5595 // forth to work around.
5596 this.toggleClipping( false );
5597 this.position();
5598 this.toggleClipping( true );
5599 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5600 // If that also causes it to be clipped, open in whichever direction
5601 // we have more space
5602 oppositeWidth = this.$element.width();
5603 if ( oppositeWidth < normalWidth ) {
5604 this.isAutoFlipped = !this.isAutoFlipped;
5605 // Due to T180173, horizontally clipped PopupWidgets have messed up
5606 // dimensions, which causes positioning to be off. Toggle clipping
5607 // back and forth to work around.
5608 this.toggleClipping( false );
5609 this.position();
5610 this.toggleClipping( true );
5611 }
5612 }
5613 }
5614 }
5615 }
5616
5617 this.emit( 'ready' );
5618 } else {
5619 this.toggleClipping( false );
5620 if ( this.autoClose ) {
5621 this.unbindDocumentMouseDownListener();
5622 this.unbindDocumentKeyDownListener();
5623 }
5624 }
5625 }
5626
5627 return this;
5628 };
5629
5630 /**
5631 * Set the size of the popup.
5632 *
5633 * Changing the size may also change the popup's position depending on the alignment.
5634 *
5635 * @param {number|null} [width=320] Width in pixels. Pass `null` to use automatic width.
5636 * @param {number|null} [height=null] Height in pixels. Pass `null` to use automatic height.
5637 * @param {boolean} [transition=false] Use a smooth transition
5638 * @chainable
5639 */
5640 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
5641 this.width = width !== undefined ? width : 320;
5642 this.height = height !== undefined ? height : null;
5643 if ( this.isVisible() ) {
5644 this.updateDimensions( transition );
5645 }
5646 };
5647
5648 /**
5649 * Update the size and position.
5650 *
5651 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
5652 * be called automatically.
5653 *
5654 * @param {boolean} [transition=false] Use a smooth transition
5655 * @chainable
5656 */
5657 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
5658 var widget = this;
5659
5660 // Prevent transition from being interrupted
5661 clearTimeout( this.transitionTimeout );
5662 if ( transition ) {
5663 // Enable transition
5664 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
5665 }
5666
5667 this.position();
5668
5669 if ( transition ) {
5670 // Prevent transitioning after transition is complete
5671 this.transitionTimeout = setTimeout( function () {
5672 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
5673 }, 200 );
5674 } else {
5675 // Prevent transitioning immediately
5676 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
5677 }
5678 };
5679
5680 /**
5681 * @inheritdoc
5682 */
5683 OO.ui.PopupWidget.prototype.computePosition = function () {
5684 var direction, align, vertical, start, end, near, far, sizeProp, popupSize, anchorSize,
5685 anchorPos, anchorOffset, anchorMargin, parentPosition, positionProp, positionAdjustment,
5686 floatablePos, offsetParentPos, containerPos, popupPosition, viewportSpacing,
5687 popupPos = {},
5688 anchorCss = { left: '', right: '', top: '', bottom: '' },
5689 popupPositionOppositeMap = {
5690 above: 'below',
5691 below: 'above',
5692 before: 'after',
5693 after: 'before'
5694 },
5695 alignMap = {
5696 ltr: {
5697 'force-left': 'backwards',
5698 'force-right': 'forwards'
5699 },
5700 rtl: {
5701 'force-left': 'forwards',
5702 'force-right': 'backwards'
5703 }
5704 },
5705 anchorEdgeMap = {
5706 above: 'bottom',
5707 below: 'top',
5708 before: 'end',
5709 after: 'start'
5710 },
5711 hPosMap = {
5712 forwards: 'start',
5713 center: 'center',
5714 backwards: this.anchored ? 'before' : 'end'
5715 },
5716 vPosMap = {
5717 forwards: 'top',
5718 center: 'center',
5719 backwards: 'bottom'
5720 };
5721
5722 if ( !this.$container ) {
5723 // Lazy-initialize $container if not specified in constructor
5724 this.$container = $( this.getClosestScrollableElementContainer() );
5725 }
5726 direction = this.$container.css( 'direction' );
5727
5728 // Set height and width before we do anything else, since it might cause our measurements
5729 // to change (e.g. due to scrollbars appearing or disappearing), and it also affects centering
5730 this.$popup.css( {
5731 width: this.width !== null ? this.width : 'auto',
5732 height: this.height !== null ? this.height : 'auto'
5733 } );
5734
5735 align = alignMap[ direction ][ this.align ] || this.align;
5736 popupPosition = this.popupPosition;
5737 if ( this.isAutoFlipped ) {
5738 popupPosition = popupPositionOppositeMap[ popupPosition ];
5739 }
5740
5741 // If the popup is positioned before or after, then the anchor positioning is vertical,
5742 // otherwise horizontal
5743 vertical = popupPosition === 'before' || popupPosition === 'after';
5744 start = vertical ? 'top' : ( direction === 'rtl' ? 'right' : 'left' );
5745 end = vertical ? 'bottom' : ( direction === 'rtl' ? 'left' : 'right' );
5746 near = vertical ? 'top' : 'left';
5747 far = vertical ? 'bottom' : 'right';
5748 sizeProp = vertical ? 'Height' : 'Width';
5749 popupSize = vertical ?
5750 ( this.height || this.$popup.height() ) :
5751 ( this.width || this.$popup.width() );
5752
5753 this.setAnchorEdge( anchorEdgeMap[ popupPosition ] );
5754 this.horizontalPosition = vertical ? popupPosition : hPosMap[ align ];
5755 this.verticalPosition = vertical ? vPosMap[ align ] : popupPosition;
5756
5757 // Parent method
5758 parentPosition = OO.ui.mixin.FloatableElement.prototype.computePosition.call( this );
5759 // Find out which property FloatableElement used for positioning, and adjust that value
5760 positionProp = vertical ?
5761 ( parentPosition.top !== '' ? 'top' : 'bottom' ) :
5762 ( parentPosition.left !== '' ? 'left' : 'right' );
5763
5764 // Figure out where the near and far edges of the popup and $floatableContainer are
5765 floatablePos = this.$floatableContainer.offset();
5766 floatablePos[ far ] = floatablePos[ near ] + this.$floatableContainer[ 'outer' + sizeProp ]();
5767 // Measure where the offsetParent is and compute our position based on that and parentPosition
5768 offsetParentPos = this.$element.offsetParent()[ 0 ] === document.documentElement ?
5769 { top: 0, left: 0 } :
5770 this.$element.offsetParent().offset();
5771
5772 if ( positionProp === near ) {
5773 popupPos[ near ] = offsetParentPos[ near ] + parentPosition[ near ];
5774 popupPos[ far ] = popupPos[ near ] + popupSize;
5775 } else {
5776 popupPos[ far ] = offsetParentPos[ near ] +
5777 this.$element.offsetParent()[ 'inner' + sizeProp ]() - parentPosition[ far ];
5778 popupPos[ near ] = popupPos[ far ] - popupSize;
5779 }
5780
5781 if ( this.anchored ) {
5782 // Position the anchor (which is positioned relative to the popup) to point to
5783 // $floatableContainer
5784 anchorPos = ( floatablePos[ start ] + floatablePos[ end ] ) / 2;
5785 anchorOffset = ( start === far ? -1 : 1 ) * ( anchorPos - popupPos[ start ] );
5786
5787 // If the anchor is less than 2*anchorSize from either edge, move the popup to make more
5788 // space this.$anchor.width()/height() returns 0 because of the CSS trickery we use, so use
5789 // scrollWidth/Height
5790 anchorSize = this.$anchor[ 0 ][ 'scroll' + sizeProp ];
5791 anchorMargin = parseFloat( this.$anchor.css( 'margin-' + start ) );
5792 if ( anchorOffset + anchorMargin < 2 * anchorSize ) {
5793 // Not enough space for the anchor on the start side; pull the popup startwards
5794 positionAdjustment = ( positionProp === start ? -1 : 1 ) *
5795 ( 2 * anchorSize - ( anchorOffset + anchorMargin ) );
5796 } else if ( anchorOffset + anchorMargin > popupSize - 2 * anchorSize ) {
5797 // Not enough space for the anchor on the end side; pull the popup endwards
5798 positionAdjustment = ( positionProp === end ? -1 : 1 ) *
5799 ( anchorOffset + anchorMargin - ( popupSize - 2 * anchorSize ) );
5800 } else {
5801 positionAdjustment = 0;
5802 }
5803 } else {
5804 positionAdjustment = 0;
5805 }
5806
5807 // Check if the popup will go beyond the edge of this.$container
5808 containerPos = this.$container[ 0 ] === document.documentElement ?
5809 { top: 0, left: 0 } :
5810 this.$container.offset();
5811 containerPos[ far ] = containerPos[ near ] + this.$container[ 'inner' + sizeProp ]();
5812 if ( this.$container[ 0 ] === document.documentElement ) {
5813 viewportSpacing = OO.ui.getViewportSpacing();
5814 containerPos[ near ] += viewportSpacing[ near ];
5815 containerPos[ far ] -= viewportSpacing[ far ];
5816 }
5817 // Take into account how much the popup will move because of the adjustments we're going to make
5818 popupPos[ near ] += ( positionProp === near ? 1 : -1 ) * positionAdjustment;
5819 popupPos[ far ] += ( positionProp === near ? 1 : -1 ) * positionAdjustment;
5820 if ( containerPos[ near ] + this.containerPadding > popupPos[ near ] ) {
5821 // Popup goes beyond the near (left/top) edge, move it to the right/bottom
5822 positionAdjustment += ( positionProp === near ? 1 : -1 ) *
5823 ( containerPos[ near ] + this.containerPadding - popupPos[ near ] );
5824 } else if ( containerPos[ far ] - this.containerPadding < popupPos[ far ] ) {
5825 // Popup goes beyond the far (right/bottom) edge, move it to the left/top
5826 positionAdjustment += ( positionProp === far ? 1 : -1 ) *
5827 ( popupPos[ far ] - ( containerPos[ far ] - this.containerPadding ) );
5828 }
5829
5830 if ( this.anchored ) {
5831 // Adjust anchorOffset for positionAdjustment
5832 anchorOffset += ( positionProp === start ? -1 : 1 ) * positionAdjustment;
5833
5834 // Position the anchor
5835 anchorCss[ start ] = anchorOffset;
5836 this.$anchor.css( anchorCss );
5837 }
5838
5839 // Move the popup if needed
5840 parentPosition[ positionProp ] += positionAdjustment;
5841
5842 return parentPosition;
5843 };
5844
5845 /**
5846 * Set popup alignment
5847 *
5848 * @param {string} [align=center] Alignment of the popup, `center`, `force-left`, `force-right`,
5849 * `backwards` or `forwards`.
5850 */
5851 OO.ui.PopupWidget.prototype.setAlignment = function ( align ) {
5852 // Validate alignment
5853 if ( [ 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align ) > -1 ) {
5854 this.align = align;
5855 } else {
5856 this.align = 'center';
5857 }
5858 this.position();
5859 };
5860
5861 /**
5862 * Get popup alignment
5863 *
5864 * @return {string} Alignment of the popup, `center`, `force-left`, `force-right`,
5865 * `backwards` or `forwards`.
5866 */
5867 OO.ui.PopupWidget.prototype.getAlignment = function () {
5868 return this.align;
5869 };
5870
5871 /**
5872 * Change the positioning of the popup.
5873 *
5874 * @param {string} position 'above', 'below', 'before' or 'after'
5875 */
5876 OO.ui.PopupWidget.prototype.setPosition = function ( position ) {
5877 if ( [ 'above', 'below', 'before', 'after' ].indexOf( position ) === -1 ) {
5878 position = 'below';
5879 }
5880 this.popupPosition = position;
5881 this.position();
5882 };
5883
5884 /**
5885 * Get popup positioning.
5886 *
5887 * @return {string} 'above', 'below', 'before' or 'after'
5888 */
5889 OO.ui.PopupWidget.prototype.getPosition = function () {
5890 return this.popupPosition;
5891 };
5892
5893 /**
5894 * Set popup auto-flipping.
5895 *
5896 * @param {boolean} autoFlip Whether to automatically switch the popup's position between
5897 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5898 * desired direction to display the popup without clipping
5899 */
5900 OO.ui.PopupWidget.prototype.setAutoFlip = function ( autoFlip ) {
5901 autoFlip = !!autoFlip;
5902
5903 if ( this.autoFlip !== autoFlip ) {
5904 this.autoFlip = autoFlip;
5905 }
5906 };
5907
5908 /**
5909 * Set which elements will not close the popup when clicked.
5910 *
5911 * For auto-closing popups, clicks on these elements will not cause the popup to auto-close.
5912 *
5913 * @param {jQuery} $autoCloseIgnore Elements to ignore for auto-closing
5914 */
5915 OO.ui.PopupWidget.prototype.setAutoCloseIgnore = function ( $autoCloseIgnore ) {
5916 this.$autoCloseIgnore = $autoCloseIgnore;
5917 };
5918
5919 /**
5920 * Get an ID of the body element, this can be used as the
5921 * `aria-describedby` attribute for an input field.
5922 *
5923 * @return {string} The ID of the body element
5924 */
5925 OO.ui.PopupWidget.prototype.getBodyId = function () {
5926 var id = this.$body.attr( 'id' );
5927 if ( id === undefined ) {
5928 id = OO.ui.generateElementId();
5929 this.$body.attr( 'id', id );
5930 }
5931 return id;
5932 };
5933
5934 /**
5935 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5936 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5937 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5938 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5939 *
5940 * @abstract
5941 * @class
5942 *
5943 * @constructor
5944 * @param {Object} [config] Configuration options
5945 * @cfg {Object} [popup] Configuration to pass to popup
5946 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5947 */
5948 OO.ui.mixin.PopupElement = function OoUiMixinPopupElement( config ) {
5949 // Configuration initialization
5950 config = config || {};
5951
5952 // Properties
5953 this.popup = new OO.ui.PopupWidget( $.extend(
5954 {
5955 autoClose: true,
5956 $floatableContainer: this.$element
5957 },
5958 config.popup,
5959 {
5960 $autoCloseIgnore: this.$element.add( config.popup && config.popup.$autoCloseIgnore )
5961 }
5962 ) );
5963 };
5964
5965 /* Methods */
5966
5967 /**
5968 * Get popup.
5969 *
5970 * @return {OO.ui.PopupWidget} Popup widget
5971 */
5972 OO.ui.mixin.PopupElement.prototype.getPopup = function () {
5973 return this.popup;
5974 };
5975
5976 /**
5977 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
5978 * which is used to display additional information or options.
5979 *
5980 * @example
5981 * // A PopupButtonWidget.
5982 * var popupButton = new OO.ui.PopupButtonWidget( {
5983 * label: 'Popup button with options',
5984 * icon: 'menu',
5985 * popup: {
5986 * $content: $( '<p>Additional options here.</p>' ),
5987 * padded: true,
5988 * align: 'force-left'
5989 * }
5990 * } );
5991 * // Append the button to the DOM.
5992 * $( document.body ).append( popupButton.$element );
5993 *
5994 * @class
5995 * @extends OO.ui.ButtonWidget
5996 * @mixins OO.ui.mixin.PopupElement
5997 *
5998 * @constructor
5999 * @param {Object} [config] Configuration options
6000 * @cfg {jQuery} [$overlay] Render the popup into a separate layer. This configuration is useful
6001 * in cases where the expanded popup is larger than its containing `<div>`. The specified overlay
6002 * layer is usually on top of the containing `<div>` and has a larger area. By default, the popup
6003 * uses relative positioning.
6004 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
6005 */
6006 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
6007 // Configuration initialization
6008 config = config || {};
6009
6010 // Parent constructor
6011 OO.ui.PopupButtonWidget.parent.call( this, config );
6012
6013 // Mixin constructors
6014 OO.ui.mixin.PopupElement.call( this, config );
6015
6016 // Properties
6017 this.$overlay = ( config.$overlay === true ?
6018 OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
6019
6020 // Events
6021 this.connect( this, {
6022 click: 'onAction'
6023 } );
6024
6025 // Initialization
6026 this.$element.addClass( 'oo-ui-popupButtonWidget' );
6027 this.popup.$element
6028 .addClass( 'oo-ui-popupButtonWidget-popup' )
6029 .toggleClass( 'oo-ui-popupButtonWidget-framed-popup', this.isFramed() )
6030 .toggleClass( 'oo-ui-popupButtonWidget-frameless-popup', !this.isFramed() );
6031 this.$overlay.append( this.popup.$element );
6032 };
6033
6034 /* Setup */
6035
6036 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
6037 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.mixin.PopupElement );
6038
6039 /* Methods */
6040
6041 /**
6042 * Handle the button action being triggered.
6043 *
6044 * @private
6045 */
6046 OO.ui.PopupButtonWidget.prototype.onAction = function () {
6047 this.popup.toggle();
6048 };
6049
6050 /**
6051 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
6052 *
6053 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
6054 *
6055 * @private
6056 * @abstract
6057 * @class
6058 * @mixins OO.ui.mixin.GroupElement
6059 *
6060 * @constructor
6061 * @param {Object} [config] Configuration options
6062 */
6063 OO.ui.mixin.GroupWidget = function OoUiMixinGroupWidget( config ) {
6064 // Mixin constructors
6065 OO.ui.mixin.GroupElement.call( this, config );
6066 };
6067
6068 /* Setup */
6069
6070 OO.mixinClass( OO.ui.mixin.GroupWidget, OO.ui.mixin.GroupElement );
6071
6072 /* Methods */
6073
6074 /**
6075 * Set the disabled state of the widget.
6076 *
6077 * This will also update the disabled state of child widgets.
6078 *
6079 * @param {boolean} disabled Disable widget
6080 * @chainable
6081 * @return {OO.ui.Widget} The widget, for chaining
6082 */
6083 OO.ui.mixin.GroupWidget.prototype.setDisabled = function ( disabled ) {
6084 var i, len;
6085
6086 // Parent method
6087 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
6088 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
6089
6090 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
6091 if ( this.items ) {
6092 for ( i = 0, len = this.items.length; i < len; i++ ) {
6093 this.items[ i ].updateDisabled();
6094 }
6095 }
6096
6097 return this;
6098 };
6099
6100 /**
6101 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
6102 *
6103 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group.
6104 * This allows bidirectional communication.
6105 *
6106 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
6107 *
6108 * @private
6109 * @abstract
6110 * @class
6111 *
6112 * @constructor
6113 */
6114 OO.ui.mixin.ItemWidget = function OoUiMixinItemWidget() {
6115 //
6116 };
6117
6118 /* Methods */
6119
6120 /**
6121 * Check if widget is disabled.
6122 *
6123 * Checks parent if present, making disabled state inheritable.
6124 *
6125 * @return {boolean} Widget is disabled
6126 */
6127 OO.ui.mixin.ItemWidget.prototype.isDisabled = function () {
6128 return this.disabled ||
6129 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
6130 };
6131
6132 /**
6133 * Set group element is in.
6134 *
6135 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
6136 * @chainable
6137 * @return {OO.ui.Widget} The widget, for chaining
6138 */
6139 OO.ui.mixin.ItemWidget.prototype.setElementGroup = function ( group ) {
6140 // Parent method
6141 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
6142 OO.ui.Element.prototype.setElementGroup.call( this, group );
6143
6144 // Initialize item disabled states
6145 this.updateDisabled();
6146
6147 return this;
6148 };
6149
6150 /**
6151 * OptionWidgets are special elements that can be selected and configured with data. The
6152 * data is often unique for each option, but it does not have to be. OptionWidgets are used
6153 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
6154 * and examples, please see the [OOUI documentation on MediaWiki][1].
6155 *
6156 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6157 *
6158 * @class
6159 * @extends OO.ui.Widget
6160 * @mixins OO.ui.mixin.ItemWidget
6161 * @mixins OO.ui.mixin.LabelElement
6162 * @mixins OO.ui.mixin.FlaggedElement
6163 * @mixins OO.ui.mixin.AccessKeyedElement
6164 * @mixins OO.ui.mixin.TitledElement
6165 *
6166 * @constructor
6167 * @param {Object} [config] Configuration options
6168 */
6169 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
6170 // Configuration initialization
6171 config = config || {};
6172
6173 // Parent constructor
6174 OO.ui.OptionWidget.parent.call( this, config );
6175
6176 // Mixin constructors
6177 OO.ui.mixin.ItemWidget.call( this );
6178 OO.ui.mixin.LabelElement.call( this, config );
6179 OO.ui.mixin.FlaggedElement.call( this, config );
6180 OO.ui.mixin.AccessKeyedElement.call( this, config );
6181 OO.ui.mixin.TitledElement.call( this, config );
6182
6183 // Properties
6184 this.highlighted = false;
6185 this.pressed = false;
6186 this.setSelected( !!config.selected );
6187
6188 // Initialization
6189 this.$element
6190 .data( 'oo-ui-optionWidget', this )
6191 // Allow programmatic focussing (and by access key), but not tabbing
6192 .attr( 'tabindex', '-1' )
6193 .attr( 'role', 'option' )
6194 .addClass( 'oo-ui-optionWidget' )
6195 .append( this.$label );
6196 };
6197
6198 /* Setup */
6199
6200 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
6201 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.ItemWidget );
6202 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.LabelElement );
6203 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.FlaggedElement );
6204 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.AccessKeyedElement );
6205 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.TitledElement );
6206
6207 /* Static Properties */
6208
6209 /**
6210 * Whether this option can be selected. See #setSelected.
6211 *
6212 * @static
6213 * @inheritable
6214 * @property {boolean}
6215 */
6216 OO.ui.OptionWidget.static.selectable = true;
6217
6218 /**
6219 * Whether this option can be highlighted. See #setHighlighted.
6220 *
6221 * @static
6222 * @inheritable
6223 * @property {boolean}
6224 */
6225 OO.ui.OptionWidget.static.highlightable = true;
6226
6227 /**
6228 * Whether this option can be pressed. See #setPressed.
6229 *
6230 * @static
6231 * @inheritable
6232 * @property {boolean}
6233 */
6234 OO.ui.OptionWidget.static.pressable = true;
6235
6236 /**
6237 * Whether this option will be scrolled into view when it is selected.
6238 *
6239 * @static
6240 * @inheritable
6241 * @property {boolean}
6242 */
6243 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
6244
6245 /* Methods */
6246
6247 /**
6248 * Check if the option can be selected.
6249 *
6250 * @return {boolean} Item is selectable
6251 */
6252 OO.ui.OptionWidget.prototype.isSelectable = function () {
6253 return this.constructor.static.selectable && !this.disabled && this.isVisible();
6254 };
6255
6256 /**
6257 * Check if the option can be highlighted. A highlight indicates that the option
6258 * may be selected when a user presses Enter key or clicks. Disabled items cannot
6259 * be highlighted.
6260 *
6261 * @return {boolean} Item is highlightable
6262 */
6263 OO.ui.OptionWidget.prototype.isHighlightable = function () {
6264 return this.constructor.static.highlightable && !this.disabled && this.isVisible();
6265 };
6266
6267 /**
6268 * Check if the option can be pressed. The pressed state occurs when a user mouses
6269 * down on an item, but has not yet let go of the mouse.
6270 *
6271 * @return {boolean} Item is pressable
6272 */
6273 OO.ui.OptionWidget.prototype.isPressable = function () {
6274 return this.constructor.static.pressable && !this.disabled && this.isVisible();
6275 };
6276
6277 /**
6278 * Check if the option is selected.
6279 *
6280 * @return {boolean} Item is selected
6281 */
6282 OO.ui.OptionWidget.prototype.isSelected = function () {
6283 return this.selected;
6284 };
6285
6286 /**
6287 * Check if the option is highlighted. A highlight indicates that the
6288 * item may be selected when a user presses Enter key or clicks.
6289 *
6290 * @return {boolean} Item is highlighted
6291 */
6292 OO.ui.OptionWidget.prototype.isHighlighted = function () {
6293 return this.highlighted;
6294 };
6295
6296 /**
6297 * Check if the option is pressed. The pressed state occurs when a user mouses
6298 * down on an item, but has not yet let go of the mouse. The item may appear
6299 * selected, but it will not be selected until the user releases the mouse.
6300 *
6301 * @return {boolean} Item is pressed
6302 */
6303 OO.ui.OptionWidget.prototype.isPressed = function () {
6304 return this.pressed;
6305 };
6306
6307 /**
6308 * Set the option’s selected state. In general, all modifications to the selection
6309 * should be handled by the SelectWidget’s
6310 * {@link OO.ui.SelectWidget#selectItem selectItem( [item] )} method instead of this method.
6311 *
6312 * @param {boolean} [state=false] Select option
6313 * @chainable
6314 * @return {OO.ui.Widget} The widget, for chaining
6315 */
6316 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
6317 if ( this.constructor.static.selectable ) {
6318 this.selected = !!state;
6319 this.$element
6320 .toggleClass( 'oo-ui-optionWidget-selected', state )
6321 .attr( 'aria-selected', state.toString() );
6322 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
6323 this.scrollElementIntoView();
6324 }
6325 this.updateThemeClasses();
6326 }
6327 return this;
6328 };
6329
6330 /**
6331 * Set the option’s highlighted state. In general, all programmatic
6332 * modifications to the highlight should be handled by the
6333 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
6334 * method instead of this method.
6335 *
6336 * @param {boolean} [state=false] Highlight option
6337 * @chainable
6338 * @return {OO.ui.Widget} The widget, for chaining
6339 */
6340 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
6341 if ( this.constructor.static.highlightable ) {
6342 this.highlighted = !!state;
6343 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
6344 this.updateThemeClasses();
6345 }
6346 return this;
6347 };
6348
6349 /**
6350 * Set the option’s pressed state. In general, all
6351 * programmatic modifications to the pressed state should be handled by the
6352 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
6353 * method instead of this method.
6354 *
6355 * @param {boolean} [state=false] Press option
6356 * @chainable
6357 * @return {OO.ui.Widget} The widget, for chaining
6358 */
6359 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
6360 if ( this.constructor.static.pressable ) {
6361 this.pressed = !!state;
6362 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
6363 this.updateThemeClasses();
6364 }
6365 return this;
6366 };
6367
6368 /**
6369 * Get text to match search strings against.
6370 *
6371 * The default implementation returns the label text, but subclasses
6372 * can override this to provide more complex behavior.
6373 *
6374 * @return {string|boolean} String to match search string against
6375 */
6376 OO.ui.OptionWidget.prototype.getMatchText = function () {
6377 var label = this.getLabel();
6378 return typeof label === 'string' ? label : this.$label.text();
6379 };
6380
6381 /**
6382 * A SelectWidget is of a generic selection of options. The OOUI library contains several types of
6383 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
6384 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
6385 * menu selects}.
6386 *
6387 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For
6388 * more information, please see the [OOUI documentation on MediaWiki][1].
6389 *
6390 * @example
6391 * // A select widget with three options.
6392 * var select = new OO.ui.SelectWidget( {
6393 * items: [
6394 * new OO.ui.OptionWidget( {
6395 * data: 'a',
6396 * label: 'Option One',
6397 * } ),
6398 * new OO.ui.OptionWidget( {
6399 * data: 'b',
6400 * label: 'Option Two',
6401 * } ),
6402 * new OO.ui.OptionWidget( {
6403 * data: 'c',
6404 * label: 'Option Three',
6405 * } )
6406 * ]
6407 * } );
6408 * $( document.body ).append( select.$element );
6409 *
6410 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6411 *
6412 * @abstract
6413 * @class
6414 * @extends OO.ui.Widget
6415 * @mixins OO.ui.mixin.GroupWidget
6416 *
6417 * @constructor
6418 * @param {Object} [config] Configuration options
6419 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
6420 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
6421 * the [OOUI documentation on MediaWiki] [2] for examples.
6422 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6423 */
6424 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
6425 // Configuration initialization
6426 config = config || {};
6427
6428 // Parent constructor
6429 OO.ui.SelectWidget.parent.call( this, config );
6430
6431 // Mixin constructors
6432 OO.ui.mixin.GroupWidget.call( this, $.extend( {
6433 $group: this.$element
6434 }, config ) );
6435
6436 // Properties
6437 this.pressed = false;
6438 this.selecting = null;
6439 this.onDocumentMouseUpHandler = this.onDocumentMouseUp.bind( this );
6440 this.onDocumentMouseMoveHandler = this.onDocumentMouseMove.bind( this );
6441 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
6442 this.onDocumentKeyPressHandler = this.onDocumentKeyPress.bind( this );
6443 this.keyPressBuffer = '';
6444 this.keyPressBufferTimer = null;
6445 this.blockMouseOverEvents = 0;
6446
6447 // Events
6448 this.connect( this, {
6449 toggle: 'onToggle'
6450 } );
6451 this.$element.on( {
6452 focusin: this.onFocus.bind( this ),
6453 mousedown: this.onMouseDown.bind( this ),
6454 mouseover: this.onMouseOver.bind( this ),
6455 mouseleave: this.onMouseLeave.bind( this )
6456 } );
6457
6458 // Initialization
6459 this.$element
6460 // -depressed is a deprecated alias of -unpressed
6461 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-unpressed oo-ui-selectWidget-depressed' )
6462 .attr( 'role', 'listbox' );
6463 this.setFocusOwner( this.$element );
6464 if ( Array.isArray( config.items ) ) {
6465 this.addItems( config.items );
6466 }
6467 };
6468
6469 /* Setup */
6470
6471 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
6472 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupWidget );
6473
6474 /* Events */
6475
6476 /**
6477 * @event highlight
6478 *
6479 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
6480 *
6481 * @param {OO.ui.OptionWidget|null} item Highlighted item
6482 */
6483
6484 /**
6485 * @event press
6486 *
6487 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
6488 * pressed state of an option.
6489 *
6490 * @param {OO.ui.OptionWidget|null} item Pressed item
6491 */
6492
6493 /**
6494 * @event select
6495 *
6496 * A `select` event is emitted when the selection is modified programmatically with the #selectItem
6497 * method.
6498 *
6499 * @param {OO.ui.OptionWidget|null} item Selected item
6500 */
6501
6502 /**
6503 * @event choose
6504 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
6505 * @param {OO.ui.OptionWidget} item Chosen item
6506 */
6507
6508 /**
6509 * @event add
6510 *
6511 * An `add` event is emitted when options are added to the select with the #addItems method.
6512 *
6513 * @param {OO.ui.OptionWidget[]} items Added items
6514 * @param {number} index Index of insertion point
6515 */
6516
6517 /**
6518 * @event remove
6519 *
6520 * A `remove` event is emitted when options are removed from the select with the #clearItems
6521 * or #removeItems methods.
6522 *
6523 * @param {OO.ui.OptionWidget[]} items Removed items
6524 */
6525
6526 /* Static methods */
6527
6528 /**
6529 * Normalize text for filter matching
6530 *
6531 * @param {string} text Text
6532 * @return {string} Normalized text
6533 */
6534 OO.ui.SelectWidget.static.normalizeForMatching = function ( text ) {
6535 // Replace trailing whitespace, normalize multiple spaces and make case insensitive
6536 var normalized = text.trim().replace( /\s+/, ' ' ).toLowerCase();
6537
6538 // Normalize Unicode
6539 // eslint-disable-next-line no-restricted-properties
6540 if ( normalized.normalize ) {
6541 // eslint-disable-next-line no-restricted-properties
6542 normalized = normalized.normalize();
6543 }
6544 return normalized;
6545 };
6546
6547 /* Methods */
6548
6549 /**
6550 * Handle focus events
6551 *
6552 * @private
6553 * @param {jQuery.Event} event
6554 */
6555 OO.ui.SelectWidget.prototype.onFocus = function ( event ) {
6556 var item;
6557 if ( event.target === this.$element[ 0 ] ) {
6558 // This widget was focussed, e.g. by the user tabbing to it.
6559 // The styles for focus state depend on one of the items being selected.
6560 if ( !this.findSelectedItem() ) {
6561 item = this.findFirstSelectableItem();
6562 }
6563 } else {
6564 if ( event.target.tabIndex === -1 ) {
6565 // One of the options got focussed (and the event bubbled up here).
6566 // They can't be tabbed to, but they can be activated using access keys.
6567 // OptionWidgets and focusable UI elements inside them have tabindex="-1" set.
6568 item = this.findTargetItem( event );
6569 } else {
6570 // There is something actually user-focusable in one of the labels of the options, and
6571 // the user focussed it (e.g. by tabbing to it). Do nothing (especially, don't change
6572 // the focus).
6573 return;
6574 }
6575 }
6576
6577 if ( item ) {
6578 if ( item.constructor.static.highlightable ) {
6579 this.highlightItem( item );
6580 } else {
6581 this.selectItem( item );
6582 }
6583 }
6584
6585 if ( event.target !== this.$element[ 0 ] ) {
6586 this.$focusOwner.trigger( 'focus' );
6587 }
6588 };
6589
6590 /**
6591 * Handle mouse down events.
6592 *
6593 * @private
6594 * @param {jQuery.Event} e Mouse down event
6595 * @return {undefined/boolean} False to prevent default if event is handled
6596 */
6597 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
6598 var item;
6599
6600 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
6601 this.togglePressed( true );
6602 item = this.findTargetItem( e );
6603 if ( item && item.isSelectable() ) {
6604 this.pressItem( item );
6605 this.selecting = item;
6606 this.getElementDocument().addEventListener( 'mouseup', this.onDocumentMouseUpHandler, true );
6607 this.getElementDocument().addEventListener( 'mousemove', this.onDocumentMouseMoveHandler, true );
6608 }
6609 }
6610 return false;
6611 };
6612
6613 /**
6614 * Handle document mouse up events.
6615 *
6616 * @private
6617 * @param {MouseEvent} e Mouse up event
6618 * @return {undefined/boolean} False to prevent default if event is handled
6619 */
6620 OO.ui.SelectWidget.prototype.onDocumentMouseUp = function ( e ) {
6621 var item;
6622
6623 this.togglePressed( false );
6624 if ( !this.selecting ) {
6625 item = this.findTargetItem( e );
6626 if ( item && item.isSelectable() ) {
6627 this.selecting = item;
6628 }
6629 }
6630 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT && this.selecting ) {
6631 this.pressItem( null );
6632 this.chooseItem( this.selecting );
6633 this.selecting = null;
6634 }
6635
6636 this.getElementDocument().removeEventListener( 'mouseup', this.onDocumentMouseUpHandler, true );
6637 this.getElementDocument().removeEventListener( 'mousemove', this.onDocumentMouseMoveHandler, true );
6638
6639 return false;
6640 };
6641
6642 /**
6643 * Handle document mouse move events.
6644 *
6645 * @private
6646 * @param {MouseEvent} e Mouse move event
6647 */
6648 OO.ui.SelectWidget.prototype.onDocumentMouseMove = function ( e ) {
6649 var item;
6650
6651 if ( !this.isDisabled() && this.pressed ) {
6652 item = this.findTargetItem( e );
6653 if ( item && item !== this.selecting && item.isSelectable() ) {
6654 this.pressItem( item );
6655 this.selecting = item;
6656 }
6657 }
6658 };
6659
6660 /**
6661 * Handle mouse over events.
6662 *
6663 * @private
6664 * @param {jQuery.Event} e Mouse over event
6665 * @return {undefined/boolean} False to prevent default if event is handled
6666 */
6667 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
6668 var item;
6669 if ( this.blockMouseOverEvents ) {
6670 return;
6671 }
6672 if ( !this.isDisabled() ) {
6673 item = this.findTargetItem( e );
6674 this.highlightItem( item && item.isHighlightable() ? item : null );
6675 }
6676 return false;
6677 };
6678
6679 /**
6680 * Handle mouse leave events.
6681 *
6682 * @private
6683 * @param {jQuery.Event} e Mouse over event
6684 * @return {undefined/boolean} False to prevent default if event is handled
6685 */
6686 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
6687 if ( !this.isDisabled() ) {
6688 this.highlightItem( null );
6689 }
6690 return false;
6691 };
6692
6693 /**
6694 * Handle document key down events.
6695 *
6696 * @protected
6697 * @param {KeyboardEvent} e Key down event
6698 */
6699 OO.ui.SelectWidget.prototype.onDocumentKeyDown = function ( e ) {
6700 var nextItem,
6701 handled = false,
6702 currentItem = this.findHighlightedItem() || this.findSelectedItem();
6703
6704 if ( !this.isDisabled() && this.isVisible() ) {
6705 switch ( e.keyCode ) {
6706 case OO.ui.Keys.ENTER:
6707 if ( currentItem && currentItem.constructor.static.highlightable ) {
6708 // Was only highlighted, now let's select it. No-op if already selected.
6709 this.chooseItem( currentItem );
6710 handled = true;
6711 }
6712 break;
6713 case OO.ui.Keys.UP:
6714 case OO.ui.Keys.LEFT:
6715 this.clearKeyPressBuffer();
6716 nextItem = this.findRelativeSelectableItem( currentItem, -1 );
6717 handled = true;
6718 break;
6719 case OO.ui.Keys.DOWN:
6720 case OO.ui.Keys.RIGHT:
6721 this.clearKeyPressBuffer();
6722 nextItem = this.findRelativeSelectableItem( currentItem, 1 );
6723 handled = true;
6724 break;
6725 case OO.ui.Keys.ESCAPE:
6726 case OO.ui.Keys.TAB:
6727 if ( currentItem && currentItem.constructor.static.highlightable ) {
6728 currentItem.setHighlighted( false );
6729 }
6730 this.unbindDocumentKeyDownListener();
6731 this.unbindDocumentKeyPressListener();
6732 // Don't prevent tabbing away / defocusing
6733 handled = false;
6734 break;
6735 }
6736
6737 if ( nextItem ) {
6738 if ( nextItem.constructor.static.highlightable ) {
6739 this.highlightItem( nextItem );
6740 } else {
6741 this.chooseItem( nextItem );
6742 }
6743 this.scrollItemIntoView( nextItem );
6744 }
6745
6746 if ( handled ) {
6747 e.preventDefault();
6748 e.stopPropagation();
6749 }
6750 }
6751 };
6752
6753 /**
6754 * Bind document key down listener.
6755 *
6756 * @protected
6757 */
6758 OO.ui.SelectWidget.prototype.bindDocumentKeyDownListener = function () {
6759 this.getElementDocument().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
6760 };
6761
6762 /**
6763 * Unbind document key down listener.
6764 *
6765 * @protected
6766 */
6767 OO.ui.SelectWidget.prototype.unbindDocumentKeyDownListener = function () {
6768 this.getElementDocument().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
6769 };
6770
6771 /**
6772 * Scroll item into view, preventing spurious mouse highlight actions from happening.
6773 *
6774 * @param {OO.ui.OptionWidget} item Item to scroll into view
6775 */
6776 OO.ui.SelectWidget.prototype.scrollItemIntoView = function ( item ) {
6777 var widget = this;
6778 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic
6779 // scrolling and around 100-150 ms after it is finished.
6780 this.blockMouseOverEvents++;
6781 item.scrollElementIntoView().done( function () {
6782 setTimeout( function () {
6783 widget.blockMouseOverEvents--;
6784 }, 200 );
6785 } );
6786 };
6787
6788 /**
6789 * Clear the key-press buffer
6790 *
6791 * @protected
6792 */
6793 OO.ui.SelectWidget.prototype.clearKeyPressBuffer = function () {
6794 if ( this.keyPressBufferTimer ) {
6795 clearTimeout( this.keyPressBufferTimer );
6796 this.keyPressBufferTimer = null;
6797 }
6798 this.keyPressBuffer = '';
6799 };
6800
6801 /**
6802 * Handle key press events.
6803 *
6804 * @protected
6805 * @param {KeyboardEvent} e Key press event
6806 * @return {undefined/boolean} False to prevent default if event is handled
6807 */
6808 OO.ui.SelectWidget.prototype.onDocumentKeyPress = function ( e ) {
6809 var c, filter, item;
6810
6811 if ( !e.charCode ) {
6812 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.keyPressBuffer !== '' ) {
6813 this.keyPressBuffer = this.keyPressBuffer.substr( 0, this.keyPressBuffer.length - 1 );
6814 return false;
6815 }
6816 return;
6817 }
6818 // eslint-disable-next-line no-restricted-properties
6819 if ( String.fromCodePoint ) {
6820 // eslint-disable-next-line no-restricted-properties
6821 c = String.fromCodePoint( e.charCode );
6822 } else {
6823 c = String.fromCharCode( e.charCode );
6824 }
6825
6826 if ( this.keyPressBufferTimer ) {
6827 clearTimeout( this.keyPressBufferTimer );
6828 }
6829 this.keyPressBufferTimer = setTimeout( this.clearKeyPressBuffer.bind( this ), 1500 );
6830
6831 item = this.findHighlightedItem() || this.findSelectedItem();
6832
6833 if ( this.keyPressBuffer === c ) {
6834 // Common (if weird) special case: typing "xxxx" will cycle through all
6835 // the items beginning with "x".
6836 if ( item ) {
6837 item = this.findRelativeSelectableItem( item, 1 );
6838 }
6839 } else {
6840 this.keyPressBuffer += c;
6841 }
6842
6843 filter = this.getItemMatcher( this.keyPressBuffer, false );
6844 if ( !item || !filter( item ) ) {
6845 item = this.findRelativeSelectableItem( item, 1, filter );
6846 }
6847 if ( item ) {
6848 if ( this.isVisible() && item.constructor.static.highlightable ) {
6849 this.highlightItem( item );
6850 } else {
6851 this.chooseItem( item );
6852 }
6853 this.scrollItemIntoView( item );
6854 }
6855
6856 e.preventDefault();
6857 e.stopPropagation();
6858 };
6859
6860 /**
6861 * Get a matcher for the specific string
6862 *
6863 * @protected
6864 * @param {string} query String to match against items
6865 * @param {string} [mode='prefix'] Matching mode: 'substring', 'prefix', or 'exact'
6866 * @return {Function} function ( OO.ui.OptionWidget ) => boolean
6867 */
6868 OO.ui.SelectWidget.prototype.getItemMatcher = function ( query, mode ) {
6869 var normalizeForMatching = this.constructor.static.normalizeForMatching,
6870 normalizedQuery = normalizeForMatching( query );
6871
6872 // Support deprecated exact=true argument
6873 if ( mode === true ) {
6874 mode = 'exact';
6875 }
6876
6877 return function ( item ) {
6878 var matchText = normalizeForMatching( item.getMatchText() );
6879
6880 if ( normalizedQuery === '' ) {
6881 // Empty string matches all, except if we are in 'exact'
6882 // mode, where it doesn't match at all
6883 return mode !== 'exact';
6884 }
6885
6886 switch ( mode ) {
6887 case 'exact':
6888 return matchText === normalizedQuery;
6889 case 'substring':
6890 return matchText.indexOf( normalizedQuery ) !== -1;
6891 // 'prefix'
6892 default:
6893 return matchText.indexOf( normalizedQuery ) === 0;
6894 }
6895 };
6896 };
6897
6898 /**
6899 * Bind document key press listener.
6900 *
6901 * @protected
6902 */
6903 OO.ui.SelectWidget.prototype.bindDocumentKeyPressListener = function () {
6904 this.getElementDocument().addEventListener( 'keypress', this.onDocumentKeyPressHandler, true );
6905 };
6906
6907 /**
6908 * Unbind document key down listener.
6909 *
6910 * If you override this, be sure to call this.clearKeyPressBuffer() from your
6911 * implementation.
6912 *
6913 * @protected
6914 */
6915 OO.ui.SelectWidget.prototype.unbindDocumentKeyPressListener = function () {
6916 this.getElementDocument().removeEventListener( 'keypress', this.onDocumentKeyPressHandler, true );
6917 this.clearKeyPressBuffer();
6918 };
6919
6920 /**
6921 * Visibility change handler
6922 *
6923 * @protected
6924 * @param {boolean} visible
6925 */
6926 OO.ui.SelectWidget.prototype.onToggle = function ( visible ) {
6927 if ( !visible ) {
6928 this.clearKeyPressBuffer();
6929 }
6930 };
6931
6932 /**
6933 * Get the closest item to a jQuery.Event.
6934 *
6935 * @private
6936 * @param {jQuery.Event} e
6937 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
6938 */
6939 OO.ui.SelectWidget.prototype.findTargetItem = function ( e ) {
6940 var $option = $( e.target ).closest( '.oo-ui-optionWidget' );
6941 if ( !$option.closest( '.oo-ui-selectWidget' ).is( this.$element ) ) {
6942 return null;
6943 }
6944 return $option.data( 'oo-ui-optionWidget' ) || null;
6945 };
6946
6947 /**
6948 * Find selected item.
6949 *
6950 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
6951 */
6952 OO.ui.SelectWidget.prototype.findSelectedItem = function () {
6953 var i, len;
6954
6955 for ( i = 0, len = this.items.length; i < len; i++ ) {
6956 if ( this.items[ i ].isSelected() ) {
6957 return this.items[ i ];
6958 }
6959 }
6960 return null;
6961 };
6962
6963 /**
6964 * Find highlighted item.
6965 *
6966 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
6967 */
6968 OO.ui.SelectWidget.prototype.findHighlightedItem = function () {
6969 var i, len;
6970
6971 for ( i = 0, len = this.items.length; i < len; i++ ) {
6972 if ( this.items[ i ].isHighlighted() ) {
6973 return this.items[ i ];
6974 }
6975 }
6976 return null;
6977 };
6978
6979 /**
6980 * Toggle pressed state.
6981 *
6982 * Press is a state that occurs when a user mouses down on an item, but
6983 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
6984 * until the user releases the mouse.
6985 *
6986 * @param {boolean} pressed An option is being pressed
6987 */
6988 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
6989 if ( pressed === undefined ) {
6990 pressed = !this.pressed;
6991 }
6992 if ( pressed !== this.pressed ) {
6993 this.$element
6994 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
6995 // -depressed is a deprecated alias of -unpressed
6996 .toggleClass( 'oo-ui-selectWidget-unpressed oo-ui-selectWidget-depressed', !pressed );
6997 this.pressed = pressed;
6998 }
6999 };
7000
7001 /**
7002 * Highlight an option. If the `item` param is omitted, no options will be highlighted
7003 * and any existing highlight will be removed. The highlight is mutually exclusive.
7004 *
7005 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
7006 * @fires highlight
7007 * @chainable
7008 * @return {OO.ui.Widget} The widget, for chaining
7009 */
7010 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
7011 var i, len, highlighted,
7012 changed = false;
7013
7014 for ( i = 0, len = this.items.length; i < len; i++ ) {
7015 highlighted = this.items[ i ] === item;
7016 if ( this.items[ i ].isHighlighted() !== highlighted ) {
7017 this.items[ i ].setHighlighted( highlighted );
7018 changed = true;
7019 }
7020 }
7021 if ( changed ) {
7022 if ( item ) {
7023 this.$focusOwner.attr( 'aria-activedescendant', item.getElementId() );
7024 } else {
7025 this.$focusOwner.removeAttr( 'aria-activedescendant' );
7026 }
7027 this.emit( 'highlight', item );
7028 }
7029
7030 return this;
7031 };
7032
7033 /**
7034 * Fetch an item by its label.
7035 *
7036 * @param {string} label Label of the item to select.
7037 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
7038 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
7039 */
7040 OO.ui.SelectWidget.prototype.getItemFromLabel = function ( label, prefix ) {
7041 var i, item, found,
7042 len = this.items.length,
7043 filter = this.getItemMatcher( label, 'exact' );
7044
7045 for ( i = 0; i < len; i++ ) {
7046 item = this.items[ i ];
7047 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
7048 return item;
7049 }
7050 }
7051
7052 if ( prefix ) {
7053 found = null;
7054 filter = this.getItemMatcher( label, 'prefix' );
7055 for ( i = 0; i < len; i++ ) {
7056 item = this.items[ i ];
7057 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
7058 if ( found ) {
7059 return null;
7060 }
7061 found = item;
7062 }
7063 }
7064 if ( found ) {
7065 return found;
7066 }
7067 }
7068
7069 return null;
7070 };
7071
7072 /**
7073 * Programmatically select an option by its label. If the item does not exist,
7074 * all options will be deselected.
7075 *
7076 * @param {string} [label] Label of the item to select.
7077 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
7078 * @fires select
7079 * @chainable
7080 * @return {OO.ui.Widget} The widget, for chaining
7081 */
7082 OO.ui.SelectWidget.prototype.selectItemByLabel = function ( label, prefix ) {
7083 var itemFromLabel = this.getItemFromLabel( label, !!prefix );
7084 if ( label === undefined || !itemFromLabel ) {
7085 return this.selectItem();
7086 }
7087 return this.selectItem( itemFromLabel );
7088 };
7089
7090 /**
7091 * Programmatically select an option by its data. If the `data` parameter is omitted,
7092 * or if the item does not exist, all options will be deselected.
7093 *
7094 * @param {Object|string} [data] Value of the item to select, omit to deselect all
7095 * @fires select
7096 * @chainable
7097 * @return {OO.ui.Widget} The widget, for chaining
7098 */
7099 OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) {
7100 var itemFromData = this.findItemFromData( data );
7101 if ( data === undefined || !itemFromData ) {
7102 return this.selectItem();
7103 }
7104 return this.selectItem( itemFromData );
7105 };
7106
7107 /**
7108 * Programmatically select an option by its reference. If the `item` parameter is omitted,
7109 * all options will be deselected.
7110 *
7111 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
7112 * @fires select
7113 * @chainable
7114 * @return {OO.ui.Widget} The widget, for chaining
7115 */
7116 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
7117 var i, len, selected,
7118 changed = false;
7119
7120 for ( i = 0, len = this.items.length; i < len; i++ ) {
7121 selected = this.items[ i ] === item;
7122 if ( this.items[ i ].isSelected() !== selected ) {
7123 this.items[ i ].setSelected( selected );
7124 changed = true;
7125 }
7126 }
7127 if ( changed ) {
7128 if ( item && !item.constructor.static.highlightable ) {
7129 if ( item ) {
7130 this.$focusOwner.attr( 'aria-activedescendant', item.getElementId() );
7131 } else {
7132 this.$focusOwner.removeAttr( 'aria-activedescendant' );
7133 }
7134 }
7135 this.emit( 'select', item );
7136 }
7137
7138 return this;
7139 };
7140
7141 /**
7142 * Press an item.
7143 *
7144 * Press is a state that occurs when a user mouses down on an item, but has not
7145 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
7146 * releases the mouse.
7147 *
7148 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
7149 * @fires press
7150 * @chainable
7151 * @return {OO.ui.Widget} The widget, for chaining
7152 */
7153 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
7154 var i, len, pressed,
7155 changed = false;
7156
7157 for ( i = 0, len = this.items.length; i < len; i++ ) {
7158 pressed = this.items[ i ] === item;
7159 if ( this.items[ i ].isPressed() !== pressed ) {
7160 this.items[ i ].setPressed( pressed );
7161 changed = true;
7162 }
7163 }
7164 if ( changed ) {
7165 this.emit( 'press', item );
7166 }
7167
7168 return this;
7169 };
7170
7171 /**
7172 * Choose an item.
7173 *
7174 * Note that ‘choose’ should never be modified programmatically. A user can choose
7175 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
7176 * use the #selectItem method.
7177 *
7178 * This method is identical to #selectItem, but may vary in subclasses that take additional action
7179 * when users choose an item with the keyboard or mouse.
7180 *
7181 * @param {OO.ui.OptionWidget} item Item to choose
7182 * @fires choose
7183 * @chainable
7184 * @return {OO.ui.Widget} The widget, for chaining
7185 */
7186 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
7187 if ( item ) {
7188 this.selectItem( item );
7189 this.emit( 'choose', item );
7190 }
7191
7192 return this;
7193 };
7194
7195 /**
7196 * Find an option by its position relative to the specified item (or to the start of the option
7197 * array, if item is `null`). The direction in which to search through the option array is specified
7198 * with a number: -1 for reverse (the default) or 1 for forward. The method will return an option,
7199 * or `null` if there are no options in the array.
7200 *
7201 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at
7202 * the beginning of the array.
7203 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
7204 * @param {Function} [filter] Only consider items for which this function returns
7205 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
7206 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
7207 */
7208 OO.ui.SelectWidget.prototype.findRelativeSelectableItem = function ( item, direction, filter ) {
7209 var currentIndex, nextIndex, i,
7210 increase = direction > 0 ? 1 : -1,
7211 len = this.items.length;
7212
7213 if ( item instanceof OO.ui.OptionWidget ) {
7214 currentIndex = this.items.indexOf( item );
7215 nextIndex = ( currentIndex + increase + len ) % len;
7216 } else {
7217 // If no item is selected and moving forward, start at the beginning.
7218 // If moving backward, start at the end.
7219 nextIndex = direction > 0 ? 0 : len - 1;
7220 }
7221
7222 for ( i = 0; i < len; i++ ) {
7223 item = this.items[ nextIndex ];
7224 if (
7225 item instanceof OO.ui.OptionWidget && item.isSelectable() &&
7226 ( !filter || filter( item ) )
7227 ) {
7228 return item;
7229 }
7230 nextIndex = ( nextIndex + increase + len ) % len;
7231 }
7232 return null;
7233 };
7234
7235 /**
7236 * Find the next selectable item or `null` if there are no selectable items.
7237 * Disabled options and menu-section markers and breaks are not selectable.
7238 *
7239 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
7240 */
7241 OO.ui.SelectWidget.prototype.findFirstSelectableItem = function () {
7242 return this.findRelativeSelectableItem( null, 1 );
7243 };
7244
7245 /**
7246 * Add an array of options to the select. Optionally, an index number can be used to
7247 * specify an insertion point.
7248 *
7249 * @param {OO.ui.OptionWidget[]} items Items to add
7250 * @param {number} [index] Index to insert items after
7251 * @fires add
7252 * @chainable
7253 * @return {OO.ui.Widget} The widget, for chaining
7254 */
7255 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
7256 // Mixin method
7257 OO.ui.mixin.GroupWidget.prototype.addItems.call( this, items, index );
7258
7259 // Always provide an index, even if it was omitted
7260 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
7261
7262 return this;
7263 };
7264
7265 /**
7266 * Remove the specified array of options from the select. Options will be detached
7267 * from the DOM, not removed, so they can be reused later. To remove all options from
7268 * the select, you may wish to use the #clearItems method instead.
7269 *
7270 * @param {OO.ui.OptionWidget[]} items Items to remove
7271 * @fires remove
7272 * @chainable
7273 * @return {OO.ui.Widget} The widget, for chaining
7274 */
7275 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
7276 var i, len, item;
7277
7278 // Deselect items being removed
7279 for ( i = 0, len = items.length; i < len; i++ ) {
7280 item = items[ i ];
7281 if ( item.isSelected() ) {
7282 this.selectItem( null );
7283 }
7284 }
7285
7286 // Mixin method
7287 OO.ui.mixin.GroupWidget.prototype.removeItems.call( this, items );
7288
7289 this.emit( 'remove', items );
7290
7291 return this;
7292 };
7293
7294 /**
7295 * Clear all options from the select. Options will be detached from the DOM, not removed,
7296 * so that they can be reused later. To remove a subset of options from the select, use
7297 * the #removeItems method.
7298 *
7299 * @fires remove
7300 * @chainable
7301 * @return {OO.ui.Widget} The widget, for chaining
7302 */
7303 OO.ui.SelectWidget.prototype.clearItems = function () {
7304 var items = this.items.slice();
7305
7306 // Mixin method
7307 OO.ui.mixin.GroupWidget.prototype.clearItems.call( this );
7308
7309 // Clear selection
7310 this.selectItem( null );
7311
7312 this.emit( 'remove', items );
7313
7314 return this;
7315 };
7316
7317 /**
7318 * Set the DOM element which has focus while the user is interacting with this SelectWidget.
7319 *
7320 * This is used to set `aria-activedescendant` and `aria-expanded` on it.
7321 *
7322 * @protected
7323 * @param {jQuery} $focusOwner
7324 */
7325 OO.ui.SelectWidget.prototype.setFocusOwner = function ( $focusOwner ) {
7326 this.$focusOwner = $focusOwner;
7327 };
7328
7329 /**
7330 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
7331 * with an {@link OO.ui.mixin.IconElement icon} and/or
7332 * {@link OO.ui.mixin.IndicatorElement indicator}.
7333 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
7334 * options. For more information about options and selects, please see the
7335 * [OOUI documentation on MediaWiki][1].
7336 *
7337 * @example
7338 * // Decorated options in a select widget.
7339 * var select = new OO.ui.SelectWidget( {
7340 * items: [
7341 * new OO.ui.DecoratedOptionWidget( {
7342 * data: 'a',
7343 * label: 'Option with icon',
7344 * icon: 'help'
7345 * } ),
7346 * new OO.ui.DecoratedOptionWidget( {
7347 * data: 'b',
7348 * label: 'Option with indicator',
7349 * indicator: 'next'
7350 * } )
7351 * ]
7352 * } );
7353 * $( document.body ).append( select.$element );
7354 *
7355 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7356 *
7357 * @class
7358 * @extends OO.ui.OptionWidget
7359 * @mixins OO.ui.mixin.IconElement
7360 * @mixins OO.ui.mixin.IndicatorElement
7361 *
7362 * @constructor
7363 * @param {Object} [config] Configuration options
7364 */
7365 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
7366 // Parent constructor
7367 OO.ui.DecoratedOptionWidget.parent.call( this, config );
7368
7369 // Mixin constructors
7370 OO.ui.mixin.IconElement.call( this, config );
7371 OO.ui.mixin.IndicatorElement.call( this, config );
7372
7373 // Initialization
7374 this.$element
7375 .addClass( 'oo-ui-decoratedOptionWidget' )
7376 .prepend( this.$icon )
7377 .append( this.$indicator );
7378 };
7379
7380 /* Setup */
7381
7382 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
7383 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IconElement );
7384 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IndicatorElement );
7385
7386 /**
7387 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
7388 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
7389 * the [OOUI documentation on MediaWiki] [1] for more information.
7390 *
7391 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
7392 *
7393 * @class
7394 * @extends OO.ui.DecoratedOptionWidget
7395 *
7396 * @constructor
7397 * @param {Object} [config] Configuration options
7398 */
7399 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
7400 // Parent constructor
7401 OO.ui.MenuOptionWidget.parent.call( this, config );
7402
7403 // Properties
7404 this.checkIcon = new OO.ui.IconWidget( {
7405 icon: 'check',
7406 classes: [ 'oo-ui-menuOptionWidget-checkIcon' ]
7407 } );
7408
7409 // Initialization
7410 this.$element
7411 .prepend( this.checkIcon.$element )
7412 .addClass( 'oo-ui-menuOptionWidget' );
7413 };
7414
7415 /* Setup */
7416
7417 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
7418
7419 /* Static Properties */
7420
7421 /**
7422 * @static
7423 * @inheritdoc
7424 */
7425 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
7426
7427 /**
7428 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to
7429 * group one or more related {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets
7430 * cannot be highlighted or selected.
7431 *
7432 * @example
7433 * var dropdown = new OO.ui.DropdownWidget( {
7434 * menu: {
7435 * items: [
7436 * new OO.ui.MenuSectionOptionWidget( {
7437 * label: 'Dogs'
7438 * } ),
7439 * new OO.ui.MenuOptionWidget( {
7440 * data: 'corgi',
7441 * label: 'Welsh Corgi'
7442 * } ),
7443 * new OO.ui.MenuOptionWidget( {
7444 * data: 'poodle',
7445 * label: 'Standard Poodle'
7446 * } ),
7447 * new OO.ui.MenuSectionOptionWidget( {
7448 * label: 'Cats'
7449 * } ),
7450 * new OO.ui.MenuOptionWidget( {
7451 * data: 'lion',
7452 * label: 'Lion'
7453 * } )
7454 * ]
7455 * }
7456 * } );
7457 * $( document.body ).append( dropdown.$element );
7458 *
7459 * @class
7460 * @extends OO.ui.DecoratedOptionWidget
7461 *
7462 * @constructor
7463 * @param {Object} [config] Configuration options
7464 */
7465 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
7466 // Parent constructor
7467 OO.ui.MenuSectionOptionWidget.parent.call( this, config );
7468
7469 // Initialization
7470 this.$element
7471 .addClass( 'oo-ui-menuSectionOptionWidget' )
7472 .removeAttr( 'role aria-selected' );
7473 this.selected = false;
7474 };
7475
7476 /* Setup */
7477
7478 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
7479
7480 /* Static Properties */
7481
7482 /**
7483 * @static
7484 * @inheritdoc
7485 */
7486 OO.ui.MenuSectionOptionWidget.static.selectable = false;
7487
7488 /**
7489 * @static
7490 * @inheritdoc
7491 */
7492 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
7493
7494 /**
7495 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
7496 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
7497 * See {@link OO.ui.DropdownWidget DropdownWidget},
7498 * {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}, and
7499 * {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
7500 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
7501 * and customized to be opened, closed, and displayed as needed.
7502 *
7503 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
7504 * mouse outside the menu.
7505 *
7506 * Menus also have support for keyboard interaction:
7507 *
7508 * - Enter/Return key: choose and select a menu option
7509 * - Up-arrow key: highlight the previous menu option
7510 * - Down-arrow key: highlight the next menu option
7511 * - Escape key: hide the menu
7512 *
7513 * Unlike most widgets, MenuSelectWidget is initially hidden and must be shown by calling #toggle.
7514 *
7515 * Please see the [OOUI documentation on MediaWiki][1] for more information.
7516 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7517 *
7518 * @class
7519 * @extends OO.ui.SelectWidget
7520 * @mixins OO.ui.mixin.ClippableElement
7521 * @mixins OO.ui.mixin.FloatableElement
7522 *
7523 * @constructor
7524 * @param {Object} [config] Configuration options
7525 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu
7526 * items that match the text the user types. This config is used by
7527 * {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget} and
7528 * {@link OO.ui.mixin.LookupElement LookupElement}
7529 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
7530 * the text the user types. This config is used by
7531 * {@link OO.ui.TagMultiselectWidget TagMultiselectWidget}
7532 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks
7533 * the mouse anywhere on the page outside of this widget, the menu is hidden. For example, if
7534 * there is a button that toggles the menu's visibility on click, the menu will be hidden then
7535 * re-shown when the user clicks that button, unless the button (or its parent widget) is passed
7536 * in here.
7537 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
7538 * @cfg {jQuery} [$autoCloseIgnore] If these elements are clicked, don't auto-hide the menu.
7539 * @cfg {boolean} [hideOnChoose=true] Hide the menu when the user chooses an option.
7540 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
7541 * @cfg {boolean} [highlightOnFilter] Highlight the first result when filtering
7542 * @cfg {string} [filterMode='prefix'] The mode by which the menu filters the results.
7543 * Options are 'exact', 'prefix' or 'substring'. See `OO.ui.SelectWidget#getItemMatcher`
7544 * @param {number|string} [width] Width of the menu as a number of pixels or CSS string with unit
7545 * suffix, used by {@link OO.ui.mixin.ClippableElement ClippableElement}
7546 */
7547 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
7548 // Configuration initialization
7549 config = config || {};
7550
7551 // Parent constructor
7552 OO.ui.MenuSelectWidget.parent.call( this, config );
7553
7554 // Mixin constructors
7555 OO.ui.mixin.ClippableElement.call( this, $.extend( { $clippable: this.$group }, config ) );
7556 OO.ui.mixin.FloatableElement.call( this, config );
7557
7558 // Initial vertical positions other than 'center' will result in
7559 // the menu being flipped if there is not enough space in the container.
7560 // Store the original position so we know what to reset to.
7561 this.originalVerticalPosition = this.verticalPosition;
7562
7563 // Properties
7564 this.autoHide = config.autoHide === undefined || !!config.autoHide;
7565 this.hideOnChoose = config.hideOnChoose === undefined || !!config.hideOnChoose;
7566 this.filterFromInput = !!config.filterFromInput;
7567 this.$input = config.$input ? config.$input : config.input ? config.input.$input : null;
7568 this.$widget = config.widget ? config.widget.$element : null;
7569 this.$autoCloseIgnore = config.$autoCloseIgnore || $( [] );
7570 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
7571 this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 );
7572 this.highlightOnFilter = !!config.highlightOnFilter;
7573 this.lastHighlightedItem = null;
7574 this.width = config.width;
7575 this.filterMode = config.filterMode;
7576
7577 // Initialization
7578 this.$element.addClass( 'oo-ui-menuSelectWidget' );
7579 if ( config.widget ) {
7580 this.setFocusOwner( config.widget.$tabIndexed );
7581 }
7582
7583 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
7584 // that reference properties not initialized at that time of parent class construction
7585 // TODO: Find a better way to handle post-constructor setup
7586 this.visible = false;
7587 this.$element.addClass( 'oo-ui-element-hidden' );
7588 this.$focusOwner.attr( 'aria-expanded', 'false' );
7589 };
7590
7591 /* Setup */
7592
7593 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
7594 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement );
7595 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.FloatableElement );
7596
7597 /* Events */
7598
7599 /**
7600 * @event ready
7601 *
7602 * The menu is ready: it is visible and has been positioned and clipped.
7603 */
7604
7605 /* Static properties */
7606
7607 /**
7608 * Positions to flip to if there isn't room in the container for the
7609 * menu in a specific direction.
7610 *
7611 * @property {Object.<string,string>}
7612 */
7613 OO.ui.MenuSelectWidget.static.flippedPositions = {
7614 below: 'above',
7615 above: 'below',
7616 top: 'bottom',
7617 bottom: 'top'
7618 };
7619
7620 /* Methods */
7621
7622 /**
7623 * Handles document mouse down events.
7624 *
7625 * @protected
7626 * @param {MouseEvent} e Mouse down event
7627 */
7628 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
7629 if (
7630 this.isVisible() &&
7631 !OO.ui.contains(
7632 this.$element.add( this.$widget ).add( this.$autoCloseIgnore ).get(),
7633 e.target,
7634 true
7635 )
7636 ) {
7637 this.toggle( false );
7638 }
7639 };
7640
7641 /**
7642 * @inheritdoc
7643 */
7644 OO.ui.MenuSelectWidget.prototype.onDocumentKeyDown = function ( e ) {
7645 var currentItem = this.findHighlightedItem() || this.findSelectedItem();
7646
7647 if ( !this.isDisabled() && this.isVisible() ) {
7648 switch ( e.keyCode ) {
7649 case OO.ui.Keys.LEFT:
7650 case OO.ui.Keys.RIGHT:
7651 // Do nothing if a text field is associated, arrow keys will be handled natively
7652 if ( !this.$input ) {
7653 OO.ui.MenuSelectWidget.parent.prototype.onDocumentKeyDown.call( this, e );
7654 }
7655 break;
7656 case OO.ui.Keys.ESCAPE:
7657 case OO.ui.Keys.TAB:
7658 if ( currentItem ) {
7659 currentItem.setHighlighted( false );
7660 }
7661 this.toggle( false );
7662 // Don't prevent tabbing away, prevent defocusing
7663 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
7664 e.preventDefault();
7665 e.stopPropagation();
7666 }
7667 break;
7668 default:
7669 OO.ui.MenuSelectWidget.parent.prototype.onDocumentKeyDown.call( this, e );
7670 return;
7671 }
7672 }
7673 };
7674
7675 /**
7676 * Update menu item visibility and clipping after input changes (if filterFromInput is enabled)
7677 * or after items were added/removed (always).
7678 *
7679 * @protected
7680 */
7681 OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () {
7682 var i, item, items, visible, section, sectionEmpty, filter, exactFilter,
7683 anyVisible = false,
7684 len = this.items.length,
7685 showAll = !this.isVisible(),
7686 exactMatch = false;
7687
7688 if ( this.$input && this.filterFromInput ) {
7689 filter = showAll ? null : this.getItemMatcher( this.$input.val(), this.filterMode );
7690 exactFilter = this.getItemMatcher( this.$input.val(), 'exact' );
7691 // Hide non-matching options, and also hide section headers if all options
7692 // in their section are hidden.
7693 for ( i = 0; i < len; i++ ) {
7694 item = this.items[ i ];
7695 if ( item instanceof OO.ui.MenuSectionOptionWidget ) {
7696 if ( section ) {
7697 // If the previous section was empty, hide its header
7698 section.toggle( showAll || !sectionEmpty );
7699 }
7700 section = item;
7701 sectionEmpty = true;
7702 } else if ( item instanceof OO.ui.OptionWidget ) {
7703 visible = showAll || filter( item );
7704 exactMatch = exactMatch || exactFilter( item );
7705 anyVisible = anyVisible || visible;
7706 sectionEmpty = sectionEmpty && !visible;
7707 item.toggle( visible );
7708 }
7709 }
7710 // Process the final section
7711 if ( section ) {
7712 section.toggle( showAll || !sectionEmpty );
7713 }
7714
7715 if ( anyVisible && this.items.length && !exactMatch ) {
7716 this.scrollItemIntoView( this.items[ 0 ] );
7717 }
7718
7719 if ( !anyVisible ) {
7720 this.highlightItem( null );
7721 }
7722
7723 this.$element.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible );
7724
7725 if (
7726 this.highlightOnFilter &&
7727 !( this.lastHighlightedItem && this.lastHighlightedItem.isVisible() )
7728 ) {
7729 // Highlight the first item on the list
7730 item = null;
7731 items = this.getItems();
7732 for ( i = 0; i < items.length; i++ ) {
7733 if ( items[ i ].isVisible() ) {
7734 item = items[ i ];
7735 break;
7736 }
7737 }
7738 this.highlightItem( item );
7739 this.lastHighlightedItem = item;
7740 }
7741
7742 }
7743
7744 // Reevaluate clipping
7745 this.clip();
7746 };
7747
7748 /**
7749 * @inheritdoc
7750 */
7751 OO.ui.MenuSelectWidget.prototype.bindDocumentKeyDownListener = function () {
7752 if ( this.$input ) {
7753 this.$input.on( 'keydown', this.onDocumentKeyDownHandler );
7754 } else {
7755 OO.ui.MenuSelectWidget.parent.prototype.bindDocumentKeyDownListener.call( this );
7756 }
7757 };
7758
7759 /**
7760 * @inheritdoc
7761 */
7762 OO.ui.MenuSelectWidget.prototype.unbindDocumentKeyDownListener = function () {
7763 if ( this.$input ) {
7764 this.$input.off( 'keydown', this.onDocumentKeyDownHandler );
7765 } else {
7766 OO.ui.MenuSelectWidget.parent.prototype.unbindDocumentKeyDownListener.call( this );
7767 }
7768 };
7769
7770 /**
7771 * @inheritdoc
7772 */
7773 OO.ui.MenuSelectWidget.prototype.bindDocumentKeyPressListener = function () {
7774 if ( this.$input ) {
7775 if ( this.filterFromInput ) {
7776 this.$input.on(
7777 'keydown mouseup cut paste change input select',
7778 this.onInputEditHandler
7779 );
7780 this.updateItemVisibility();
7781 }
7782 } else {
7783 OO.ui.MenuSelectWidget.parent.prototype.bindDocumentKeyPressListener.call( this );
7784 }
7785 };
7786
7787 /**
7788 * @inheritdoc
7789 */
7790 OO.ui.MenuSelectWidget.prototype.unbindDocumentKeyPressListener = function () {
7791 if ( this.$input ) {
7792 if ( this.filterFromInput ) {
7793 this.$input.off(
7794 'keydown mouseup cut paste change input select',
7795 this.onInputEditHandler
7796 );
7797 this.updateItemVisibility();
7798 }
7799 } else {
7800 OO.ui.MenuSelectWidget.parent.prototype.unbindDocumentKeyPressListener.call( this );
7801 }
7802 };
7803
7804 /**
7805 * Choose an item.
7806 *
7807 * When a user chooses an item, the menu is closed, unless the hideOnChoose config option is
7808 * set to false.
7809 *
7810 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with
7811 * the keyboard or mouse and it becomes selected. To select an item programmatically,
7812 * use the #selectItem method.
7813 *
7814 * @param {OO.ui.OptionWidget} item Item to choose
7815 * @chainable
7816 * @return {OO.ui.Widget} The widget, for chaining
7817 */
7818 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
7819 OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item );
7820 if ( this.hideOnChoose ) {
7821 this.toggle( false );
7822 }
7823 return this;
7824 };
7825
7826 /**
7827 * @inheritdoc
7828 */
7829 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
7830 // Parent method
7831 OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index );
7832
7833 this.updateItemVisibility();
7834
7835 return this;
7836 };
7837
7838 /**
7839 * @inheritdoc
7840 */
7841 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
7842 // Parent method
7843 OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items );
7844
7845 this.updateItemVisibility();
7846
7847 return this;
7848 };
7849
7850 /**
7851 * @inheritdoc
7852 */
7853 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
7854 // Parent method
7855 OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this );
7856
7857 this.updateItemVisibility();
7858
7859 return this;
7860 };
7861
7862 /**
7863 * Toggle visibility of the menu. The menu is initially hidden and must be shown by calling
7864 * `.toggle( true )` after its #$element is attached to the DOM.
7865 *
7866 * Do not show the menu while it is not attached to the DOM. The calculations required to display
7867 * it in the right place and with the right dimensions only work correctly while it is attached.
7868 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
7869 * strictly enforced, so currently it only generates a warning in the browser console.
7870 *
7871 * @fires ready
7872 * @inheritdoc
7873 */
7874 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
7875 var change, originalHeight, flippedHeight;
7876
7877 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
7878 change = visible !== this.isVisible();
7879
7880 if ( visible && !this.warnedUnattached && !this.isElementAttached() ) {
7881 OO.ui.warnDeprecation( 'MenuSelectWidget#toggle: Before calling this method, the menu must be attached to the DOM.' );
7882 this.warnedUnattached = true;
7883 }
7884
7885 if ( change && visible ) {
7886 // Reset position before showing the popup again. It's possible we no longer need to flip
7887 // (e.g. if the user scrolled).
7888 this.setVerticalPosition( this.originalVerticalPosition );
7889 }
7890
7891 // Parent method
7892 OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible );
7893
7894 if ( change ) {
7895 if ( visible ) {
7896
7897 if ( this.width ) {
7898 this.setIdealSize( this.width );
7899 } else if ( this.$floatableContainer ) {
7900 this.$clippable.css( 'width', 'auto' );
7901 this.setIdealSize(
7902 this.$floatableContainer[ 0 ].offsetWidth > this.$clippable[ 0 ].offsetWidth ?
7903 // Dropdown is smaller than handle so expand to width
7904 this.$floatableContainer[ 0 ].offsetWidth :
7905 // Dropdown is larger than handle so auto size
7906 'auto'
7907 );
7908 this.$clippable.css( 'width', '' );
7909 }
7910
7911 this.togglePositioning( !!this.$floatableContainer );
7912 this.toggleClipping( true );
7913
7914 this.bindDocumentKeyDownListener();
7915 this.bindDocumentKeyPressListener();
7916
7917 if (
7918 ( this.isClippedVertically() || this.isFloatableOutOfView() ) &&
7919 this.originalVerticalPosition !== 'center'
7920 ) {
7921 // If opening the menu in one direction causes it to be clipped, flip it
7922 originalHeight = this.$element.height();
7923 this.setVerticalPosition(
7924 this.constructor.static.flippedPositions[ this.originalVerticalPosition ]
7925 );
7926 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
7927 // If flipping also causes it to be clipped, open in whichever direction
7928 // we have more space
7929 flippedHeight = this.$element.height();
7930 if ( originalHeight > flippedHeight ) {
7931 this.setVerticalPosition( this.originalVerticalPosition );
7932 }
7933 }
7934 }
7935 // Note that we do not flip the menu's opening direction if the clipping changes
7936 // later (e.g. after the user scrolls), that seems like it would be annoying
7937
7938 this.$focusOwner.attr( 'aria-expanded', 'true' );
7939
7940 if ( this.findSelectedItem() ) {
7941 this.$focusOwner.attr( 'aria-activedescendant', this.findSelectedItem().getElementId() );
7942 this.findSelectedItem().scrollElementIntoView( { duration: 0 } );
7943 }
7944
7945 // Auto-hide
7946 if ( this.autoHide ) {
7947 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
7948 }
7949
7950 this.emit( 'ready' );
7951 } else {
7952 this.$focusOwner.removeAttr( 'aria-activedescendant' );
7953 this.unbindDocumentKeyDownListener();
7954 this.unbindDocumentKeyPressListener();
7955 this.$focusOwner.attr( 'aria-expanded', 'false' );
7956 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
7957 this.togglePositioning( false );
7958 this.toggleClipping( false );
7959 }
7960 }
7961
7962 return this;
7963 };
7964
7965 /**
7966 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
7967 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
7968 * users can interact with it.
7969 *
7970 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7971 * OO.ui.DropdownInputWidget instead.
7972 *
7973 * @example
7974 * // A DropdownWidget with a menu that contains three options.
7975 * var dropDown = new OO.ui.DropdownWidget( {
7976 * label: 'Dropdown menu: Select a menu option',
7977 * menu: {
7978 * items: [
7979 * new OO.ui.MenuOptionWidget( {
7980 * data: 'a',
7981 * label: 'First'
7982 * } ),
7983 * new OO.ui.MenuOptionWidget( {
7984 * data: 'b',
7985 * label: 'Second'
7986 * } ),
7987 * new OO.ui.MenuOptionWidget( {
7988 * data: 'c',
7989 * label: 'Third'
7990 * } )
7991 * ]
7992 * }
7993 * } );
7994 *
7995 * $( document.body ).append( dropDown.$element );
7996 *
7997 * dropDown.getMenu().selectItemByData( 'b' );
7998 *
7999 * dropDown.getMenu().findSelectedItem().getData(); // Returns 'b'.
8000 *
8001 * For more information, please see the [OOUI documentation on MediaWiki] [1].
8002 *
8003 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
8004 *
8005 * @class
8006 * @extends OO.ui.Widget
8007 * @mixins OO.ui.mixin.IconElement
8008 * @mixins OO.ui.mixin.IndicatorElement
8009 * @mixins OO.ui.mixin.LabelElement
8010 * @mixins OO.ui.mixin.TitledElement
8011 * @mixins OO.ui.mixin.TabIndexedElement
8012 *
8013 * @constructor
8014 * @param {Object} [config] Configuration options
8015 * @cfg {Object} [menu] Configuration options to pass to
8016 * {@link OO.ui.MenuSelectWidget menu select widget}.
8017 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful
8018 * in cases where the expanded menu is larger than its containing `<div>`. The specified overlay
8019 * layer is usually on top of the containing `<div>` and has a larger area. By default, the menu
8020 * uses relative positioning.
8021 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
8022 */
8023 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
8024 // Configuration initialization
8025 config = $.extend( { indicator: 'down' }, config );
8026
8027 // Parent constructor
8028 OO.ui.DropdownWidget.parent.call( this, config );
8029
8030 // Properties (must be set before TabIndexedElement constructor call)
8031 this.$handle = $( '<button>' );
8032 this.$overlay = ( config.$overlay === true ?
8033 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( {
8040 $titled: this.$label
8041 }, config ) );
8042 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {
8043 $tabIndexed: this.$handle
8044 }, config ) );
8045
8046 // Properties
8047 this.menu = new OO.ui.MenuSelectWidget( $.extend( {
8048 widget: this,
8049 $floatableContainer: this.$element
8050 }, config.menu ) );
8051
8052 // Events
8053 this.$handle.on( {
8054 click: this.onClick.bind( this ),
8055 keydown: this.onKeyDown.bind( this ),
8056 // Hack? Handle type-to-search when menu is not expanded and not handling its own events.
8057 keypress: this.menu.onDocumentKeyPressHandler,
8058 blur: this.menu.clearKeyPressBuffer.bind( this.menu )
8059 } );
8060 this.menu.connect( this, {
8061 select: 'onMenuSelect',
8062 toggle: 'onMenuToggle'
8063 } );
8064
8065 // Initialization
8066 this.$handle
8067 .addClass( 'oo-ui-dropdownWidget-handle' )
8068 .attr( {
8069 type: 'button',
8070 'aria-owns': this.menu.getElementId(),
8071 'aria-haspopup': 'listbox'
8072 } )
8073 .append( this.$icon, this.$label, this.$indicator );
8074 this.$element
8075 .addClass( 'oo-ui-dropdownWidget' )
8076 .append( this.$handle );
8077 this.$overlay.append( this.menu.$element );
8078 };
8079
8080 /* Setup */
8081
8082 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
8083 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IconElement );
8084 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IndicatorElement );
8085 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.LabelElement );
8086 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TitledElement );
8087 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TabIndexedElement );
8088
8089 /* Methods */
8090
8091 /**
8092 * Get the menu.
8093 *
8094 * @return {OO.ui.MenuSelectWidget} Menu of widget
8095 */
8096 OO.ui.DropdownWidget.prototype.getMenu = function () {
8097 return this.menu;
8098 };
8099
8100 /**
8101 * Handles menu select events.
8102 *
8103 * @private
8104 * @param {OO.ui.MenuOptionWidget} item Selected menu item
8105 */
8106 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
8107 var selectedLabel;
8108
8109 if ( !item ) {
8110 this.setLabel( null );
8111 return;
8112 }
8113
8114 selectedLabel = item.getLabel();
8115
8116 // If the label is a DOM element, clone it, because setLabel will append() it
8117 if ( selectedLabel instanceof $ ) {
8118 selectedLabel = selectedLabel.clone();
8119 }
8120
8121 this.setLabel( selectedLabel );
8122 };
8123
8124 /**
8125 * Handle menu toggle events.
8126 *
8127 * @private
8128 * @param {boolean} isVisible Open state of the menu
8129 */
8130 OO.ui.DropdownWidget.prototype.onMenuToggle = function ( isVisible ) {
8131 this.$element.toggleClass( 'oo-ui-dropdownWidget-open', isVisible );
8132 };
8133
8134 /**
8135 * Handle mouse click events.
8136 *
8137 * @private
8138 * @param {jQuery.Event} e Mouse click event
8139 * @return {undefined/boolean} False to prevent default if event is handled
8140 */
8141 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
8142 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
8143 this.menu.toggle();
8144 }
8145 return false;
8146 };
8147
8148 /**
8149 * Handle key down events.
8150 *
8151 * @private
8152 * @param {jQuery.Event} e Key down event
8153 * @return {undefined/boolean} False to prevent default if event is handled
8154 */
8155 OO.ui.DropdownWidget.prototype.onKeyDown = function ( e ) {
8156 if (
8157 !this.isDisabled() &&
8158 (
8159 e.which === OO.ui.Keys.ENTER ||
8160 (
8161 e.which === OO.ui.Keys.SPACE &&
8162 // Avoid conflicts with type-to-search, see SelectWidget#onKeyPress.
8163 // Space only closes the menu is the user is not typing to search.
8164 this.menu.keyPressBuffer === ''
8165 ) ||
8166 (
8167 !this.menu.isVisible() &&
8168 (
8169 e.which === OO.ui.Keys.UP ||
8170 e.which === OO.ui.Keys.DOWN
8171 )
8172 )
8173 )
8174 ) {
8175 this.menu.toggle();
8176 return false;
8177 }
8178 };
8179
8180 /**
8181 * RadioOptionWidget is an option widget that looks like a radio button.
8182 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
8183 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8184 *
8185 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8186 *
8187 * @class
8188 * @extends OO.ui.OptionWidget
8189 *
8190 * @constructor
8191 * @param {Object} [config] Configuration options
8192 */
8193 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
8194 // Configuration initialization
8195 config = config || {};
8196
8197 // Properties (must be done before parent constructor which calls #setDisabled)
8198 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
8199
8200 // Parent constructor
8201 OO.ui.RadioOptionWidget.parent.call( this, config );
8202
8203 // Initialization
8204 // Remove implicit role, we're handling it ourselves
8205 this.radio.$input.attr( 'role', 'presentation' );
8206 this.$element
8207 .addClass( 'oo-ui-radioOptionWidget' )
8208 .attr( 'role', 'radio' )
8209 .attr( 'aria-checked', 'false' )
8210 .removeAttr( 'aria-selected' )
8211 .prepend( this.radio.$element );
8212 };
8213
8214 /* Setup */
8215
8216 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
8217
8218 /* Static Properties */
8219
8220 /**
8221 * @static
8222 * @inheritdoc
8223 */
8224 OO.ui.RadioOptionWidget.static.highlightable = false;
8225
8226 /**
8227 * @static
8228 * @inheritdoc
8229 */
8230 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
8231
8232 /**
8233 * @static
8234 * @inheritdoc
8235 */
8236 OO.ui.RadioOptionWidget.static.pressable = false;
8237
8238 /**
8239 * @static
8240 * @inheritdoc
8241 */
8242 OO.ui.RadioOptionWidget.static.tagName = 'label';
8243
8244 /* Methods */
8245
8246 /**
8247 * @inheritdoc
8248 */
8249 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
8250 OO.ui.RadioOptionWidget.parent.prototype.setSelected.call( this, state );
8251
8252 this.radio.setSelected( state );
8253 this.$element
8254 .attr( 'aria-checked', state.toString() )
8255 .removeAttr( 'aria-selected' );
8256
8257 return this;
8258 };
8259
8260 /**
8261 * @inheritdoc
8262 */
8263 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
8264 OO.ui.RadioOptionWidget.parent.prototype.setDisabled.call( this, disabled );
8265
8266 this.radio.setDisabled( this.isDisabled() );
8267
8268 return this;
8269 };
8270
8271 /**
8272 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
8273 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
8274 * an interface for adding, removing and selecting options.
8275 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8276 *
8277 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8278 * OO.ui.RadioSelectInputWidget instead.
8279 *
8280 * @example
8281 * // A RadioSelectWidget with RadioOptions.
8282 * var option1 = new OO.ui.RadioOptionWidget( {
8283 * data: 'a',
8284 * label: 'Selected radio option'
8285 * } ),
8286 * option2 = new OO.ui.RadioOptionWidget( {
8287 * data: 'b',
8288 * label: 'Unselected radio option'
8289 * } );
8290 * radioSelect = new OO.ui.RadioSelectWidget( {
8291 * items: [ option1, option2 ]
8292 * } );
8293 *
8294 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
8295 * radioSelect.selectItem( option1 );
8296 *
8297 * $( document.body ).append( radioSelect.$element );
8298 *
8299 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8300
8301 *
8302 * @class
8303 * @extends OO.ui.SelectWidget
8304 * @mixins OO.ui.mixin.TabIndexedElement
8305 *
8306 * @constructor
8307 * @param {Object} [config] Configuration options
8308 */
8309 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
8310 // Parent constructor
8311 OO.ui.RadioSelectWidget.parent.call( this, config );
8312
8313 // Mixin constructors
8314 OO.ui.mixin.TabIndexedElement.call( this, config );
8315
8316 // Events
8317 this.$element.on( {
8318 focus: this.bindDocumentKeyDownListener.bind( this ),
8319 blur: this.unbindDocumentKeyDownListener.bind( this )
8320 } );
8321
8322 // Initialization
8323 this.$element
8324 .addClass( 'oo-ui-radioSelectWidget' )
8325 .attr( 'role', 'radiogroup' );
8326 };
8327
8328 /* Setup */
8329
8330 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
8331 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.mixin.TabIndexedElement );
8332
8333 /**
8334 * MultioptionWidgets are special elements that can be selected and configured with data. The
8335 * data is often unique for each option, but it does not have to be. MultioptionWidgets are used
8336 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
8337 * and examples, please see the [OOUI documentation on MediaWiki][1].
8338 *
8339 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8340 *
8341 * @class
8342 * @extends OO.ui.Widget
8343 * @mixins OO.ui.mixin.ItemWidget
8344 * @mixins OO.ui.mixin.LabelElement
8345 * @mixins OO.ui.mixin.TitledElement
8346 *
8347 * @constructor
8348 * @param {Object} [config] Configuration options
8349 * @cfg {boolean} [selected=false] Whether the option is initially selected
8350 */
8351 OO.ui.MultioptionWidget = function OoUiMultioptionWidget( config ) {
8352 // Configuration initialization
8353 config = config || {};
8354
8355 // Parent constructor
8356 OO.ui.MultioptionWidget.parent.call( this, config );
8357
8358 // Mixin constructors
8359 OO.ui.mixin.ItemWidget.call( this );
8360 OO.ui.mixin.LabelElement.call( this, config );
8361 OO.ui.mixin.TitledElement.call( this, config );
8362
8363 // Properties
8364 this.selected = null;
8365
8366 // Initialization
8367 this.$element
8368 .addClass( 'oo-ui-multioptionWidget' )
8369 .append( this.$label );
8370 this.setSelected( config.selected );
8371 };
8372
8373 /* Setup */
8374
8375 OO.inheritClass( OO.ui.MultioptionWidget, OO.ui.Widget );
8376 OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.ItemWidget );
8377 OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.LabelElement );
8378 OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.TitledElement );
8379
8380 /* Events */
8381
8382 /**
8383 * @event change
8384 *
8385 * A change event is emitted when the selected state of the option changes.
8386 *
8387 * @param {boolean} selected Whether the option is now selected
8388 */
8389
8390 /* Methods */
8391
8392 /**
8393 * Check if the option is selected.
8394 *
8395 * @return {boolean} Item is selected
8396 */
8397 OO.ui.MultioptionWidget.prototype.isSelected = function () {
8398 return this.selected;
8399 };
8400
8401 /**
8402 * Set the option’s selected state. In general, all modifications to the selection
8403 * should be handled by the SelectWidget’s
8404 * {@link OO.ui.SelectWidget#selectItem selectItem( [item] )} method instead of this method.
8405 *
8406 * @param {boolean} [state=false] Select option
8407 * @chainable
8408 * @return {OO.ui.Widget} The widget, for chaining
8409 */
8410 OO.ui.MultioptionWidget.prototype.setSelected = function ( state ) {
8411 state = !!state;
8412 if ( this.selected !== state ) {
8413 this.selected = state;
8414 this.emit( 'change', state );
8415 this.$element.toggleClass( 'oo-ui-multioptionWidget-selected', state );
8416 }
8417 return this;
8418 };
8419
8420 /**
8421 * MultiselectWidget allows selecting multiple options from a list.
8422 *
8423 * For more information about menus and options, please see the [OOUI documentation
8424 * on MediaWiki][1].
8425 *
8426 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
8427 *
8428 * @class
8429 * @abstract
8430 * @extends OO.ui.Widget
8431 * @mixins OO.ui.mixin.GroupWidget
8432 * @mixins OO.ui.mixin.TitledElement
8433 *
8434 * @constructor
8435 * @param {Object} [config] Configuration options
8436 * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
8437 */
8438 OO.ui.MultiselectWidget = function OoUiMultiselectWidget( config ) {
8439 // Parent constructor
8440 OO.ui.MultiselectWidget.parent.call( this, config );
8441
8442 // Configuration initialization
8443 config = config || {};
8444
8445 // Mixin constructors
8446 OO.ui.mixin.GroupWidget.call( this, config );
8447 OO.ui.mixin.TitledElement.call( this, config );
8448
8449 // Events
8450 this.aggregate( {
8451 change: 'select'
8452 } );
8453 // This is mostly for compatibility with TagMultiselectWidget... normally, 'change' is emitted
8454 // by GroupElement only when items are added/removed
8455 this.connect( this, {
8456 select: [ 'emit', 'change' ]
8457 } );
8458
8459 // Initialization
8460 if ( config.items ) {
8461 this.addItems( config.items );
8462 }
8463 this.$group.addClass( 'oo-ui-multiselectWidget-group' );
8464 this.$element.addClass( 'oo-ui-multiselectWidget' )
8465 .append( this.$group );
8466 };
8467
8468 /* Setup */
8469
8470 OO.inheritClass( OO.ui.MultiselectWidget, OO.ui.Widget );
8471 OO.mixinClass( OO.ui.MultiselectWidget, OO.ui.mixin.GroupWidget );
8472 OO.mixinClass( OO.ui.MultiselectWidget, OO.ui.mixin.TitledElement );
8473
8474 /* Events */
8475
8476 /**
8477 * @event change
8478 *
8479 * A change event is emitted when the set of items changes, or an item is selected or deselected.
8480 */
8481
8482 /**
8483 * @event select
8484 *
8485 * A select event is emitted when an item is selected or deselected.
8486 */
8487
8488 /* Methods */
8489
8490 /**
8491 * Find options that are selected.
8492 *
8493 * @return {OO.ui.MultioptionWidget[]} Selected options
8494 */
8495 OO.ui.MultiselectWidget.prototype.findSelectedItems = function () {
8496 return this.items.filter( function ( item ) {
8497 return item.isSelected();
8498 } );
8499 };
8500
8501 /**
8502 * Find the data of options that are selected.
8503 *
8504 * @return {Object[]|string[]} Values of selected options
8505 */
8506 OO.ui.MultiselectWidget.prototype.findSelectedItemsData = function () {
8507 return this.findSelectedItems().map( function ( item ) {
8508 return item.data;
8509 } );
8510 };
8511
8512 /**
8513 * Select options by reference. Options not mentioned in the `items` array will be deselected.
8514 *
8515 * @param {OO.ui.MultioptionWidget[]} items Items to select
8516 * @chainable
8517 * @return {OO.ui.Widget} The widget, for chaining
8518 */
8519 OO.ui.MultiselectWidget.prototype.selectItems = function ( items ) {
8520 this.items.forEach( function ( item ) {
8521 var selected = items.indexOf( item ) !== -1;
8522 item.setSelected( selected );
8523 } );
8524 return this;
8525 };
8526
8527 /**
8528 * Select items by their data. Options not mentioned in the `datas` array will be deselected.
8529 *
8530 * @param {Object[]|string[]} datas Values of items to select
8531 * @chainable
8532 * @return {OO.ui.Widget} The widget, for chaining
8533 */
8534 OO.ui.MultiselectWidget.prototype.selectItemsByData = function ( datas ) {
8535 var items,
8536 widget = this;
8537 items = datas.map( function ( data ) {
8538 return widget.findItemFromData( data );
8539 } );
8540 this.selectItems( items );
8541 return this;
8542 };
8543
8544 /**
8545 * CheckboxMultioptionWidget is an option widget that looks like a checkbox.
8546 * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
8547 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8548 *
8549 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8550 *
8551 * @class
8552 * @extends OO.ui.MultioptionWidget
8553 *
8554 * @constructor
8555 * @param {Object} [config] Configuration options
8556 */
8557 OO.ui.CheckboxMultioptionWidget = function OoUiCheckboxMultioptionWidget( config ) {
8558 // Configuration initialization
8559 config = config || {};
8560
8561 // Properties (must be done before parent constructor which calls #setDisabled)
8562 this.checkbox = new OO.ui.CheckboxInputWidget();
8563
8564 // Parent constructor
8565 OO.ui.CheckboxMultioptionWidget.parent.call( this, config );
8566
8567 // Events
8568 this.checkbox.on( 'change', this.onCheckboxChange.bind( this ) );
8569 this.$element.on( 'keydown', this.onKeyDown.bind( this ) );
8570
8571 // Initialization
8572 this.$element
8573 .addClass( 'oo-ui-checkboxMultioptionWidget' )
8574 .prepend( this.checkbox.$element );
8575 };
8576
8577 /* Setup */
8578
8579 OO.inheritClass( OO.ui.CheckboxMultioptionWidget, OO.ui.MultioptionWidget );
8580
8581 /* Static Properties */
8582
8583 /**
8584 * @static
8585 * @inheritdoc
8586 */
8587 OO.ui.CheckboxMultioptionWidget.static.tagName = 'label';
8588
8589 /* Methods */
8590
8591 /**
8592 * Handle checkbox selected state change.
8593 *
8594 * @private
8595 */
8596 OO.ui.CheckboxMultioptionWidget.prototype.onCheckboxChange = function () {
8597 this.setSelected( this.checkbox.isSelected() );
8598 };
8599
8600 /**
8601 * @inheritdoc
8602 */
8603 OO.ui.CheckboxMultioptionWidget.prototype.setSelected = function ( state ) {
8604 OO.ui.CheckboxMultioptionWidget.parent.prototype.setSelected.call( this, state );
8605 this.checkbox.setSelected( state );
8606 return this;
8607 };
8608
8609 /**
8610 * @inheritdoc
8611 */
8612 OO.ui.CheckboxMultioptionWidget.prototype.setDisabled = function ( disabled ) {
8613 OO.ui.CheckboxMultioptionWidget.parent.prototype.setDisabled.call( this, disabled );
8614 this.checkbox.setDisabled( this.isDisabled() );
8615 return this;
8616 };
8617
8618 /**
8619 * Focus the widget.
8620 */
8621 OO.ui.CheckboxMultioptionWidget.prototype.focus = function () {
8622 this.checkbox.focus();
8623 };
8624
8625 /**
8626 * Handle key down events.
8627 *
8628 * @protected
8629 * @param {jQuery.Event} e
8630 */
8631 OO.ui.CheckboxMultioptionWidget.prototype.onKeyDown = function ( e ) {
8632 var
8633 element = this.getElementGroup(),
8634 nextItem;
8635
8636 if ( e.keyCode === OO.ui.Keys.LEFT || e.keyCode === OO.ui.Keys.UP ) {
8637 nextItem = element.getRelativeFocusableItem( this, -1 );
8638 } else if ( e.keyCode === OO.ui.Keys.RIGHT || e.keyCode === OO.ui.Keys.DOWN ) {
8639 nextItem = element.getRelativeFocusableItem( this, 1 );
8640 }
8641
8642 if ( nextItem ) {
8643 e.preventDefault();
8644 nextItem.focus();
8645 }
8646 };
8647
8648 /**
8649 * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
8650 * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
8651 * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
8652 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8653 *
8654 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8655 * OO.ui.CheckboxMultiselectInputWidget instead.
8656 *
8657 * @example
8658 * // A CheckboxMultiselectWidget with CheckboxMultioptions.
8659 * var option1 = new OO.ui.CheckboxMultioptionWidget( {
8660 * data: 'a',
8661 * selected: true,
8662 * label: 'Selected checkbox'
8663 * } ),
8664 * option2 = new OO.ui.CheckboxMultioptionWidget( {
8665 * data: 'b',
8666 * label: 'Unselected checkbox'
8667 * } ),
8668 * multiselect = new OO.ui.CheckboxMultiselectWidget( {
8669 * items: [ option1, option2 ]
8670 * } );
8671 * $( document.body ).append( multiselect.$element );
8672 *
8673 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8674 *
8675 * @class
8676 * @extends OO.ui.MultiselectWidget
8677 *
8678 * @constructor
8679 * @param {Object} [config] Configuration options
8680 */
8681 OO.ui.CheckboxMultiselectWidget = function OoUiCheckboxMultiselectWidget( config ) {
8682 // Parent constructor
8683 OO.ui.CheckboxMultiselectWidget.parent.call( this, config );
8684
8685 // Properties
8686 this.$lastClicked = null;
8687
8688 // Events
8689 this.$group.on( 'click', this.onClick.bind( this ) );
8690
8691 // Initialization
8692 this.$element.addClass( 'oo-ui-checkboxMultiselectWidget' );
8693 };
8694
8695 /* Setup */
8696
8697 OO.inheritClass( OO.ui.CheckboxMultiselectWidget, OO.ui.MultiselectWidget );
8698
8699 /* Methods */
8700
8701 /**
8702 * Get an option by its position relative to the specified item (or to the start of the
8703 * option array, if item is `null`). The direction in which to search through the option array
8704 * is specified with a number: -1 for reverse (the default) or 1 for forward. The method will
8705 * return an option, or `null` if there are no options in the array.
8706 *
8707 * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or
8708 * `null` to start at the beginning of the array.
8709 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
8710 * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items
8711 * in the select.
8712 */
8713 OO.ui.CheckboxMultiselectWidget.prototype.getRelativeFocusableItem = function ( item, direction ) {
8714 var currentIndex, nextIndex, i,
8715 increase = direction > 0 ? 1 : -1,
8716 len = this.items.length;
8717
8718 if ( item ) {
8719 currentIndex = this.items.indexOf( item );
8720 nextIndex = ( currentIndex + increase + len ) % len;
8721 } else {
8722 // If no item is selected and moving forward, start at the beginning.
8723 // If moving backward, start at the end.
8724 nextIndex = direction > 0 ? 0 : len - 1;
8725 }
8726
8727 for ( i = 0; i < len; i++ ) {
8728 item = this.items[ nextIndex ];
8729 if ( item && !item.isDisabled() ) {
8730 return item;
8731 }
8732 nextIndex = ( nextIndex + increase + len ) % len;
8733 }
8734 return null;
8735 };
8736
8737 /**
8738 * Handle click events on checkboxes.
8739 *
8740 * @param {jQuery.Event} e
8741 */
8742 OO.ui.CheckboxMultiselectWidget.prototype.onClick = function ( e ) {
8743 var $options, lastClickedIndex, nowClickedIndex, i, direction, wasSelected, items,
8744 $lastClicked = this.$lastClicked,
8745 $nowClicked = $( e.target ).closest( '.oo-ui-checkboxMultioptionWidget' )
8746 .not( '.oo-ui-widget-disabled' );
8747
8748 // Allow selecting multiple options at once by Shift-clicking them
8749 if ( $lastClicked && $nowClicked.length && e.shiftKey ) {
8750 $options = this.$group.find( '.oo-ui-checkboxMultioptionWidget' );
8751 lastClickedIndex = $options.index( $lastClicked );
8752 nowClickedIndex = $options.index( $nowClicked );
8753 // If it's the same item, either the user is being silly, or it's a fake event generated
8754 // by the browser. In either case we don't need custom handling.
8755 if ( nowClickedIndex !== lastClickedIndex ) {
8756 items = this.items;
8757 wasSelected = items[ nowClickedIndex ].isSelected();
8758 direction = nowClickedIndex > lastClickedIndex ? 1 : -1;
8759
8760 // This depends on the DOM order of the items and the order of the .items array being
8761 // the same.
8762 for ( i = lastClickedIndex; i !== nowClickedIndex; i += direction ) {
8763 if ( !items[ i ].isDisabled() ) {
8764 items[ i ].setSelected( !wasSelected );
8765 }
8766 }
8767 // For the now-clicked element, use immediate timeout to allow the browser to do its own
8768 // handling first, then set our value. The order in which events happen is different for
8769 // clicks on the <input> and on the <label> and there are additional fake clicks fired
8770 // for non-click actions that change the checkboxes.
8771 e.preventDefault();
8772 setTimeout( function () {
8773 if ( !items[ nowClickedIndex ].isDisabled() ) {
8774 items[ nowClickedIndex ].setSelected( !wasSelected );
8775 }
8776 } );
8777 }
8778 }
8779
8780 if ( $nowClicked.length ) {
8781 this.$lastClicked = $nowClicked;
8782 }
8783 };
8784
8785 /**
8786 * Focus the widget
8787 *
8788 * @chainable
8789 * @return {OO.ui.Widget} The widget, for chaining
8790 */
8791 OO.ui.CheckboxMultiselectWidget.prototype.focus = function () {
8792 var item;
8793 if ( !this.isDisabled() ) {
8794 item = this.getRelativeFocusableItem( null, 1 );
8795 if ( item ) {
8796 item.focus();
8797 }
8798 }
8799 return this;
8800 };
8801
8802 /**
8803 * @inheritdoc
8804 */
8805 OO.ui.CheckboxMultiselectWidget.prototype.simulateLabelClick = function () {
8806 this.focus();
8807 };
8808
8809 /**
8810 * Progress bars visually display the status of an operation, such as a download,
8811 * and can be either determinate or indeterminate:
8812 *
8813 * - **determinate** process bars show the percent of an operation that is complete.
8814 *
8815 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
8816 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
8817 * not use percentages.
8818 *
8819 * The value of the `progress` configuration determines whether the bar is determinate
8820 * or indeterminate.
8821 *
8822 * @example
8823 * // Examples of determinate and indeterminate progress bars.
8824 * var progressBar1 = new OO.ui.ProgressBarWidget( {
8825 * progress: 33
8826 * } );
8827 * var progressBar2 = new OO.ui.ProgressBarWidget();
8828 *
8829 * // Create a FieldsetLayout to layout progress bars.
8830 * var fieldset = new OO.ui.FieldsetLayout;
8831 * fieldset.addItems( [
8832 * new OO.ui.FieldLayout( progressBar1, {
8833 * label: 'Determinate',
8834 * align: 'top'
8835 * } ),
8836 * new OO.ui.FieldLayout( progressBar2, {
8837 * label: 'Indeterminate',
8838 * align: 'top'
8839 * } )
8840 * ] );
8841 * $( document.body ).append( fieldset.$element );
8842 *
8843 * @class
8844 * @extends OO.ui.Widget
8845 *
8846 * @constructor
8847 * @param {Object} [config] Configuration options
8848 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
8849 * To create a determinate progress bar, specify a number that reflects the initial
8850 * percent complete.
8851 * By default, the progress bar is indeterminate.
8852 */
8853 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
8854 // Configuration initialization
8855 config = config || {};
8856
8857 // Parent constructor
8858 OO.ui.ProgressBarWidget.parent.call( this, config );
8859
8860 // Properties
8861 this.$bar = $( '<div>' );
8862 this.progress = null;
8863
8864 // Initialization
8865 this.setProgress( config.progress !== undefined ? config.progress : false );
8866 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
8867 this.$element
8868 .attr( {
8869 role: 'progressbar',
8870 'aria-valuemin': 0,
8871 'aria-valuemax': 100
8872 } )
8873 .addClass( 'oo-ui-progressBarWidget' )
8874 .append( this.$bar );
8875 };
8876
8877 /* Setup */
8878
8879 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
8880
8881 /* Static Properties */
8882
8883 /**
8884 * @static
8885 * @inheritdoc
8886 */
8887 OO.ui.ProgressBarWidget.static.tagName = 'div';
8888
8889 /* Methods */
8890
8891 /**
8892 * Get the percent of the progress that has been completed. Indeterminate progresses will
8893 * return `false`.
8894 *
8895 * @return {number|boolean} Progress percent
8896 */
8897 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
8898 return this.progress;
8899 };
8900
8901 /**
8902 * Set the percent of the process completed or `false` for an indeterminate process.
8903 *
8904 * @param {number|boolean} progress Progress percent or `false` for indeterminate
8905 */
8906 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
8907 this.progress = progress;
8908
8909 if ( progress !== false ) {
8910 this.$bar.css( 'width', this.progress + '%' );
8911 this.$element.attr( 'aria-valuenow', this.progress );
8912 } else {
8913 this.$bar.css( 'width', '' );
8914 this.$element.removeAttr( 'aria-valuenow' );
8915 }
8916 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress === false );
8917 };
8918
8919 /**
8920 * InputWidget is the base class for all input widgets, which
8921 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox
8922 * inputs}, {@link OO.ui.RadioInputWidget radio inputs}, and
8923 * {@link OO.ui.ButtonInputWidget button inputs}.
8924 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
8925 *
8926 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
8927 *
8928 * @abstract
8929 * @class
8930 * @extends OO.ui.Widget
8931 * @mixins OO.ui.mixin.TabIndexedElement
8932 * @mixins OO.ui.mixin.TitledElement
8933 * @mixins OO.ui.mixin.AccessKeyedElement
8934 *
8935 * @constructor
8936 * @param {Object} [config] Configuration options
8937 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
8938 * @cfg {string} [value=''] The value of the input.
8939 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
8940 * @cfg {string} [inputId] The value of the input’s HTML `id` attribute.
8941 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the
8942 * value of an input before it is accepted.
8943 */
8944 OO.ui.InputWidget = function OoUiInputWidget( config ) {
8945 // Configuration initialization
8946 config = config || {};
8947
8948 // Parent constructor
8949 OO.ui.InputWidget.parent.call( this, config );
8950
8951 // Properties
8952 // See #reusePreInfuseDOM about config.$input
8953 this.$input = config.$input || this.getInputElement( config );
8954 this.value = '';
8955 this.inputFilter = config.inputFilter;
8956
8957 // Mixin constructors
8958 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {
8959 $tabIndexed: this.$input
8960 }, config ) );
8961 OO.ui.mixin.TitledElement.call( this, $.extend( {
8962 $titled: this.$input
8963 }, config ) );
8964 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {
8965 $accessKeyed: this.$input
8966 }, config ) );
8967
8968 // Events
8969 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
8970
8971 // Initialization
8972 this.$input
8973 .addClass( 'oo-ui-inputWidget-input' )
8974 .attr( 'name', config.name )
8975 .prop( 'disabled', this.isDisabled() );
8976 this.$element
8977 .addClass( 'oo-ui-inputWidget' )
8978 .append( this.$input );
8979 this.setValue( config.value );
8980 if ( config.dir ) {
8981 this.setDir( config.dir );
8982 }
8983 if ( config.inputId !== undefined ) {
8984 this.setInputId( config.inputId );
8985 }
8986 };
8987
8988 /* Setup */
8989
8990 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
8991 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TabIndexedElement );
8992 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TitledElement );
8993 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.AccessKeyedElement );
8994
8995 /* Static Methods */
8996
8997 /**
8998 * @inheritdoc
8999 */
9000 OO.ui.InputWidget.static.reusePreInfuseDOM = function ( node, config ) {
9001 config = OO.ui.InputWidget.parent.static.reusePreInfuseDOM( node, config );
9002 // Reusing `$input` lets browsers preserve inputted values across page reloads, see T114134.
9003 config.$input = $( node ).find( '.oo-ui-inputWidget-input' );
9004 return config;
9005 };
9006
9007 /**
9008 * @inheritdoc
9009 */
9010 OO.ui.InputWidget.static.gatherPreInfuseState = function ( node, config ) {
9011 var state = OO.ui.InputWidget.parent.static.gatherPreInfuseState( node, config );
9012 if ( config.$input && config.$input.length ) {
9013 state.value = config.$input.val();
9014 // Might be better in TabIndexedElement, but it's awkward to do there because
9015 // mixins are awkward
9016 state.focus = config.$input.is( ':focus' );
9017 }
9018 return state;
9019 };
9020
9021 /* Events */
9022
9023 /**
9024 * @event change
9025 *
9026 * A change event is emitted when the value of the input changes.
9027 *
9028 * @param {string} value
9029 */
9030
9031 /* Methods */
9032
9033 /**
9034 * Get input element.
9035 *
9036 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
9037 * different circumstances. The element must have a `value` property (like form elements).
9038 *
9039 * @protected
9040 * @param {Object} config Configuration options
9041 * @return {jQuery} Input element
9042 */
9043 OO.ui.InputWidget.prototype.getInputElement = function () {
9044 return $( '<input>' );
9045 };
9046
9047 /**
9048 * Handle potentially value-changing events.
9049 *
9050 * @private
9051 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
9052 */
9053 OO.ui.InputWidget.prototype.onEdit = function () {
9054 var widget = this;
9055 if ( !this.isDisabled() ) {
9056 // Allow the stack to clear so the value will be updated
9057 setTimeout( function () {
9058 widget.setValue( widget.$input.val() );
9059 } );
9060 }
9061 };
9062
9063 /**
9064 * Get the value of the input.
9065 *
9066 * @return {string} Input value
9067 */
9068 OO.ui.InputWidget.prototype.getValue = function () {
9069 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
9070 // it, and we won't know unless they're kind enough to trigger a 'change' event.
9071 var value = this.$input.val();
9072 if ( this.value !== value ) {
9073 this.setValue( value );
9074 }
9075 return this.value;
9076 };
9077
9078 /**
9079 * Set the directionality of the input.
9080 *
9081 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
9082 * @chainable
9083 * @return {OO.ui.Widget} The widget, for chaining
9084 */
9085 OO.ui.InputWidget.prototype.setDir = function ( dir ) {
9086 this.$input.prop( 'dir', dir );
9087 return this;
9088 };
9089
9090 /**
9091 * Set the value of the input.
9092 *
9093 * @param {string} value New value
9094 * @fires change
9095 * @chainable
9096 * @return {OO.ui.Widget} The widget, for chaining
9097 */
9098 OO.ui.InputWidget.prototype.setValue = function ( value ) {
9099 value = this.cleanUpValue( value );
9100 // Update the DOM if it has changed. Note that with cleanUpValue, it
9101 // is possible for the DOM value to change without this.value changing.
9102 if ( this.$input.val() !== value ) {
9103 this.$input.val( value );
9104 }
9105 if ( this.value !== value ) {
9106 this.value = value;
9107 this.emit( 'change', this.value );
9108 }
9109 // The first time that the value is set (probably while constructing the widget),
9110 // remember it in defaultValue. This property can be later used to check whether
9111 // the value of the input has been changed since it was created.
9112 if ( this.defaultValue === undefined ) {
9113 this.defaultValue = this.value;
9114 this.$input[ 0 ].defaultValue = this.defaultValue;
9115 }
9116 return this;
9117 };
9118
9119 /**
9120 * Clean up incoming value.
9121 *
9122 * Ensures value is a string, and converts undefined and null to empty string.
9123 *
9124 * @private
9125 * @param {string} value Original value
9126 * @return {string} Cleaned up value
9127 */
9128 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
9129 if ( value === undefined || value === null ) {
9130 return '';
9131 } else if ( this.inputFilter ) {
9132 return this.inputFilter( String( value ) );
9133 } else {
9134 return String( value );
9135 }
9136 };
9137
9138 /**
9139 * @inheritdoc
9140 */
9141 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
9142 OO.ui.InputWidget.parent.prototype.setDisabled.call( this, state );
9143 if ( this.$input ) {
9144 this.$input.prop( 'disabled', this.isDisabled() );
9145 }
9146 return this;
9147 };
9148
9149 /**
9150 * Set the 'id' attribute of the `<input>` element.
9151 *
9152 * @param {string} id
9153 * @chainable
9154 * @return {OO.ui.Widget} The widget, for chaining
9155 */
9156 OO.ui.InputWidget.prototype.setInputId = function ( id ) {
9157 this.$input.attr( 'id', id );
9158 return this;
9159 };
9160
9161 /**
9162 * @inheritdoc
9163 */
9164 OO.ui.InputWidget.prototype.restorePreInfuseState = function ( state ) {
9165 OO.ui.InputWidget.parent.prototype.restorePreInfuseState.call( this, state );
9166 if ( state.value !== undefined && state.value !== this.getValue() ) {
9167 this.setValue( state.value );
9168 }
9169 if ( state.focus ) {
9170 this.focus();
9171 }
9172 };
9173
9174 /**
9175 * Data widget intended for creating `<input type="hidden">` inputs.
9176 *
9177 * @class
9178 * @extends OO.ui.Widget
9179 *
9180 * @constructor
9181 * @param {Object} [config] Configuration options
9182 * @cfg {string} [value=''] The value of the input.
9183 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
9184 */
9185 OO.ui.HiddenInputWidget = function OoUiHiddenInputWidget( config ) {
9186 // Configuration initialization
9187 config = $.extend( { value: '', name: '' }, config );
9188
9189 // Parent constructor
9190 OO.ui.HiddenInputWidget.parent.call( this, config );
9191
9192 // Initialization
9193 this.$element.attr( {
9194 type: 'hidden',
9195 value: config.value,
9196 name: config.name
9197 } );
9198 this.$element.removeAttr( 'aria-disabled' );
9199 };
9200
9201 /* Setup */
9202
9203 OO.inheritClass( OO.ui.HiddenInputWidget, OO.ui.Widget );
9204
9205 /* Static Properties */
9206
9207 /**
9208 * @static
9209 * @inheritdoc
9210 */
9211 OO.ui.HiddenInputWidget.static.tagName = 'input';
9212
9213 /**
9214 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
9215 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
9216 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
9217 * HTML `<button>` (the default) or an HTML `<input>` tags. See the
9218 * [OOUI documentation on MediaWiki] [1] for more information.
9219 *
9220 * @example
9221 * // A ButtonInputWidget rendered as an HTML button, the default.
9222 * var button = new OO.ui.ButtonInputWidget( {
9223 * label: 'Input button',
9224 * icon: 'check',
9225 * value: 'check'
9226 * } );
9227 * $( document.body ).append( button.$element );
9228 *
9229 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#Button_inputs
9230 *
9231 * @class
9232 * @extends OO.ui.InputWidget
9233 * @mixins OO.ui.mixin.ButtonElement
9234 * @mixins OO.ui.mixin.IconElement
9235 * @mixins OO.ui.mixin.IndicatorElement
9236 * @mixins OO.ui.mixin.LabelElement
9237 * @mixins OO.ui.mixin.FlaggedElement
9238 *
9239 * @constructor
9240 * @param {Object} [config] Configuration options
9241 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute:
9242 * 'button', 'submit' or 'reset'.
9243 * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
9244 * Widgets configured to be an `<input>` do not support {@link #icon icons} and
9245 * {@link #indicator indicators},
9246 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should
9247 * only be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
9248 */
9249 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
9250 // Configuration initialization
9251 config = $.extend( { type: 'button', useInputTag: false }, config );
9252
9253 // See InputWidget#reusePreInfuseDOM about config.$input
9254 if ( config.$input ) {
9255 config.$input.empty();
9256 }
9257
9258 // Properties (must be set before parent constructor, which calls #setValue)
9259 this.useInputTag = config.useInputTag;
9260
9261 // Parent constructor
9262 OO.ui.ButtonInputWidget.parent.call( this, config );
9263
9264 // Mixin constructors
9265 OO.ui.mixin.ButtonElement.call( this, $.extend( {
9266 $button: this.$input
9267 }, config ) );
9268 OO.ui.mixin.IconElement.call( this, config );
9269 OO.ui.mixin.IndicatorElement.call( this, config );
9270 OO.ui.mixin.LabelElement.call( this, config );
9271 OO.ui.mixin.FlaggedElement.call( this, config );
9272
9273 // Initialization
9274 if ( !config.useInputTag ) {
9275 this.$input.append( this.$icon, this.$label, this.$indicator );
9276 }
9277 this.$element.addClass( 'oo-ui-buttonInputWidget' );
9278 };
9279
9280 /* Setup */
9281
9282 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
9283 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.ButtonElement );
9284 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IconElement );
9285 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IndicatorElement );
9286 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.LabelElement );
9287 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.FlaggedElement );
9288
9289 /* Static Properties */
9290
9291 /**
9292 * @static
9293 * @inheritdoc
9294 */
9295 OO.ui.ButtonInputWidget.static.tagName = 'span';
9296
9297 /* Methods */
9298
9299 /**
9300 * @inheritdoc
9301 * @protected
9302 */
9303 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
9304 var type;
9305 type = [ 'button', 'submit', 'reset' ].indexOf( config.type ) !== -1 ? config.type : 'button';
9306 return $( '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + type + '">' );
9307 };
9308
9309 /**
9310 * Set label value.
9311 *
9312 * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
9313 *
9314 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
9315 * text, or `null` for no label
9316 * @chainable
9317 * @return {OO.ui.Widget} The widget, for chaining
9318 */
9319 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
9320 if ( typeof label === 'function' ) {
9321 label = OO.ui.resolveMsg( label );
9322 }
9323
9324 if ( this.useInputTag ) {
9325 // Discard non-plaintext labels
9326 if ( typeof label !== 'string' ) {
9327 label = '';
9328 }
9329
9330 this.$input.val( label );
9331 }
9332
9333 return OO.ui.mixin.LabelElement.prototype.setLabel.call( this, label );
9334 };
9335
9336 /**
9337 * Set the value of the input.
9338 *
9339 * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
9340 * they do not support {@link #value values}.
9341 *
9342 * @param {string} value New value
9343 * @chainable
9344 * @return {OO.ui.Widget} The widget, for chaining
9345 */
9346 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
9347 if ( !this.useInputTag ) {
9348 OO.ui.ButtonInputWidget.parent.prototype.setValue.call( this, value );
9349 }
9350 return this;
9351 };
9352
9353 /**
9354 * @inheritdoc
9355 */
9356 OO.ui.ButtonInputWidget.prototype.getInputId = function () {
9357 // Disable generating `<label>` elements for buttons. One would very rarely need additional
9358 // label for a button, and it's already a big clickable target, and it causes
9359 // unexpected rendering.
9360 return null;
9361 };
9362
9363 /**
9364 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
9365 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
9366 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
9367 * alignment. For more information, please see the [OOUI documentation on MediaWiki][1].
9368 *
9369 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9370 *
9371 * @example
9372 * // An example of selected, unselected, and disabled checkbox inputs.
9373 * var checkbox1 = new OO.ui.CheckboxInputWidget( {
9374 * value: 'a',
9375 * selected: true
9376 * } ),
9377 * checkbox2 = new OO.ui.CheckboxInputWidget( {
9378 * value: 'b'
9379 * } ),
9380 * checkbox3 = new OO.ui.CheckboxInputWidget( {
9381 * value:'c',
9382 * disabled: true
9383 * } ),
9384 * // Create a fieldset layout with fields for each checkbox.
9385 * fieldset = new OO.ui.FieldsetLayout( {
9386 * label: 'Checkboxes'
9387 * } );
9388 * fieldset.addItems( [
9389 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
9390 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
9391 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
9392 * ] );
9393 * $( document.body ).append( fieldset.$element );
9394 *
9395 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9396 *
9397 * @class
9398 * @extends OO.ui.InputWidget
9399 *
9400 * @constructor
9401 * @param {Object} [config] Configuration options
9402 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is
9403 * not selected.
9404 */
9405 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
9406 // Configuration initialization
9407 config = config || {};
9408
9409 // Parent constructor
9410 OO.ui.CheckboxInputWidget.parent.call( this, config );
9411
9412 // Properties
9413 this.checkIcon = new OO.ui.IconWidget( {
9414 icon: 'check',
9415 classes: [ 'oo-ui-checkboxInputWidget-checkIcon' ]
9416 } );
9417
9418 // Initialization
9419 this.$element
9420 .addClass( 'oo-ui-checkboxInputWidget' )
9421 // Required for pretty styling in WikimediaUI theme
9422 .append( this.checkIcon.$element );
9423 this.setSelected( config.selected !== undefined ? config.selected : false );
9424 };
9425
9426 /* Setup */
9427
9428 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
9429
9430 /* Static Properties */
9431
9432 /**
9433 * @static
9434 * @inheritdoc
9435 */
9436 OO.ui.CheckboxInputWidget.static.tagName = 'span';
9437
9438 /* Static Methods */
9439
9440 /**
9441 * @inheritdoc
9442 */
9443 OO.ui.CheckboxInputWidget.static.gatherPreInfuseState = function ( node, config ) {
9444 var state = OO.ui.CheckboxInputWidget.parent.static.gatherPreInfuseState( node, config );
9445 state.checked = config.$input.prop( 'checked' );
9446 return state;
9447 };
9448
9449 /* Methods */
9450
9451 /**
9452 * @inheritdoc
9453 * @protected
9454 */
9455 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
9456 return $( '<input>' ).attr( 'type', 'checkbox' );
9457 };
9458
9459 /**
9460 * @inheritdoc
9461 */
9462 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
9463 var widget = this;
9464 if ( !this.isDisabled() ) {
9465 // Allow the stack to clear so the value will be updated
9466 setTimeout( function () {
9467 widget.setSelected( widget.$input.prop( 'checked' ) );
9468 } );
9469 }
9470 };
9471
9472 /**
9473 * Set selection state of this checkbox.
9474 *
9475 * @param {boolean} state `true` for selected
9476 * @chainable
9477 * @return {OO.ui.Widget} The widget, for chaining
9478 */
9479 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
9480 state = !!state;
9481 if ( this.selected !== state ) {
9482 this.selected = state;
9483 this.$input.prop( 'checked', this.selected );
9484 this.emit( 'change', this.selected );
9485 }
9486 // The first time that the selection state is set (probably while constructing the widget),
9487 // remember it in defaultSelected. This property can be later used to check whether
9488 // the selection state of the input has been changed since it was created.
9489 if ( this.defaultSelected === undefined ) {
9490 this.defaultSelected = this.selected;
9491 this.$input[ 0 ].defaultChecked = this.defaultSelected;
9492 }
9493 return this;
9494 };
9495
9496 /**
9497 * Check if this checkbox is selected.
9498 *
9499 * @return {boolean} Checkbox is selected
9500 */
9501 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
9502 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
9503 // it, and we won't know unless they're kind enough to trigger a 'change' event.
9504 var selected = this.$input.prop( 'checked' );
9505 if ( this.selected !== selected ) {
9506 this.setSelected( selected );
9507 }
9508 return this.selected;
9509 };
9510
9511 /**
9512 * @inheritdoc
9513 */
9514 OO.ui.CheckboxInputWidget.prototype.simulateLabelClick = function () {
9515 if ( !this.isDisabled() ) {
9516 this.$handle.trigger( 'click' );
9517 }
9518 this.focus();
9519 };
9520
9521 /**
9522 * @inheritdoc
9523 */
9524 OO.ui.CheckboxInputWidget.prototype.restorePreInfuseState = function ( state ) {
9525 OO.ui.CheckboxInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
9526 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
9527 this.setSelected( state.checked );
9528 }
9529 };
9530
9531 /**
9532 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
9533 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the
9534 * value of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9535 * more information about input widgets.
9536 *
9537 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
9538 * are no options. If no `value` configuration option is provided, the first option is selected.
9539 * If you need a state representing no value (no option being selected), use a DropdownWidget.
9540 *
9541 * This and OO.ui.RadioSelectInputWidget support similar configuration options.
9542 *
9543 * @example
9544 * // A DropdownInputWidget with three options.
9545 * var dropdownInput = new OO.ui.DropdownInputWidget( {
9546 * options: [
9547 * { data: 'a', label: 'First' },
9548 * { data: 'b', label: 'Second', disabled: true },
9549 * { optgroup: 'Group label' },
9550 * { data: 'c', label: 'First sub-item)' }
9551 * ]
9552 * } );
9553 * $( document.body ).append( dropdownInput.$element );
9554 *
9555 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9556 *
9557 * @class
9558 * @extends OO.ui.InputWidget
9559 *
9560 * @constructor
9561 * @param {Object} [config] Configuration options
9562 * @cfg {Object[]} [options=[]] Array of menu options in the format described above.
9563 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
9564 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful
9565 * in cases where the expanded menu is larger than its containing `<div>`. The specified overlay
9566 * layer is usually on top of the containing `<div>` and has a larger area. By default, the menu
9567 * uses relative positioning.
9568 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
9569 */
9570 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
9571 // Configuration initialization
9572 config = config || {};
9573
9574 // Properties (must be done before parent constructor which calls #setDisabled)
9575 this.dropdownWidget = new OO.ui.DropdownWidget( $.extend(
9576 {
9577 $overlay: config.$overlay
9578 },
9579 config.dropdown
9580 ) );
9581 // Set up the options before parent constructor, which uses them to validate config.value.
9582 // Use this instead of setOptions() because this.$input is not set up yet.
9583 this.setOptionsData( config.options || [] );
9584
9585 // Parent constructor
9586 OO.ui.DropdownInputWidget.parent.call( this, config );
9587
9588 // Events
9589 this.dropdownWidget.getMenu().connect( this, {
9590 select: 'onMenuSelect'
9591 } );
9592
9593 // Initialization
9594 this.$element
9595 .addClass( 'oo-ui-dropdownInputWidget' )
9596 .append( this.dropdownWidget.$element );
9597 this.setTabIndexedElement( this.dropdownWidget.$tabIndexed );
9598 this.setTitledElement( this.dropdownWidget.$handle );
9599 };
9600
9601 /* Setup */
9602
9603 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
9604
9605 /* Methods */
9606
9607 /**
9608 * @inheritdoc
9609 * @protected
9610 */
9611 OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
9612 return $( '<select>' );
9613 };
9614
9615 /**
9616 * Handles menu select events.
9617 *
9618 * @private
9619 * @param {OO.ui.MenuOptionWidget|null} item Selected menu item
9620 */
9621 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
9622 this.setValue( item ? item.getData() : '' );
9623 };
9624
9625 /**
9626 * @inheritdoc
9627 */
9628 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
9629 var selected;
9630 value = this.cleanUpValue( value );
9631 // Only allow setting values that are actually present in the dropdown
9632 selected = this.dropdownWidget.getMenu().findItemFromData( value ) ||
9633 this.dropdownWidget.getMenu().findFirstSelectableItem();
9634 this.dropdownWidget.getMenu().selectItem( selected );
9635 value = selected ? selected.getData() : '';
9636 OO.ui.DropdownInputWidget.parent.prototype.setValue.call( this, value );
9637 if ( this.optionsDirty ) {
9638 // We reached this from the constructor or from #setOptions.
9639 // We have to update the <select> element.
9640 this.updateOptionsInterface();
9641 }
9642 return this;
9643 };
9644
9645 /**
9646 * @inheritdoc
9647 */
9648 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
9649 this.dropdownWidget.setDisabled( state );
9650 OO.ui.DropdownInputWidget.parent.prototype.setDisabled.call( this, state );
9651 return this;
9652 };
9653
9654 /**
9655 * Set the options available for this input.
9656 *
9657 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9658 * @chainable
9659 * @return {OO.ui.Widget} The widget, for chaining
9660 */
9661 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
9662 var value = this.getValue();
9663
9664 this.setOptionsData( options );
9665
9666 // Re-set the value to update the visible interface (DropdownWidget and <select>).
9667 // In case the previous value is no longer an available option, select the first valid one.
9668 this.setValue( value );
9669
9670 return this;
9671 };
9672
9673 /**
9674 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
9675 *
9676 * This method may be called before the parent constructor, so various properties may not be
9677 * initialized yet.
9678 *
9679 * @param {Object[]} options Array of menu options (see #constructor for details).
9680 * @private
9681 */
9682 OO.ui.DropdownInputWidget.prototype.setOptionsData = function ( options ) {
9683 var optionWidgets, optIndex, opt, previousOptgroup, optionWidget, optValue,
9684 widget = this;
9685
9686 this.optionsDirty = true;
9687
9688 // Go through all the supplied option configs and create either
9689 // MenuSectionOption or MenuOption widgets from each.
9690 optionWidgets = [];
9691 for ( optIndex = 0; optIndex < options.length; optIndex++ ) {
9692 opt = options[ optIndex ];
9693
9694 if ( opt.optgroup !== undefined ) {
9695 // Create a <optgroup> menu item.
9696 optionWidget = widget.createMenuSectionOptionWidget( opt.optgroup );
9697 previousOptgroup = optionWidget;
9698
9699 } else {
9700 // Create a normal <option> menu item.
9701 optValue = widget.cleanUpValue( opt.data );
9702 optionWidget = widget.createMenuOptionWidget(
9703 optValue,
9704 opt.label !== undefined ? opt.label : optValue
9705 );
9706 }
9707
9708 // Disable the menu option if it is itself disabled or if its parent optgroup is disabled.
9709 if (
9710 opt.disabled !== undefined ||
9711 previousOptgroup instanceof OO.ui.MenuSectionOptionWidget &&
9712 previousOptgroup.isDisabled()
9713 ) {
9714 optionWidget.setDisabled( true );
9715 }
9716
9717 optionWidgets.push( optionWidget );
9718 }
9719
9720 this.dropdownWidget.getMenu().clearItems().addItems( optionWidgets );
9721 };
9722
9723 /**
9724 * Create a menu option widget.
9725 *
9726 * @protected
9727 * @param {string} data Item data
9728 * @param {string} label Item label
9729 * @return {OO.ui.MenuOptionWidget} Option widget
9730 */
9731 OO.ui.DropdownInputWidget.prototype.createMenuOptionWidget = function ( data, label ) {
9732 return new OO.ui.MenuOptionWidget( {
9733 data: data,
9734 label: label
9735 } );
9736 };
9737
9738 /**
9739 * Create a menu section option widget.
9740 *
9741 * @protected
9742 * @param {string} label Section item label
9743 * @return {OO.ui.MenuSectionOptionWidget} Menu section option widget
9744 */
9745 OO.ui.DropdownInputWidget.prototype.createMenuSectionOptionWidget = function ( label ) {
9746 return new OO.ui.MenuSectionOptionWidget( {
9747 label: label
9748 } );
9749 };
9750
9751 /**
9752 * Update the user-visible interface to match the internal list of options and value.
9753 *
9754 * This method must only be called after the parent constructor.
9755 *
9756 * @private
9757 */
9758 OO.ui.DropdownInputWidget.prototype.updateOptionsInterface = function () {
9759 var
9760 $optionsContainer = this.$input,
9761 defaultValue = this.defaultValue,
9762 widget = this;
9763
9764 this.$input.empty();
9765
9766 this.dropdownWidget.getMenu().getItems().forEach( function ( optionWidget ) {
9767 var $optionNode;
9768
9769 if ( !( optionWidget instanceof OO.ui.MenuSectionOptionWidget ) ) {
9770 $optionNode = $( '<option>' )
9771 .attr( 'value', optionWidget.getData() )
9772 .text( optionWidget.getLabel() );
9773
9774 // Remember original selection state. This property can be later used to check whether
9775 // the selection state of the input has been changed since it was created.
9776 $optionNode[ 0 ].defaultSelected = ( optionWidget.getData() === defaultValue );
9777
9778 $optionsContainer.append( $optionNode );
9779 } else {
9780 $optionNode = $( '<optgroup>' )
9781 .attr( 'label', optionWidget.getLabel() );
9782 widget.$input.append( $optionNode );
9783 $optionsContainer = $optionNode;
9784 }
9785
9786 // Disable the option or optgroup if required.
9787 if ( optionWidget.isDisabled() ) {
9788 $optionNode.prop( 'disabled', true );
9789 }
9790 } );
9791
9792 this.optionsDirty = false;
9793 };
9794
9795 /**
9796 * @inheritdoc
9797 */
9798 OO.ui.DropdownInputWidget.prototype.focus = function () {
9799 this.dropdownWidget.focus();
9800 return this;
9801 };
9802
9803 /**
9804 * @inheritdoc
9805 */
9806 OO.ui.DropdownInputWidget.prototype.blur = function () {
9807 this.dropdownWidget.blur();
9808 return this;
9809 };
9810
9811 /**
9812 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
9813 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
9814 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
9815 * please see the [OOUI documentation on MediaWiki][1].
9816 *
9817 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9818 *
9819 * @example
9820 * // An example of selected, unselected, and disabled radio inputs
9821 * var radio1 = new OO.ui.RadioInputWidget( {
9822 * value: 'a',
9823 * selected: true
9824 * } );
9825 * var radio2 = new OO.ui.RadioInputWidget( {
9826 * value: 'b'
9827 * } );
9828 * var radio3 = new OO.ui.RadioInputWidget( {
9829 * value: 'c',
9830 * disabled: true
9831 * } );
9832 * // Create a fieldset layout with fields for each radio button.
9833 * var fieldset = new OO.ui.FieldsetLayout( {
9834 * label: 'Radio inputs'
9835 * } );
9836 * fieldset.addItems( [
9837 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
9838 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
9839 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
9840 * ] );
9841 * $( document.body ).append( fieldset.$element );
9842 *
9843 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9844 *
9845 * @class
9846 * @extends OO.ui.InputWidget
9847 *
9848 * @constructor
9849 * @param {Object} [config] Configuration options
9850 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button
9851 * is not selected.
9852 */
9853 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
9854 // Configuration initialization
9855 config = config || {};
9856
9857 // Parent constructor
9858 OO.ui.RadioInputWidget.parent.call( this, config );
9859
9860 // Initialization
9861 this.$element
9862 .addClass( 'oo-ui-radioInputWidget' )
9863 // Required for pretty styling in WikimediaUI theme
9864 .append( $( '<span>' ) );
9865 this.setSelected( config.selected !== undefined ? config.selected : false );
9866 };
9867
9868 /* Setup */
9869
9870 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
9871
9872 /* Static Properties */
9873
9874 /**
9875 * @static
9876 * @inheritdoc
9877 */
9878 OO.ui.RadioInputWidget.static.tagName = 'span';
9879
9880 /* Static Methods */
9881
9882 /**
9883 * @inheritdoc
9884 */
9885 OO.ui.RadioInputWidget.static.gatherPreInfuseState = function ( node, config ) {
9886 var state = OO.ui.RadioInputWidget.parent.static.gatherPreInfuseState( node, config );
9887 state.checked = config.$input.prop( 'checked' );
9888 return state;
9889 };
9890
9891 /* Methods */
9892
9893 /**
9894 * @inheritdoc
9895 * @protected
9896 */
9897 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
9898 return $( '<input>' ).attr( 'type', 'radio' );
9899 };
9900
9901 /**
9902 * @inheritdoc
9903 */
9904 OO.ui.RadioInputWidget.prototype.onEdit = function () {
9905 // RadioInputWidget doesn't track its state.
9906 };
9907
9908 /**
9909 * Set selection state of this radio button.
9910 *
9911 * @param {boolean} state `true` for selected
9912 * @chainable
9913 * @return {OO.ui.Widget} The widget, for chaining
9914 */
9915 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
9916 // RadioInputWidget doesn't track its state.
9917 this.$input.prop( 'checked', state );
9918 // The first time that the selection state is set (probably while constructing the widget),
9919 // remember it in defaultSelected. This property can be later used to check whether
9920 // the selection state of the input has been changed since it was created.
9921 if ( this.defaultSelected === undefined ) {
9922 this.defaultSelected = state;
9923 this.$input[ 0 ].defaultChecked = this.defaultSelected;
9924 }
9925 return this;
9926 };
9927
9928 /**
9929 * Check if this radio button is selected.
9930 *
9931 * @return {boolean} Radio is selected
9932 */
9933 OO.ui.RadioInputWidget.prototype.isSelected = function () {
9934 return this.$input.prop( 'checked' );
9935 };
9936
9937 /**
9938 * @inheritdoc
9939 */
9940 OO.ui.RadioInputWidget.prototype.simulateLabelClick = function () {
9941 if ( !this.isDisabled() ) {
9942 this.$input.trigger( 'click' );
9943 }
9944 this.focus();
9945 };
9946
9947 /**
9948 * @inheritdoc
9949 */
9950 OO.ui.RadioInputWidget.prototype.restorePreInfuseState = function ( state ) {
9951 OO.ui.RadioInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
9952 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
9953 this.setSelected( state.checked );
9954 }
9955 };
9956
9957 /**
9958 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be
9959 * used within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with
9960 * the value of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9961 * more information about input widgets.
9962 *
9963 * This and OO.ui.DropdownInputWidget support similar configuration options.
9964 *
9965 * @example
9966 * // A RadioSelectInputWidget with three options
9967 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
9968 * options: [
9969 * { data: 'a', label: 'First' },
9970 * { data: 'b', label: 'Second'},
9971 * { data: 'c', label: 'Third' }
9972 * ]
9973 * } );
9974 * $( document.body ).append( radioSelectInput.$element );
9975 *
9976 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9977 *
9978 * @class
9979 * @extends OO.ui.InputWidget
9980 *
9981 * @constructor
9982 * @param {Object} [config] Configuration options
9983 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9984 */
9985 OO.ui.RadioSelectInputWidget = function OoUiRadioSelectInputWidget( config ) {
9986 // Configuration initialization
9987 config = config || {};
9988
9989 // Properties (must be done before parent constructor which calls #setDisabled)
9990 this.radioSelectWidget = new OO.ui.RadioSelectWidget();
9991 // Set up the options before parent constructor, which uses them to validate config.value.
9992 // Use this instead of setOptions() because this.$input is not set up yet
9993 this.setOptionsData( config.options || [] );
9994
9995 // Parent constructor
9996 OO.ui.RadioSelectInputWidget.parent.call( this, config );
9997
9998 // Events
9999 this.radioSelectWidget.connect( this, {
10000 select: 'onMenuSelect'
10001 } );
10002
10003 // Initialization
10004 this.$element
10005 .addClass( 'oo-ui-radioSelectInputWidget' )
10006 .append( this.radioSelectWidget.$element );
10007 this.setTabIndexedElement( this.radioSelectWidget.$tabIndexed );
10008 };
10009
10010 /* Setup */
10011
10012 OO.inheritClass( OO.ui.RadioSelectInputWidget, OO.ui.InputWidget );
10013
10014 /* Static Methods */
10015
10016 /**
10017 * @inheritdoc
10018 */
10019 OO.ui.RadioSelectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
10020 var state = OO.ui.RadioSelectInputWidget.parent.static.gatherPreInfuseState( node, config );
10021 state.value = $( node ).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
10022 return state;
10023 };
10024
10025 /**
10026 * @inheritdoc
10027 */
10028 OO.ui.RadioSelectInputWidget.static.reusePreInfuseDOM = function ( node, config ) {
10029 config = OO.ui.RadioSelectInputWidget.parent.static.reusePreInfuseDOM( node, config );
10030 // Cannot reuse the `<input type=radio>` set
10031 delete config.$input;
10032 return config;
10033 };
10034
10035 /* Methods */
10036
10037 /**
10038 * @inheritdoc
10039 * @protected
10040 */
10041 OO.ui.RadioSelectInputWidget.prototype.getInputElement = function () {
10042 // Use this instead of <input type="hidden">, because hidden inputs do not have separate
10043 // 'value' and 'defaultValue' properties, and InputWidget wants to handle 'defaultValue'.
10044 return $( '<input>' ).addClass( 'oo-ui-element-hidden' );
10045 };
10046
10047 /**
10048 * Handles menu select events.
10049 *
10050 * @private
10051 * @param {OO.ui.RadioOptionWidget} item Selected menu item
10052 */
10053 OO.ui.RadioSelectInputWidget.prototype.onMenuSelect = function ( item ) {
10054 this.setValue( item.getData() );
10055 };
10056
10057 /**
10058 * @inheritdoc
10059 */
10060 OO.ui.RadioSelectInputWidget.prototype.setValue = function ( value ) {
10061 var selected;
10062 value = this.cleanUpValue( value );
10063 // Only allow setting values that are actually present in the dropdown
10064 selected = this.radioSelectWidget.findItemFromData( value ) ||
10065 this.radioSelectWidget.findFirstSelectableItem();
10066 this.radioSelectWidget.selectItem( selected );
10067 value = selected ? selected.getData() : '';
10068 OO.ui.RadioSelectInputWidget.parent.prototype.setValue.call( this, value );
10069 return this;
10070 };
10071
10072 /**
10073 * @inheritdoc
10074 */
10075 OO.ui.RadioSelectInputWidget.prototype.setDisabled = function ( state ) {
10076 this.radioSelectWidget.setDisabled( state );
10077 OO.ui.RadioSelectInputWidget.parent.prototype.setDisabled.call( this, state );
10078 return this;
10079 };
10080
10081 /**
10082 * Set the options available for this input.
10083 *
10084 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10085 * @chainable
10086 * @return {OO.ui.Widget} The widget, for chaining
10087 */
10088 OO.ui.RadioSelectInputWidget.prototype.setOptions = function ( options ) {
10089 var value = this.getValue();
10090
10091 this.setOptionsData( options );
10092
10093 // Re-set the value to update the visible interface (RadioSelectWidget).
10094 // In case the previous value is no longer an available option, select the first valid one.
10095 this.setValue( value );
10096
10097 return this;
10098 };
10099
10100 /**
10101 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
10102 *
10103 * This method may be called before the parent constructor, so various properties may not be
10104 * intialized yet.
10105 *
10106 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10107 * @private
10108 */
10109 OO.ui.RadioSelectInputWidget.prototype.setOptionsData = function ( options ) {
10110 var widget = this;
10111
10112 this.radioSelectWidget
10113 .clearItems()
10114 .addItems( options.map( function ( opt ) {
10115 var optValue = widget.cleanUpValue( opt.data );
10116 return new OO.ui.RadioOptionWidget( {
10117 data: optValue,
10118 label: opt.label !== undefined ? opt.label : optValue
10119 } );
10120 } ) );
10121 };
10122
10123 /**
10124 * @inheritdoc
10125 */
10126 OO.ui.RadioSelectInputWidget.prototype.focus = function () {
10127 this.radioSelectWidget.focus();
10128 return this;
10129 };
10130
10131 /**
10132 * @inheritdoc
10133 */
10134 OO.ui.RadioSelectInputWidget.prototype.blur = function () {
10135 this.radioSelectWidget.blur();
10136 return this;
10137 };
10138
10139 /**
10140 * CheckboxMultiselectInputWidget is a
10141 * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
10142 * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
10143 * HTML `<input type=checkbox>` tags. Please see the [OOUI documentation on MediaWiki][1] for
10144 * more information about input widgets.
10145 *
10146 * @example
10147 * // A CheckboxMultiselectInputWidget with three options.
10148 * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
10149 * options: [
10150 * { data: 'a', label: 'First' },
10151 * { data: 'b', label: 'Second' },
10152 * { data: 'c', label: 'Third' }
10153 * ]
10154 * } );
10155 * $( document.body ).append( multiselectInput.$element );
10156 *
10157 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
10158 *
10159 * @class
10160 * @extends OO.ui.InputWidget
10161 *
10162 * @constructor
10163 * @param {Object} [config] Configuration options
10164 * @cfg {Object[]} [options=[]] Array of menu options in the format
10165 * `{ data: …, label: …, disabled: … }`
10166 */
10167 OO.ui.CheckboxMultiselectInputWidget = function OoUiCheckboxMultiselectInputWidget( config ) {
10168 // Configuration initialization
10169 config = config || {};
10170
10171 // Properties (must be done before parent constructor which calls #setDisabled)
10172 this.checkboxMultiselectWidget = new OO.ui.CheckboxMultiselectWidget();
10173 // Must be set before the #setOptionsData call below
10174 this.inputName = config.name;
10175 // Set up the options before parent constructor, which uses them to validate config.value.
10176 // Use this instead of setOptions() because this.$input is not set up yet
10177 this.setOptionsData( config.options || [] );
10178
10179 // Parent constructor
10180 OO.ui.CheckboxMultiselectInputWidget.parent.call( this, config );
10181
10182 // Events
10183 this.checkboxMultiselectWidget.connect( this, {
10184 select: 'onCheckboxesSelect'
10185 } );
10186
10187 // Initialization
10188 this.$element
10189 .addClass( 'oo-ui-checkboxMultiselectInputWidget' )
10190 .append( this.checkboxMultiselectWidget.$element );
10191 // We don't use this.$input, but rather the CheckboxInputWidgets inside each option
10192 this.$input.detach();
10193 };
10194
10195 /* Setup */
10196
10197 OO.inheritClass( OO.ui.CheckboxMultiselectInputWidget, OO.ui.InputWidget );
10198
10199 /* Static Methods */
10200
10201 /**
10202 * @inheritdoc
10203 */
10204 OO.ui.CheckboxMultiselectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
10205 var state = OO.ui.CheckboxMultiselectInputWidget.parent.static.gatherPreInfuseState(
10206 node, config
10207 );
10208 state.value = $( node ).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
10209 .toArray().map( function ( el ) { return el.value; } );
10210 return state;
10211 };
10212
10213 /**
10214 * @inheritdoc
10215 */
10216 OO.ui.CheckboxMultiselectInputWidget.static.reusePreInfuseDOM = function ( node, config ) {
10217 config = OO.ui.CheckboxMultiselectInputWidget.parent.static.reusePreInfuseDOM( node, config );
10218 // Cannot reuse the `<input type=checkbox>` set
10219 delete config.$input;
10220 return config;
10221 };
10222
10223 /* Methods */
10224
10225 /**
10226 * @inheritdoc
10227 * @protected
10228 */
10229 OO.ui.CheckboxMultiselectInputWidget.prototype.getInputElement = function () {
10230 // Actually unused
10231 return $( '<unused>' );
10232 };
10233
10234 /**
10235 * Handles CheckboxMultiselectWidget select events.
10236 *
10237 * @private
10238 */
10239 OO.ui.CheckboxMultiselectInputWidget.prototype.onCheckboxesSelect = function () {
10240 this.setValue( this.checkboxMultiselectWidget.findSelectedItemsData() );
10241 };
10242
10243 /**
10244 * @inheritdoc
10245 */
10246 OO.ui.CheckboxMultiselectInputWidget.prototype.getValue = function () {
10247 var value = this.$element.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
10248 .toArray().map( function ( el ) { return el.value; } );
10249 if ( this.value !== value ) {
10250 this.setValue( value );
10251 }
10252 return this.value;
10253 };
10254
10255 /**
10256 * @inheritdoc
10257 */
10258 OO.ui.CheckboxMultiselectInputWidget.prototype.setValue = function ( value ) {
10259 value = this.cleanUpValue( value );
10260 this.checkboxMultiselectWidget.selectItemsByData( value );
10261 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.setValue.call( this, value );
10262 if ( this.optionsDirty ) {
10263 // We reached this from the constructor or from #setOptions.
10264 // We have to update the <select> element.
10265 this.updateOptionsInterface();
10266 }
10267 return this;
10268 };
10269
10270 /**
10271 * Clean up incoming value.
10272 *
10273 * @param {string[]} value Original value
10274 * @return {string[]} Cleaned up value
10275 */
10276 OO.ui.CheckboxMultiselectInputWidget.prototype.cleanUpValue = function ( value ) {
10277 var i, singleValue,
10278 cleanValue = [];
10279 if ( !Array.isArray( value ) ) {
10280 return cleanValue;
10281 }
10282 for ( i = 0; i < value.length; i++ ) {
10283 singleValue = OO.ui.CheckboxMultiselectInputWidget.parent.prototype.cleanUpValue
10284 .call( this, value[ i ] );
10285 // Remove options that we don't have here
10286 if ( !this.checkboxMultiselectWidget.findItemFromData( singleValue ) ) {
10287 continue;
10288 }
10289 cleanValue.push( singleValue );
10290 }
10291 return cleanValue;
10292 };
10293
10294 /**
10295 * @inheritdoc
10296 */
10297 OO.ui.CheckboxMultiselectInputWidget.prototype.setDisabled = function ( state ) {
10298 this.checkboxMultiselectWidget.setDisabled( state );
10299 OO.ui.CheckboxMultiselectInputWidget.parent.prototype.setDisabled.call( this, state );
10300 return this;
10301 };
10302
10303 /**
10304 * Set the options available for this input.
10305 *
10306 * @param {Object[]} options Array of menu options in the format
10307 * `{ data: …, label: …, disabled: … }`
10308 * @chainable
10309 * @return {OO.ui.Widget} The widget, for chaining
10310 */
10311 OO.ui.CheckboxMultiselectInputWidget.prototype.setOptions = function ( options ) {
10312 var value = this.getValue();
10313
10314 this.setOptionsData( options );
10315
10316 // Re-set the value to update the visible interface (CheckboxMultiselectWidget).
10317 // This will also get rid of any stale options that we just removed.
10318 this.setValue( value );
10319
10320 return this;
10321 };
10322
10323 /**
10324 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
10325 *
10326 * This method may be called before the parent constructor, so various properties may not be
10327 * intialized yet.
10328 *
10329 * @param {Object[]} options Array of menu options in the format
10330 * `{ data: …, label: … }`
10331 * @private
10332 */
10333 OO.ui.CheckboxMultiselectInputWidget.prototype.setOptionsData = function ( options ) {
10334 var widget = this;
10335
10336 this.optionsDirty = true;
10337
10338 this.checkboxMultiselectWidget
10339 .clearItems()
10340 .addItems( options.map( function ( opt ) {
10341 var optValue, item, optDisabled;
10342 optValue = OO.ui.CheckboxMultiselectInputWidget.parent.prototype.cleanUpValue
10343 .call( widget, opt.data );
10344 optDisabled = opt.disabled !== undefined ? opt.disabled : false;
10345 item = new OO.ui.CheckboxMultioptionWidget( {
10346 data: optValue,
10347 label: opt.label !== undefined ? opt.label : optValue,
10348 disabled: optDisabled
10349 } );
10350 // Set the 'name' and 'value' for form submission
10351 item.checkbox.$input.attr( 'name', widget.inputName );
10352 item.checkbox.setValue( optValue );
10353 return item;
10354 } ) );
10355 };
10356
10357 /**
10358 * Update the user-visible interface to match the internal list of options and value.
10359 *
10360 * This method must only be called after the parent constructor.
10361 *
10362 * @private
10363 */
10364 OO.ui.CheckboxMultiselectInputWidget.prototype.updateOptionsInterface = function () {
10365 var defaultValue = this.defaultValue;
10366
10367 this.checkboxMultiselectWidget.getItems().forEach( function ( item ) {
10368 // Remember original selection state. This property can be later used to check whether
10369 // the selection state of the input has been changed since it was created.
10370 var isDefault = defaultValue.indexOf( item.getData() ) !== -1;
10371 item.checkbox.defaultSelected = isDefault;
10372 item.checkbox.$input[ 0 ].defaultChecked = isDefault;
10373 } );
10374
10375 this.optionsDirty = false;
10376 };
10377
10378 /**
10379 * @inheritdoc
10380 */
10381 OO.ui.CheckboxMultiselectInputWidget.prototype.focus = function () {
10382 this.checkboxMultiselectWidget.focus();
10383 return this;
10384 };
10385
10386 /**
10387 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
10388 * size of the field as well as its presentation. In addition, these widgets can be configured
10389 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an
10390 * optional validation-pattern (used to determine if an input value is valid or not) and an input
10391 * filter, which modifies incoming values rather than validating them.
10392 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
10393 *
10394 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
10395 *
10396 * @example
10397 * // A TextInputWidget.
10398 * var textInput = new OO.ui.TextInputWidget( {
10399 * value: 'Text input'
10400 * } )
10401 * $( document.body ).append( textInput.$element );
10402 *
10403 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
10404 *
10405 * @class
10406 * @extends OO.ui.InputWidget
10407 * @mixins OO.ui.mixin.IconElement
10408 * @mixins OO.ui.mixin.IndicatorElement
10409 * @mixins OO.ui.mixin.PendingElement
10410 * @mixins OO.ui.mixin.LabelElement
10411 * @mixins OO.ui.mixin.FlaggedElement
10412 *
10413 * @constructor
10414 * @param {Object} [config] Configuration options
10415 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password'
10416 * 'email', 'url' or 'number'.
10417 * @cfg {string} [placeholder] Placeholder text
10418 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
10419 * instruct the browser to focus this widget.
10420 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
10421 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
10422 *
10423 * For unfortunate historical reasons, this counts the number of UTF-16 code units rather than
10424 * Unicode codepoints, which means that codepoints outside the Basic Multilingual Plane (e.g.
10425 * many emojis) count as 2 characters each.
10426 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
10427 * the value or placeholder text: `'before'` or `'after'`
10428 * @cfg {boolean} [required=false] Mark the field as required with `true`. Implies `indicator:
10429 * 'required'`. Note that `false` & setting `indicator: 'required' will result in no indicator
10430 * shown.
10431 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
10432 * @cfg {boolean} [spellcheck] Should the browser support spellcheck for this field (`undefined`
10433 * means leaving it up to the browser).
10434 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
10435 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
10436 * (the value must contain only numbers); when RegExp, a regular expression that must match the
10437 * value for it to be considered valid; when Function, a function receiving the value as parameter
10438 * that must return true, or promise resolving to true, for it to be considered valid.
10439 */
10440 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
10441 // Configuration initialization
10442 config = $.extend( {
10443 type: 'text',
10444 labelPosition: 'after'
10445 }, config );
10446
10447 // Parent constructor
10448 OO.ui.TextInputWidget.parent.call( this, config );
10449
10450 // Mixin constructors
10451 OO.ui.mixin.IconElement.call( this, config );
10452 OO.ui.mixin.IndicatorElement.call( this, config );
10453 OO.ui.mixin.PendingElement.call( this, $.extend( { $pending: this.$input }, config ) );
10454 OO.ui.mixin.LabelElement.call( this, config );
10455 OO.ui.mixin.FlaggedElement.call( this, config );
10456
10457 // Properties
10458 this.type = this.getSaneType( config );
10459 this.readOnly = false;
10460 this.required = false;
10461 this.validate = null;
10462 this.scrollWidth = null;
10463
10464 this.setValidation( config.validate );
10465 this.setLabelPosition( config.labelPosition );
10466
10467 // Events
10468 this.$input.on( {
10469 keypress: this.onKeyPress.bind( this ),
10470 blur: this.onBlur.bind( this ),
10471 focus: this.onFocus.bind( this )
10472 } );
10473 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
10474 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
10475 this.on( 'labelChange', this.updatePosition.bind( this ) );
10476 this.on( 'change', OO.ui.debounce( this.onDebouncedChange.bind( this ), 250 ) );
10477
10478 // Initialization
10479 this.$element
10480 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type )
10481 .append( this.$icon, this.$indicator );
10482 this.setReadOnly( !!config.readOnly );
10483 this.setRequired( !!config.required );
10484 if ( config.placeholder !== undefined ) {
10485 this.$input.attr( 'placeholder', config.placeholder );
10486 }
10487 if ( config.maxLength !== undefined ) {
10488 this.$input.attr( 'maxlength', config.maxLength );
10489 }
10490 if ( config.autofocus ) {
10491 this.$input.attr( 'autofocus', 'autofocus' );
10492 }
10493 if ( config.autocomplete === false ) {
10494 this.$input.attr( 'autocomplete', 'off' );
10495 // Turning off autocompletion also disables "form caching" when the user navigates to a
10496 // different page and then clicks "Back". Re-enable it when leaving.
10497 // Borrowed from jQuery UI.
10498 $( window ).on( {
10499 beforeunload: function () {
10500 this.$input.removeAttr( 'autocomplete' );
10501 }.bind( this ),
10502 pageshow: function () {
10503 // Browsers don't seem to actually fire this event on "Back", they instead just
10504 // reload the whole page... it shouldn't hurt, though.
10505 this.$input.attr( 'autocomplete', 'off' );
10506 }.bind( this )
10507 } );
10508 }
10509 if ( config.spellcheck !== undefined ) {
10510 this.$input.attr( 'spellcheck', config.spellcheck ? 'true' : 'false' );
10511 }
10512 if ( this.label ) {
10513 this.isWaitingToBeAttached = true;
10514 this.installParentChangeDetector();
10515 }
10516 };
10517
10518 /* Setup */
10519
10520 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
10521 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IconElement );
10522 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IndicatorElement );
10523 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.PendingElement );
10524 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.LabelElement );
10525 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.FlaggedElement );
10526
10527 /* Static Properties */
10528
10529 OO.ui.TextInputWidget.static.validationPatterns = {
10530 'non-empty': /.+/,
10531 integer: /^\d+$/
10532 };
10533
10534 /* Events */
10535
10536 /**
10537 * An `enter` event is emitted when the user presses Enter key inside the text box.
10538 *
10539 * @event enter
10540 */
10541
10542 /* Methods */
10543
10544 /**
10545 * Handle icon mouse down events.
10546 *
10547 * @private
10548 * @param {jQuery.Event} e Mouse down event
10549 * @return {undefined/boolean} False to prevent default if event is handled
10550 */
10551 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
10552 if ( e.which === OO.ui.MouseButtons.LEFT ) {
10553 this.focus();
10554 return false;
10555 }
10556 };
10557
10558 /**
10559 * Handle indicator mouse down events.
10560 *
10561 * @private
10562 * @param {jQuery.Event} e Mouse down event
10563 * @return {undefined/boolean} False to prevent default if event is handled
10564 */
10565 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
10566 if ( e.which === OO.ui.MouseButtons.LEFT ) {
10567 this.focus();
10568 return false;
10569 }
10570 };
10571
10572 /**
10573 * Handle key press events.
10574 *
10575 * @private
10576 * @param {jQuery.Event} e Key press event
10577 * @fires enter If Enter key is pressed
10578 */
10579 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
10580 if ( e.which === OO.ui.Keys.ENTER ) {
10581 this.emit( 'enter', e );
10582 }
10583 };
10584
10585 /**
10586 * Handle blur events.
10587 *
10588 * @private
10589 * @param {jQuery.Event} e Blur event
10590 */
10591 OO.ui.TextInputWidget.prototype.onBlur = function () {
10592 this.setValidityFlag();
10593 };
10594
10595 /**
10596 * Handle focus events.
10597 *
10598 * @private
10599 * @param {jQuery.Event} e Focus event
10600 */
10601 OO.ui.TextInputWidget.prototype.onFocus = function () {
10602 if ( this.isWaitingToBeAttached ) {
10603 // If we've received focus, then we must be attached to the document, and if
10604 // isWaitingToBeAttached is still true, that means the handler never fired. Fire it now.
10605 this.onElementAttach();
10606 }
10607 this.setValidityFlag( true );
10608 };
10609
10610 /**
10611 * Handle element attach events.
10612 *
10613 * @private
10614 * @param {jQuery.Event} e Element attach event
10615 */
10616 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
10617 this.isWaitingToBeAttached = false;
10618 // Any previously calculated size is now probably invalid if we reattached elsewhere
10619 this.valCache = null;
10620 this.positionLabel();
10621 };
10622
10623 /**
10624 * Handle debounced change events.
10625 *
10626 * @param {string} value
10627 * @private
10628 */
10629 OO.ui.TextInputWidget.prototype.onDebouncedChange = function () {
10630 this.setValidityFlag();
10631 };
10632
10633 /**
10634 * Check if the input is {@link #readOnly read-only}.
10635 *
10636 * @return {boolean}
10637 */
10638 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
10639 return this.readOnly;
10640 };
10641
10642 /**
10643 * Set the {@link #readOnly read-only} state of the input.
10644 *
10645 * @param {boolean} state Make input read-only
10646 * @chainable
10647 * @return {OO.ui.Widget} The widget, for chaining
10648 */
10649 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
10650 this.readOnly = !!state;
10651 this.$input.prop( 'readOnly', this.readOnly );
10652 return this;
10653 };
10654
10655 /**
10656 * Check if the input is {@link #required required}.
10657 *
10658 * @return {boolean}
10659 */
10660 OO.ui.TextInputWidget.prototype.isRequired = function () {
10661 return this.required;
10662 };
10663
10664 /**
10665 * Set the {@link #required required} state of the input.
10666 *
10667 * @param {boolean} state Make input required
10668 * @chainable
10669 * @return {OO.ui.Widget} The widget, for chaining
10670 */
10671 OO.ui.TextInputWidget.prototype.setRequired = function ( state ) {
10672 this.required = !!state;
10673 if ( this.required ) {
10674 this.$input
10675 .prop( 'required', true )
10676 .attr( 'aria-required', 'true' );
10677 if ( this.getIndicator() === null ) {
10678 this.setIndicator( 'required' );
10679 }
10680 } else {
10681 this.$input
10682 .prop( 'required', false )
10683 .removeAttr( 'aria-required' );
10684 if ( this.getIndicator() === 'required' ) {
10685 this.setIndicator( null );
10686 }
10687 }
10688 return this;
10689 };
10690
10691 /**
10692 * Support function for making #onElementAttach work across browsers.
10693 *
10694 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
10695 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
10696 *
10697 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
10698 * first time that the element gets attached to the documented.
10699 */
10700 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
10701 var mutationObserver, onRemove, topmostNode, fakeParentNode,
10702 MutationObserver = window.MutationObserver ||
10703 window.WebKitMutationObserver ||
10704 window.MozMutationObserver,
10705 widget = this;
10706
10707 if ( MutationObserver ) {
10708 // The new way. If only it wasn't so ugly.
10709
10710 if ( this.isElementAttached() ) {
10711 // Widget is attached already, do nothing. This breaks the functionality of this
10712 // function when the widget is detached and reattached. Alas, doing this correctly with
10713 // MutationObserver would require observation of the whole document, which would hurt
10714 // performance of other, more important code.
10715 return;
10716 }
10717
10718 // Find topmost node in the tree
10719 topmostNode = this.$element[ 0 ];
10720 while ( topmostNode.parentNode ) {
10721 topmostNode = topmostNode.parentNode;
10722 }
10723
10724 // We have no way to detect the $element being attached somewhere without observing the
10725 // entire DOM with subtree modifications, which would hurt performance. So we cheat: we hook
10726 // to the parent node of $element, and instead detect when $element is removed from it (and
10727 // thus probably attached somewhere else). If there is no parent, we create a "fake" one. If
10728 // it doesn't get attached, we end up back here and create the parent.
10729 mutationObserver = new MutationObserver( function ( mutations ) {
10730 var i, j, removedNodes;
10731 for ( i = 0; i < mutations.length; i++ ) {
10732 removedNodes = mutations[ i ].removedNodes;
10733 for ( j = 0; j < removedNodes.length; j++ ) {
10734 if ( removedNodes[ j ] === topmostNode ) {
10735 setTimeout( onRemove, 0 );
10736 return;
10737 }
10738 }
10739 }
10740 } );
10741
10742 onRemove = function () {
10743 // If the node was attached somewhere else, report it
10744 if ( widget.isElementAttached() ) {
10745 widget.onElementAttach();
10746 }
10747 mutationObserver.disconnect();
10748 widget.installParentChangeDetector();
10749 };
10750
10751 // Create a fake parent and observe it
10752 fakeParentNode = $( '<div>' ).append( topmostNode )[ 0 ];
10753 mutationObserver.observe( fakeParentNode, { childList: true } );
10754 } else {
10755 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
10756 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
10757 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
10758 }
10759 };
10760
10761 /**
10762 * @inheritdoc
10763 * @protected
10764 */
10765 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
10766 if ( this.getSaneType( config ) === 'number' ) {
10767 return $( '<input>' )
10768 .attr( 'step', 'any' )
10769 .attr( 'type', 'number' );
10770 } else {
10771 return $( '<input>' ).attr( 'type', this.getSaneType( config ) );
10772 }
10773 };
10774
10775 /**
10776 * Get sanitized value for 'type' for given config.
10777 *
10778 * @param {Object} config Configuration options
10779 * @return {string|null}
10780 * @protected
10781 */
10782 OO.ui.TextInputWidget.prototype.getSaneType = function ( config ) {
10783 var allowedTypes = [
10784 'text',
10785 'password',
10786 'email',
10787 'url',
10788 'number'
10789 ];
10790 return allowedTypes.indexOf( config.type ) !== -1 ? config.type : 'text';
10791 };
10792
10793 /**
10794 * Focus the input and select a specified range within the text.
10795 *
10796 * @param {number} from Select from offset
10797 * @param {number} [to] Select to offset, defaults to from
10798 * @chainable
10799 * @return {OO.ui.Widget} The widget, for chaining
10800 */
10801 OO.ui.TextInputWidget.prototype.selectRange = function ( from, to ) {
10802 var isBackwards, start, end,
10803 input = this.$input[ 0 ];
10804
10805 to = to || from;
10806
10807 isBackwards = to < from;
10808 start = isBackwards ? to : from;
10809 end = isBackwards ? from : to;
10810
10811 this.focus();
10812
10813 try {
10814 input.setSelectionRange( start, end, isBackwards ? 'backward' : 'forward' );
10815 } catch ( e ) {
10816 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
10817 // Rather than expensively check if the input is attached every time, just check
10818 // if it was the cause of an error being thrown. If not, rethrow the error.
10819 if ( this.getElementDocument().body.contains( input ) ) {
10820 throw e;
10821 }
10822 }
10823 return this;
10824 };
10825
10826 /**
10827 * Get an object describing the current selection range in a directional manner
10828 *
10829 * @return {Object} Object containing 'from' and 'to' offsets
10830 */
10831 OO.ui.TextInputWidget.prototype.getRange = function () {
10832 var input = this.$input[ 0 ],
10833 start = input.selectionStart,
10834 end = input.selectionEnd,
10835 isBackwards = input.selectionDirection === 'backward';
10836
10837 return {
10838 from: isBackwards ? end : start,
10839 to: isBackwards ? start : end
10840 };
10841 };
10842
10843 /**
10844 * Get the length of the text input value.
10845 *
10846 * This could differ from the length of #getValue if the
10847 * value gets filtered
10848 *
10849 * @return {number} Input length
10850 */
10851 OO.ui.TextInputWidget.prototype.getInputLength = function () {
10852 return this.$input[ 0 ].value.length;
10853 };
10854
10855 /**
10856 * Focus the input and select the entire text.
10857 *
10858 * @chainable
10859 * @return {OO.ui.Widget} The widget, for chaining
10860 */
10861 OO.ui.TextInputWidget.prototype.select = function () {
10862 return this.selectRange( 0, this.getInputLength() );
10863 };
10864
10865 /**
10866 * Focus the input and move the cursor to the start.
10867 *
10868 * @chainable
10869 * @return {OO.ui.Widget} The widget, for chaining
10870 */
10871 OO.ui.TextInputWidget.prototype.moveCursorToStart = function () {
10872 return this.selectRange( 0 );
10873 };
10874
10875 /**
10876 * Focus the input and move the cursor to the end.
10877 *
10878 * @chainable
10879 * @return {OO.ui.Widget} The widget, for chaining
10880 */
10881 OO.ui.TextInputWidget.prototype.moveCursorToEnd = function () {
10882 return this.selectRange( this.getInputLength() );
10883 };
10884
10885 /**
10886 * Insert new content into the input.
10887 *
10888 * @param {string} content Content to be inserted
10889 * @chainable
10890 * @return {OO.ui.Widget} The widget, for chaining
10891 */
10892 OO.ui.TextInputWidget.prototype.insertContent = function ( content ) {
10893 var start, end,
10894 range = this.getRange(),
10895 value = this.getValue();
10896
10897 start = Math.min( range.from, range.to );
10898 end = Math.max( range.from, range.to );
10899
10900 this.setValue( value.slice( 0, start ) + content + value.slice( end ) );
10901 this.selectRange( start + content.length );
10902 return this;
10903 };
10904
10905 /**
10906 * Insert new content either side of a selection.
10907 *
10908 * @param {string} pre Content to be inserted before the selection
10909 * @param {string} post Content to be inserted after the selection
10910 * @chainable
10911 * @return {OO.ui.Widget} The widget, for chaining
10912 */
10913 OO.ui.TextInputWidget.prototype.encapsulateContent = function ( pre, post ) {
10914 var start, end,
10915 range = this.getRange(),
10916 offset = pre.length;
10917
10918 start = Math.min( range.from, range.to );
10919 end = Math.max( range.from, range.to );
10920
10921 this.selectRange( start ).insertContent( pre );
10922 this.selectRange( offset + end ).insertContent( post );
10923
10924 this.selectRange( offset + start, offset + end );
10925 return this;
10926 };
10927
10928 /**
10929 * Set the validation pattern.
10930 *
10931 * The validation pattern is either a regular expression, a function, or the symbolic name of a
10932 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
10933 * value must contain only numbers).
10934 *
10935 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
10936 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
10937 */
10938 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
10939 if ( validate instanceof RegExp || validate instanceof Function ) {
10940 this.validate = validate;
10941 } else {
10942 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
10943 }
10944 };
10945
10946 /**
10947 * Sets the 'invalid' flag appropriately.
10948 *
10949 * @param {boolean} [isValid] Optionally override validation result
10950 */
10951 OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) {
10952 var widget = this,
10953 setFlag = function ( valid ) {
10954 if ( !valid ) {
10955 widget.$input.attr( 'aria-invalid', 'true' );
10956 } else {
10957 widget.$input.removeAttr( 'aria-invalid' );
10958 }
10959 widget.setFlags( { invalid: !valid } );
10960 };
10961
10962 if ( isValid !== undefined ) {
10963 setFlag( isValid );
10964 } else {
10965 this.getValidity().then( function () {
10966 setFlag( true );
10967 }, function () {
10968 setFlag( false );
10969 } );
10970 }
10971 };
10972
10973 /**
10974 * Get the validity of current value.
10975 *
10976 * This method returns a promise that resolves if the value is valid and rejects if
10977 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
10978 *
10979 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
10980 */
10981 OO.ui.TextInputWidget.prototype.getValidity = function () {
10982 var result;
10983
10984 function rejectOrResolve( valid ) {
10985 if ( valid ) {
10986 return $.Deferred().resolve().promise();
10987 } else {
10988 return $.Deferred().reject().promise();
10989 }
10990 }
10991
10992 // Check browser validity and reject if it is invalid
10993 if (
10994 this.$input[ 0 ].checkValidity !== undefined &&
10995 this.$input[ 0 ].checkValidity() === false
10996 ) {
10997 return rejectOrResolve( false );
10998 }
10999
11000 // Run our checks if the browser thinks the field is valid
11001 if ( this.validate instanceof Function ) {
11002 result = this.validate( this.getValue() );
11003 if ( result && typeof result.promise === 'function' ) {
11004 return result.promise().then( function ( valid ) {
11005 return rejectOrResolve( valid );
11006 } );
11007 } else {
11008 return rejectOrResolve( result );
11009 }
11010 } else {
11011 return rejectOrResolve( this.getValue().match( this.validate ) );
11012 }
11013 };
11014
11015 /**
11016 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
11017 *
11018 * @param {string} labelPosition Label position, 'before' or 'after'
11019 * @chainable
11020 * @return {OO.ui.Widget} The widget, for chaining
11021 */
11022 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
11023 this.labelPosition = labelPosition;
11024 if ( this.label ) {
11025 // If there is no label and we only change the position, #updatePosition is a no-op,
11026 // but it takes really a lot of work to do nothing.
11027 this.updatePosition();
11028 }
11029 return this;
11030 };
11031
11032 /**
11033 * Update the position of the inline label.
11034 *
11035 * This method is called by #setLabelPosition, and can also be called on its own if
11036 * something causes the label to be mispositioned.
11037 *
11038 * @chainable
11039 * @return {OO.ui.Widget} The widget, for chaining
11040 */
11041 OO.ui.TextInputWidget.prototype.updatePosition = function () {
11042 var after = this.labelPosition === 'after';
11043
11044 this.$element
11045 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
11046 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
11047
11048 this.valCache = null;
11049 this.scrollWidth = null;
11050 this.positionLabel();
11051
11052 return this;
11053 };
11054
11055 /**
11056 * Position the label by setting the correct padding on the input.
11057 *
11058 * @private
11059 * @chainable
11060 * @return {OO.ui.Widget} The widget, for chaining
11061 */
11062 OO.ui.TextInputWidget.prototype.positionLabel = function () {
11063 var after, rtl, property, newCss;
11064
11065 if ( this.isWaitingToBeAttached ) {
11066 // #onElementAttach will be called soon, which calls this method
11067 return this;
11068 }
11069
11070 newCss = {
11071 'padding-right': '',
11072 'padding-left': ''
11073 };
11074
11075 if ( this.label ) {
11076 this.$element.append( this.$label );
11077 } else {
11078 this.$label.detach();
11079 // Clear old values if present
11080 this.$input.css( newCss );
11081 return;
11082 }
11083
11084 after = this.labelPosition === 'after';
11085 rtl = this.$element.css( 'direction' ) === 'rtl';
11086 property = after === rtl ? 'padding-left' : 'padding-right';
11087
11088 newCss[ property ] = this.$label.outerWidth( true ) + ( after ? this.scrollWidth : 0 );
11089 // We have to clear the padding on the other side, in case the element direction changed
11090 this.$input.css( newCss );
11091
11092 return this;
11093 };
11094
11095 /**
11096 * SearchInputWidgets are TextInputWidgets with `type="search"` assigned and feature a
11097 * {@link OO.ui.mixin.IconElement search icon} by default.
11098 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
11099 *
11100 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#SearchInputWidget
11101 *
11102 * @class
11103 * @extends OO.ui.TextInputWidget
11104 *
11105 * @constructor
11106 * @param {Object} [config] Configuration options
11107 */
11108 OO.ui.SearchInputWidget = function OoUiSearchInputWidget( config ) {
11109 config = $.extend( {
11110 icon: 'search'
11111 }, config );
11112
11113 // Parent constructor
11114 OO.ui.SearchInputWidget.parent.call( this, config );
11115
11116 // Events
11117 this.connect( this, {
11118 change: 'onChange'
11119 } );
11120
11121 // Initialization
11122 this.updateSearchIndicator();
11123 this.connect( this, {
11124 disable: 'onDisable'
11125 } );
11126 };
11127
11128 /* Setup */
11129
11130 OO.inheritClass( OO.ui.SearchInputWidget, OO.ui.TextInputWidget );
11131
11132 /* Methods */
11133
11134 /**
11135 * @inheritdoc
11136 * @protected
11137 */
11138 OO.ui.SearchInputWidget.prototype.getSaneType = function () {
11139 return 'search';
11140 };
11141
11142 /**
11143 * @inheritdoc
11144 */
11145 OO.ui.SearchInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
11146 if ( e.which === OO.ui.MouseButtons.LEFT ) {
11147 // Clear the text field
11148 this.setValue( '' );
11149 this.focus();
11150 return false;
11151 }
11152 };
11153
11154 /**
11155 * Update the 'clear' indicator displayed on type: 'search' text
11156 * fields, hiding it when the field is already empty or when it's not
11157 * editable.
11158 */
11159 OO.ui.SearchInputWidget.prototype.updateSearchIndicator = function () {
11160 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
11161 this.setIndicator( null );
11162 } else {
11163 this.setIndicator( 'clear' );
11164 }
11165 };
11166
11167 /**
11168 * Handle change events.
11169 *
11170 * @private
11171 */
11172 OO.ui.SearchInputWidget.prototype.onChange = function () {
11173 this.updateSearchIndicator();
11174 };
11175
11176 /**
11177 * Handle disable events.
11178 *
11179 * @param {boolean} disabled Element is disabled
11180 * @private
11181 */
11182 OO.ui.SearchInputWidget.prototype.onDisable = function () {
11183 this.updateSearchIndicator();
11184 };
11185
11186 /**
11187 * @inheritdoc
11188 */
11189 OO.ui.SearchInputWidget.prototype.setReadOnly = function ( state ) {
11190 OO.ui.SearchInputWidget.parent.prototype.setReadOnly.call( this, state );
11191 this.updateSearchIndicator();
11192 return this;
11193 };
11194
11195 /**
11196 * MultilineTextInputWidgets, like HTML textareas, are featuring customization options to
11197 * configure number of rows visible. In addition, these widgets can be autosized to fit user
11198 * inputs and can show {@link OO.ui.mixin.IconElement icons} and
11199 * {@link OO.ui.mixin.IndicatorElement indicators}.
11200 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
11201 *
11202 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
11203 *
11204 * @example
11205 * // A MultilineTextInputWidget.
11206 * var multilineTextInput = new OO.ui.MultilineTextInputWidget( {
11207 * value: 'Text input on multiple lines'
11208 * } )
11209 * $( 'body' ).append( multilineTextInput.$element );
11210 *
11211 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#MultilineTextInputWidget
11212 *
11213 * @class
11214 * @extends OO.ui.TextInputWidget
11215 *
11216 * @constructor
11217 * @param {Object} [config] Configuration options
11218 * @cfg {number} [rows] Number of visible lines in textarea. If used with `autosize`,
11219 * specifies minimum number of rows to display.
11220 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
11221 * Use the #maxRows config to specify a maximum number of displayed rows.
11222 * @cfg {number} [maxRows] Maximum number of rows to display when #autosize is set to true.
11223 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
11224 */
11225 OO.ui.MultilineTextInputWidget = function OoUiMultilineTextInputWidget( config ) {
11226 config = $.extend( {
11227 type: 'text'
11228 }, config );
11229 // Parent constructor
11230 OO.ui.MultilineTextInputWidget.parent.call( this, config );
11231
11232 // Properties
11233 this.autosize = !!config.autosize;
11234 this.styleHeight = null;
11235 this.minRows = config.rows !== undefined ? config.rows : '';
11236 this.maxRows = config.maxRows || Math.max( 2 * ( this.minRows || 0 ), 10 );
11237
11238 // Clone for resizing
11239 if ( this.autosize ) {
11240 this.$clone = this.$input
11241 .clone()
11242 .removeAttr( 'id' )
11243 .removeAttr( 'name' )
11244 .insertAfter( this.$input )
11245 .attr( 'aria-hidden', 'true' )
11246 .addClass( 'oo-ui-element-hidden' );
11247 }
11248
11249 // Events
11250 this.connect( this, {
11251 change: 'onChange'
11252 } );
11253
11254 // Initialization
11255 if ( config.rows ) {
11256 this.$input.attr( 'rows', config.rows );
11257 }
11258 if ( this.autosize ) {
11259 this.$input.addClass( 'oo-ui-textInputWidget-autosized' );
11260 this.isWaitingToBeAttached = true;
11261 this.installParentChangeDetector();
11262 }
11263 };
11264
11265 /* Setup */
11266
11267 OO.inheritClass( OO.ui.MultilineTextInputWidget, OO.ui.TextInputWidget );
11268
11269 /* Static Methods */
11270
11271 /**
11272 * @inheritdoc
11273 */
11274 OO.ui.MultilineTextInputWidget.static.gatherPreInfuseState = function ( node, config ) {
11275 var state = OO.ui.MultilineTextInputWidget.parent.static.gatherPreInfuseState( node, config );
11276 state.scrollTop = config.$input.scrollTop();
11277 return state;
11278 };
11279
11280 /* Methods */
11281
11282 /**
11283 * @inheritdoc
11284 */
11285 OO.ui.MultilineTextInputWidget.prototype.onElementAttach = function () {
11286 OO.ui.MultilineTextInputWidget.parent.prototype.onElementAttach.call( this );
11287 this.adjustSize();
11288 };
11289
11290 /**
11291 * Handle change events.
11292 *
11293 * @private
11294 */
11295 OO.ui.MultilineTextInputWidget.prototype.onChange = function () {
11296 this.adjustSize();
11297 };
11298
11299 /**
11300 * @inheritdoc
11301 */
11302 OO.ui.MultilineTextInputWidget.prototype.updatePosition = function () {
11303 OO.ui.MultilineTextInputWidget.parent.prototype.updatePosition.call( this );
11304 this.adjustSize();
11305 };
11306
11307 /**
11308 * @inheritdoc
11309 *
11310 * Modify to emit 'enter' on Ctrl/Meta+Enter, instead of plain Enter
11311 */
11312 OO.ui.MultilineTextInputWidget.prototype.onKeyPress = function ( e ) {
11313 if (
11314 ( e.which === OO.ui.Keys.ENTER && ( e.ctrlKey || e.metaKey ) ) ||
11315 // Some platforms emit keycode 10 for Control+Enter keypress in a textarea
11316 e.which === 10
11317 ) {
11318 this.emit( 'enter', e );
11319 }
11320 };
11321
11322 /**
11323 * Automatically adjust the size of the text input.
11324 *
11325 * This only affects multiline inputs that are {@link #autosize autosized}.
11326 *
11327 * @chainable
11328 * @return {OO.ui.Widget} The widget, for chaining
11329 * @fires resize
11330 */
11331 OO.ui.MultilineTextInputWidget.prototype.adjustSize = function () {
11332 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError,
11333 idealHeight, newHeight, scrollWidth, property;
11334
11335 if ( this.$input.val() !== this.valCache ) {
11336 if ( this.autosize ) {
11337 this.$clone
11338 .val( this.$input.val() )
11339 .attr( 'rows', this.minRows )
11340 // Set inline height property to 0 to measure scroll height
11341 .css( 'height', 0 );
11342
11343 this.$clone.removeClass( 'oo-ui-element-hidden' );
11344
11345 this.valCache = this.$input.val();
11346
11347 scrollHeight = this.$clone[ 0 ].scrollHeight;
11348
11349 // Remove inline height property to measure natural heights
11350 this.$clone.css( 'height', '' );
11351 innerHeight = this.$clone.innerHeight();
11352 outerHeight = this.$clone.outerHeight();
11353
11354 // Measure max rows height
11355 this.$clone
11356 .attr( 'rows', this.maxRows )
11357 .css( 'height', 'auto' )
11358 .val( '' );
11359 maxInnerHeight = this.$clone.innerHeight();
11360
11361 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
11362 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
11363 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
11364 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
11365
11366 this.$clone.addClass( 'oo-ui-element-hidden' );
11367
11368 // Only apply inline height when expansion beyond natural height is needed
11369 // Use the difference between the inner and outer height as a buffer
11370 newHeight = idealHeight > innerHeight ? idealHeight + ( outerHeight - innerHeight ) : '';
11371 if ( newHeight !== this.styleHeight ) {
11372 this.$input.css( 'height', newHeight );
11373 this.styleHeight = newHeight;
11374 this.emit( 'resize' );
11375 }
11376 }
11377 scrollWidth = this.$input[ 0 ].offsetWidth - this.$input[ 0 ].clientWidth;
11378 if ( scrollWidth !== this.scrollWidth ) {
11379 property = this.$element.css( 'direction' ) === 'rtl' ? 'left' : 'right';
11380 // Reset
11381 this.$label.css( { right: '', left: '' } );
11382 this.$indicator.css( { right: '', left: '' } );
11383
11384 if ( scrollWidth ) {
11385 this.$indicator.css( property, scrollWidth );
11386 if ( this.labelPosition === 'after' ) {
11387 this.$label.css( property, scrollWidth );
11388 }
11389 }
11390
11391 this.scrollWidth = scrollWidth;
11392 this.positionLabel();
11393 }
11394 }
11395 return this;
11396 };
11397
11398 /**
11399 * @inheritdoc
11400 * @protected
11401 */
11402 OO.ui.MultilineTextInputWidget.prototype.getInputElement = function () {
11403 return $( '<textarea>' );
11404 };
11405
11406 /**
11407 * Check if the input automatically adjusts its size.
11408 *
11409 * @return {boolean}
11410 */
11411 OO.ui.MultilineTextInputWidget.prototype.isAutosizing = function () {
11412 return !!this.autosize;
11413 };
11414
11415 /**
11416 * @inheritdoc
11417 */
11418 OO.ui.MultilineTextInputWidget.prototype.restorePreInfuseState = function ( state ) {
11419 OO.ui.MultilineTextInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
11420 if ( state.scrollTop !== undefined ) {
11421 this.$input.scrollTop( state.scrollTop );
11422 }
11423 };
11424
11425 /**
11426 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
11427 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
11428 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
11429 *
11430 * - by typing a value in the text input field. If the value exactly matches the value of a menu
11431 * option, that option will appear to be selected.
11432 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
11433 * input field.
11434 *
11435 * After the user chooses an option, its `data` will be used as a new value for the widget.
11436 * A `label` also can be specified for each option: if given, it will be shown instead of the
11437 * `data` in the dropdown menu.
11438 *
11439 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
11440 *
11441 * For more information about menus and options, please see the
11442 * [OOUI documentation on MediaWiki][1].
11443 *
11444 * @example
11445 * // A ComboBoxInputWidget.
11446 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11447 * value: 'Option 1',
11448 * options: [
11449 * { data: 'Option 1' },
11450 * { data: 'Option 2' },
11451 * { data: 'Option 3' }
11452 * ]
11453 * } );
11454 * $( document.body ).append( comboBox.$element );
11455 *
11456 * @example
11457 * // Example: A ComboBoxInputWidget with additional option labels.
11458 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11459 * value: 'Option 1',
11460 * options: [
11461 * {
11462 * data: 'Option 1',
11463 * label: 'Option One'
11464 * },
11465 * {
11466 * data: 'Option 2',
11467 * label: 'Option Two'
11468 * },
11469 * {
11470 * data: 'Option 3',
11471 * label: 'Option Three'
11472 * }
11473 * ]
11474 * } );
11475 * $( document.body ).append( comboBox.$element );
11476 *
11477 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
11478 *
11479 * @class
11480 * @extends OO.ui.TextInputWidget
11481 *
11482 * @constructor
11483 * @param {Object} [config] Configuration options
11484 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
11485 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu
11486 * select widget}.
11487 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful
11488 * in cases where the expanded menu is larger than its containing `<div>`. The specified overlay
11489 * layer is usually on top of the containing `<div>` and has a larger area. By default, the menu
11490 * uses relative positioning.
11491 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11492 */
11493 OO.ui.ComboBoxInputWidget = function OoUiComboBoxInputWidget( config ) {
11494 // Configuration initialization
11495 config = $.extend( {
11496 autocomplete: false
11497 }, config );
11498
11499 // ComboBoxInputWidget shouldn't support `multiline`
11500 config.multiline = false;
11501
11502 // See InputWidget#reusePreInfuseDOM about `config.$input`
11503 if ( config.$input ) {
11504 config.$input.removeAttr( 'list' );
11505 }
11506
11507 // Parent constructor
11508 OO.ui.ComboBoxInputWidget.parent.call( this, config );
11509
11510 // Properties
11511 this.$overlay = ( config.$overlay === true ?
11512 OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
11513 this.dropdownButton = new OO.ui.ButtonWidget( {
11514 classes: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ],
11515 label: OO.ui.msg( 'ooui-combobox-button-label' ),
11516 indicator: 'down',
11517 invisibleLabel: true,
11518 disabled: this.disabled
11519 } );
11520 this.menu = new OO.ui.MenuSelectWidget( $.extend(
11521 {
11522 widget: this,
11523 input: this,
11524 $floatableContainer: this.$element,
11525 disabled: this.isDisabled()
11526 },
11527 config.menu
11528 ) );
11529
11530 // Events
11531 this.connect( this, {
11532 change: 'onInputChange',
11533 enter: 'onInputEnter'
11534 } );
11535 this.dropdownButton.connect( this, {
11536 click: 'onDropdownButtonClick'
11537 } );
11538 this.menu.connect( this, {
11539 choose: 'onMenuChoose',
11540 add: 'onMenuItemsChange',
11541 remove: 'onMenuItemsChange',
11542 toggle: 'onMenuToggle'
11543 } );
11544
11545 // Initialization
11546 this.$input.attr( {
11547 role: 'combobox',
11548 'aria-owns': this.menu.getElementId(),
11549 'aria-autocomplete': 'list'
11550 } );
11551 this.dropdownButton.$button.attr( {
11552 'aria-controls': this.menu.getElementId()
11553 } );
11554 // Do not override options set via config.menu.items
11555 if ( config.options !== undefined ) {
11556 this.setOptions( config.options );
11557 }
11558 this.$field = $( '<div>' )
11559 .addClass( 'oo-ui-comboBoxInputWidget-field' )
11560 .append( this.$input, this.dropdownButton.$element );
11561 this.$element
11562 .addClass( 'oo-ui-comboBoxInputWidget' )
11563 .append( this.$field );
11564 this.$overlay.append( this.menu.$element );
11565 this.onMenuItemsChange();
11566 };
11567
11568 /* Setup */
11569
11570 OO.inheritClass( OO.ui.ComboBoxInputWidget, OO.ui.TextInputWidget );
11571
11572 /* Methods */
11573
11574 /**
11575 * Get the combobox's menu.
11576 *
11577 * @return {OO.ui.MenuSelectWidget} Menu widget
11578 */
11579 OO.ui.ComboBoxInputWidget.prototype.getMenu = function () {
11580 return this.menu;
11581 };
11582
11583 /**
11584 * Get the combobox's text input widget.
11585 *
11586 * @return {OO.ui.TextInputWidget} Text input widget
11587 */
11588 OO.ui.ComboBoxInputWidget.prototype.getInput = function () {
11589 return this;
11590 };
11591
11592 /**
11593 * Handle input change events.
11594 *
11595 * @private
11596 * @param {string} value New value
11597 */
11598 OO.ui.ComboBoxInputWidget.prototype.onInputChange = function ( value ) {
11599 var match = this.menu.findItemFromData( value );
11600
11601 this.menu.selectItem( match );
11602 if ( this.menu.findHighlightedItem() ) {
11603 this.menu.highlightItem( match );
11604 }
11605
11606 if ( !this.isDisabled() ) {
11607 this.menu.toggle( true );
11608 }
11609 };
11610
11611 /**
11612 * Handle input enter events.
11613 *
11614 * @private
11615 */
11616 OO.ui.ComboBoxInputWidget.prototype.onInputEnter = function () {
11617 if ( !this.isDisabled() ) {
11618 this.menu.toggle( false );
11619 }
11620 };
11621
11622 /**
11623 * Handle button click events.
11624 *
11625 * @private
11626 */
11627 OO.ui.ComboBoxInputWidget.prototype.onDropdownButtonClick = function () {
11628 this.menu.toggle();
11629 this.focus();
11630 };
11631
11632 /**
11633 * Handle menu choose events.
11634 *
11635 * @private
11636 * @param {OO.ui.OptionWidget} item Chosen item
11637 */
11638 OO.ui.ComboBoxInputWidget.prototype.onMenuChoose = function ( item ) {
11639 this.setValue( item.getData() );
11640 };
11641
11642 /**
11643 * Handle menu item change events.
11644 *
11645 * @private
11646 */
11647 OO.ui.ComboBoxInputWidget.prototype.onMenuItemsChange = function () {
11648 var match = this.menu.findItemFromData( this.getValue() );
11649 this.menu.selectItem( match );
11650 if ( this.menu.findHighlightedItem() ) {
11651 this.menu.highlightItem( match );
11652 }
11653 this.$element.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu.isEmpty() );
11654 };
11655
11656 /**
11657 * Handle menu toggle events.
11658 *
11659 * @private
11660 * @param {boolean} isVisible Open state of the menu
11661 */
11662 OO.ui.ComboBoxInputWidget.prototype.onMenuToggle = function ( isVisible ) {
11663 this.$element.toggleClass( 'oo-ui-comboBoxInputWidget-open', isVisible );
11664 };
11665
11666 /**
11667 * Update the disabled state of the controls
11668 *
11669 * @chainable
11670 * @protected
11671 * @return {OO.ui.ComboBoxInputWidget} The widget, for chaining
11672 */
11673 OO.ui.ComboBoxInputWidget.prototype.updateControlsDisabled = function () {
11674 var disabled = this.isDisabled() || this.isReadOnly();
11675 if ( this.dropdownButton ) {
11676 this.dropdownButton.setDisabled( disabled );
11677 }
11678 if ( this.menu ) {
11679 this.menu.setDisabled( disabled );
11680 }
11681 return this;
11682 };
11683
11684 /**
11685 * @inheritdoc
11686 */
11687 OO.ui.ComboBoxInputWidget.prototype.setDisabled = function () {
11688 // Parent method
11689 OO.ui.ComboBoxInputWidget.parent.prototype.setDisabled.apply( this, arguments );
11690 this.updateControlsDisabled();
11691 return this;
11692 };
11693
11694 /**
11695 * @inheritdoc
11696 */
11697 OO.ui.ComboBoxInputWidget.prototype.setReadOnly = function () {
11698 // Parent method
11699 OO.ui.ComboBoxInputWidget.parent.prototype.setReadOnly.apply( this, arguments );
11700 this.updateControlsDisabled();
11701 return this;
11702 };
11703
11704 /**
11705 * Set the options available for this input.
11706 *
11707 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
11708 * @chainable
11709 * @return {OO.ui.Widget} The widget, for chaining
11710 */
11711 OO.ui.ComboBoxInputWidget.prototype.setOptions = function ( options ) {
11712 this.getMenu()
11713 .clearItems()
11714 .addItems( options.map( function ( opt ) {
11715 return new OO.ui.MenuOptionWidget( {
11716 data: opt.data,
11717 label: opt.label !== undefined ? opt.label : opt.data
11718 } );
11719 } ) );
11720
11721 return this;
11722 };
11723
11724 /**
11725 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
11726 * which is a widget that is specified by reference before any optional configuration settings.
11727 *
11728 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of
11729 * four ways:
11730 *
11731 * - **left**: The label is placed before the field-widget and aligned with the left margin.
11732 * A left-alignment is used for forms with many fields.
11733 * - **right**: The label is placed before the field-widget and aligned to the right margin.
11734 * A right-alignment is used for long but familiar forms which users tab through,
11735 * verifying the current field with a quick glance at the label.
11736 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
11737 * that users fill out from top to bottom.
11738 * - **inline**: The label is placed after the field-widget and aligned to the left.
11739 * An inline-alignment is best used with checkboxes or radio buttons.
11740 *
11741 * Help text can either be:
11742 *
11743 * - accessed via a help icon that appears in the upper right corner of the rendered field layout,
11744 * or
11745 * - shown as a subtle explanation below the label.
11746 *
11747 * If the help text is brief, or is essential to always expose it, set `helpInline` to `true`.
11748 * If it is long or not essential, leave `helpInline` to its default, `false`.
11749 *
11750 * Please see the [OOUI documentation on MediaWiki] [1] for examples and more information.
11751 *
11752 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
11753 *
11754 * @class
11755 * @extends OO.ui.Layout
11756 * @mixins OO.ui.mixin.LabelElement
11757 * @mixins OO.ui.mixin.TitledElement
11758 *
11759 * @constructor
11760 * @param {OO.ui.Widget} fieldWidget Field widget
11761 * @param {Object} [config] Configuration options
11762 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top'
11763 * or 'inline'
11764 * @cfg {Array} [errors] Error messages about the widget, which will be
11765 * displayed below the widget.
11766 * @cfg {Array} [warnings] Warning messages about the widget, which will be
11767 * displayed below the widget.
11768 * @cfg {Array} [successMessages] Success messages on user interactions with the widget,
11769 * which will be displayed below the widget.
11770 * The array may contain strings or OO.ui.HtmlSnippet instances.
11771 * @cfg {Array} [notices] Notices about the widget, which will be displayed
11772 * below the widget.
11773 * The array may contain strings or OO.ui.HtmlSnippet instances.
11774 * These are more visible than `help` messages when `helpInline` is set, and so
11775 * might be good for transient messages.
11776 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified
11777 * and `helpInline` is `false`, a "help" icon will appear in the upper-right
11778 * corner of the rendered field; clicking it will display the text in a popup.
11779 * If `helpInline` is `true`, then a subtle description will be shown after the
11780 * label.
11781 * @cfg {boolean} [helpInline=false] Whether or not the help should be inline,
11782 * or shown when the "help" icon is clicked.
11783 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if
11784 * `help` is given.
11785 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11786 *
11787 * @throws {Error} An error is thrown if no widget is specified
11788 */
11789 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
11790 // Allow passing positional parameters inside the config object
11791 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
11792 config = fieldWidget;
11793 fieldWidget = config.fieldWidget;
11794 }
11795
11796 // Make sure we have required constructor arguments
11797 if ( fieldWidget === undefined ) {
11798 throw new Error( 'Widget not found' );
11799 }
11800
11801 // Configuration initialization
11802 config = $.extend( { align: 'left', helpInline: false }, config );
11803
11804 // Parent constructor
11805 OO.ui.FieldLayout.parent.call( this, config );
11806
11807 // Mixin constructors
11808 OO.ui.mixin.LabelElement.call( this, $.extend( {
11809 $label: $( '<label>' )
11810 }, config ) );
11811 OO.ui.mixin.TitledElement.call( this, $.extend( { $titled: this.$label }, config ) );
11812
11813 // Properties
11814 this.fieldWidget = fieldWidget;
11815 this.errors = [];
11816 this.warnings = [];
11817 this.successMessages = [];
11818 this.notices = [];
11819 this.$field = this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
11820 this.$messages = $( '<ul>' );
11821 this.$header = $( '<span>' );
11822 this.$body = $( '<div>' );
11823 this.align = null;
11824 this.helpInline = config.helpInline;
11825
11826 // Events
11827 this.fieldWidget.connect( this, {
11828 disable: 'onFieldDisable'
11829 } );
11830
11831 // Initialization
11832 this.$help = config.help ?
11833 this.createHelpElement( config.help, config.$overlay ) :
11834 $( [] );
11835 if ( this.fieldWidget.getInputId() ) {
11836 this.$label.attr( 'for', this.fieldWidget.getInputId() );
11837 if ( this.helpInline ) {
11838 this.$help.attr( 'for', this.fieldWidget.getInputId() );
11839 }
11840 } else {
11841 this.$label.on( 'click', function () {
11842 this.fieldWidget.simulateLabelClick();
11843 }.bind( this ) );
11844 if ( this.helpInline ) {
11845 this.$help.on( 'click', function () {
11846 this.fieldWidget.simulateLabelClick();
11847 }.bind( this ) );
11848 }
11849 }
11850 this.$element
11851 .addClass( 'oo-ui-fieldLayout' )
11852 .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget.isDisabled() )
11853 .append( this.$body );
11854 this.$body.addClass( 'oo-ui-fieldLayout-body' );
11855 this.$header.addClass( 'oo-ui-fieldLayout-header' );
11856 this.$messages.addClass( 'oo-ui-fieldLayout-messages' );
11857 this.$field
11858 .addClass( 'oo-ui-fieldLayout-field' )
11859 .append( this.fieldWidget.$element );
11860
11861 this.setErrors( config.errors || [] );
11862 this.setWarnings( config.warnings || [] );
11863 this.setSuccess( config.successMessages || [] );
11864 this.setNotices( config.notices || [] );
11865 this.setAlignment( config.align );
11866 // Call this again to take into account the widget's accessKey
11867 this.updateTitle();
11868 };
11869
11870 /* Setup */
11871
11872 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
11873 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.LabelElement );
11874 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.TitledElement );
11875
11876 /* Methods */
11877
11878 /**
11879 * Handle field disable events.
11880 *
11881 * @private
11882 * @param {boolean} value Field is disabled
11883 */
11884 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
11885 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
11886 };
11887
11888 /**
11889 * Get the widget contained by the field.
11890 *
11891 * @return {OO.ui.Widget} Field widget
11892 */
11893 OO.ui.FieldLayout.prototype.getField = function () {
11894 return this.fieldWidget;
11895 };
11896
11897 /**
11898 * Return `true` if the given field widget can be used with `'inline'` alignment (see
11899 * #setAlignment). Return `false` if it can't or if this can't be determined.
11900 *
11901 * @return {boolean}
11902 */
11903 OO.ui.FieldLayout.prototype.isFieldInline = function () {
11904 // This is very simplistic, but should be good enough.
11905 return this.getField().$element.prop( 'tagName' ).toLowerCase() === 'span';
11906 };
11907
11908 /**
11909 * @protected
11910 * @param {string} kind 'error' or 'notice'
11911 * @param {string|OO.ui.HtmlSnippet} text
11912 * @return {jQuery}
11913 */
11914 OO.ui.FieldLayout.prototype.makeMessage = function ( kind, text ) {
11915 var $listItem, $icon, message;
11916 $listItem = $( '<li>' );
11917 if ( kind === 'error' ) {
11918 $icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'error' ] } ).$element;
11919 $listItem.attr( 'role', 'alert' );
11920 } else if ( kind === 'warning' ) {
11921 $icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'warning' ] } ).$element;
11922 $listItem.attr( 'role', 'alert' );
11923 } else if ( kind === 'success' ) {
11924 $icon = new OO.ui.IconWidget( { icon: 'check', flags: [ 'success' ] } ).$element;
11925 } else if ( kind === 'notice' ) {
11926 $icon = new OO.ui.IconWidget( { icon: 'notice' } ).$element;
11927 } else {
11928 $icon = '';
11929 }
11930 message = new OO.ui.LabelWidget( { label: text } );
11931 $listItem
11932 .append( $icon, message.$element )
11933 .addClass( 'oo-ui-fieldLayout-messages-' + kind );
11934 return $listItem;
11935 };
11936
11937 /**
11938 * Set the field alignment mode.
11939 *
11940 * @private
11941 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
11942 * @chainable
11943 * @return {OO.ui.BookletLayout} The layout, for chaining
11944 */
11945 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
11946 if ( value !== this.align ) {
11947 // Default to 'left'
11948 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
11949 value = 'left';
11950 }
11951 // Validate
11952 if ( value === 'inline' && !this.isFieldInline() ) {
11953 value = 'top';
11954 }
11955 // Reorder elements
11956
11957 if ( this.helpInline ) {
11958 if ( value === 'top' ) {
11959 this.$header.append( this.$label );
11960 this.$body.append( this.$header, this.$field, this.$help );
11961 } else if ( value === 'inline' ) {
11962 this.$header.append( this.$label, this.$help );
11963 this.$body.append( this.$field, this.$header );
11964 } else {
11965 this.$header.append( this.$label, this.$help );
11966 this.$body.append( this.$header, this.$field );
11967 }
11968 } else {
11969 if ( value === 'top' ) {
11970 this.$header.append( this.$help, this.$label );
11971 this.$body.append( this.$header, this.$field );
11972 } else if ( value === 'inline' ) {
11973 this.$header.append( this.$help, this.$label );
11974 this.$body.append( this.$field, this.$header );
11975 } else {
11976 this.$header.append( this.$label );
11977 this.$body.append( this.$header, this.$help, this.$field );
11978 }
11979 }
11980 // Set classes. The following classes can be used here:
11981 // * oo-ui-fieldLayout-align-left
11982 // * oo-ui-fieldLayout-align-right
11983 // * oo-ui-fieldLayout-align-top
11984 // * oo-ui-fieldLayout-align-inline
11985 if ( this.align ) {
11986 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
11987 }
11988 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
11989 this.align = value;
11990 }
11991
11992 return this;
11993 };
11994
11995 /**
11996 * Set the list of error messages.
11997 *
11998 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
11999 * The array may contain strings or OO.ui.HtmlSnippet instances.
12000 * @chainable
12001 * @return {OO.ui.BookletLayout} The layout, for chaining
12002 */
12003 OO.ui.FieldLayout.prototype.setErrors = function ( errors ) {
12004 this.errors = errors.slice();
12005 this.updateMessages();
12006 return this;
12007 };
12008
12009 /**
12010 * Set the list of warning messages.
12011 *
12012 * @param {Array} warnings Warning messages about the widget, which will be displayed below
12013 * the widget.
12014 * The array may contain strings or OO.ui.HtmlSnippet instances.
12015 * @chainable
12016 * @return {OO.ui.BookletLayout} The layout, for chaining
12017 */
12018 OO.ui.FieldLayout.prototype.setWarnings = function ( warnings ) {
12019 this.warnings = warnings.slice();
12020 this.updateMessages();
12021 return this;
12022 };
12023
12024 /**
12025 * Set the list of success messages.
12026 *
12027 * @param {Array} successMessages Success messages about the widget, which will be displayed below
12028 * the widget.
12029 * The array may contain strings or OO.ui.HtmlSnippet instances.
12030 * @chainable
12031 * @return {OO.ui.BookletLayout} The layout, for chaining
12032 */
12033 OO.ui.FieldLayout.prototype.setSuccess = function ( successMessages ) {
12034 this.successMessages = successMessages.slice();
12035 this.updateMessages();
12036 return this;
12037 };
12038
12039 /**
12040 * Set the list of notice messages.
12041 *
12042 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
12043 * The array may contain strings or OO.ui.HtmlSnippet instances.
12044 * @chainable
12045 * @return {OO.ui.BookletLayout} The layout, for chaining
12046 */
12047 OO.ui.FieldLayout.prototype.setNotices = function ( notices ) {
12048 this.notices = notices.slice();
12049 this.updateMessages();
12050 return this;
12051 };
12052
12053 /**
12054 * Update the rendering of error, warning, success and notice messages.
12055 *
12056 * @private
12057 */
12058 OO.ui.FieldLayout.prototype.updateMessages = function () {
12059 var i;
12060 this.$messages.empty();
12061
12062 if (
12063 this.errors.length ||
12064 this.warnings.length ||
12065 this.successMessages.length ||
12066 this.notices.length
12067 ) {
12068 this.$body.after( this.$messages );
12069 } else {
12070 this.$messages.remove();
12071 return;
12072 }
12073
12074 for ( i = 0; i < this.errors.length; i++ ) {
12075 this.$messages.append( this.makeMessage( 'error', this.errors[ i ] ) );
12076 }
12077 for ( i = 0; i < this.warnings.length; i++ ) {
12078 this.$messages.append( this.makeMessage( 'warning', this.warnings[ i ] ) );
12079 }
12080 for ( i = 0; i < this.successMessages.length; i++ ) {
12081 this.$messages.append( this.makeMessage( 'success', this.successMessages[ i ] ) );
12082 }
12083 for ( i = 0; i < this.notices.length; i++ ) {
12084 this.$messages.append( this.makeMessage( 'notice', this.notices[ i ] ) );
12085 }
12086 };
12087
12088 /**
12089 * Include information about the widget's accessKey in our title. TitledElement calls this method.
12090 * (This is a bit of a hack.)
12091 *
12092 * @protected
12093 * @param {string} title Tooltip label for 'title' attribute
12094 * @return {string}
12095 */
12096 OO.ui.FieldLayout.prototype.formatTitleWithAccessKey = function ( title ) {
12097 if ( this.fieldWidget && this.fieldWidget.formatTitleWithAccessKey ) {
12098 return this.fieldWidget.formatTitleWithAccessKey( title );
12099 }
12100 return title;
12101 };
12102
12103 /**
12104 * Creates and returns the help element. Also sets the `aria-describedby`
12105 * attribute on the main element of the `fieldWidget`.
12106 *
12107 * @private
12108 * @param {string|OO.ui.HtmlSnippet} [help] Help text.
12109 * @param {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup.
12110 * @return {jQuery} The element that should become `this.$help`.
12111 */
12112 OO.ui.FieldLayout.prototype.createHelpElement = function ( help, $overlay ) {
12113 var helpId, helpWidget;
12114
12115 if ( this.helpInline ) {
12116 helpWidget = new OO.ui.LabelWidget( {
12117 label: help,
12118 classes: [ 'oo-ui-inline-help' ]
12119 } );
12120
12121 helpId = helpWidget.getElementId();
12122 } else {
12123 helpWidget = new OO.ui.PopupButtonWidget( {
12124 $overlay: $overlay,
12125 popup: {
12126 padded: true
12127 },
12128 classes: [ 'oo-ui-fieldLayout-help' ],
12129 framed: false,
12130 icon: 'info',
12131 label: OO.ui.msg( 'ooui-field-help' ),
12132 invisibleLabel: true
12133 } );
12134 if ( help instanceof OO.ui.HtmlSnippet ) {
12135 helpWidget.getPopup().$body.html( help.toString() );
12136 } else {
12137 helpWidget.getPopup().$body.text( help );
12138 }
12139
12140 helpId = helpWidget.getPopup().getBodyId();
12141 }
12142
12143 // Set the 'aria-describedby' attribute on the fieldWidget
12144 // Preference given to an input or a button
12145 (
12146 this.fieldWidget.$input ||
12147 this.fieldWidget.$button ||
12148 this.fieldWidget.$element
12149 ).attr( 'aria-describedby', helpId );
12150
12151 return helpWidget.$element;
12152 };
12153
12154 /**
12155 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget,
12156 * a button, and an optional label and/or help text. The field-widget (e.g., a
12157 * {@link OO.ui.TextInputWidget TextInputWidget}), is required and is specified before any optional
12158 * configuration settings.
12159 *
12160 * Labels can be aligned in one of four ways:
12161 *
12162 * - **left**: The label is placed before the field-widget and aligned with the left margin.
12163 * A left-alignment is used for forms with many fields.
12164 * - **right**: The label is placed before the field-widget and aligned to the right margin.
12165 * A right-alignment is used for long but familiar forms which users tab through,
12166 * verifying the current field with a quick glance at the label.
12167 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
12168 * that users fill out from top to bottom.
12169 * - **inline**: The label is placed after the field-widget and aligned to the left.
12170 * An inline-alignment is best used with checkboxes or radio buttons.
12171 *
12172 * Help text is accessed via a help icon that appears in the upper right corner of the rendered
12173 * field layout when help text is specified.
12174 *
12175 * @example
12176 * // Example of an ActionFieldLayout
12177 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
12178 * new OO.ui.TextInputWidget( {
12179 * placeholder: 'Field widget'
12180 * } ),
12181 * new OO.ui.ButtonWidget( {
12182 * label: 'Button'
12183 * } ),
12184 * {
12185 * label: 'An ActionFieldLayout. This label is aligned top',
12186 * align: 'top',
12187 * help: 'This is help text'
12188 * }
12189 * );
12190 *
12191 * $( document.body ).append( actionFieldLayout.$element );
12192 *
12193 * @class
12194 * @extends OO.ui.FieldLayout
12195 *
12196 * @constructor
12197 * @param {OO.ui.Widget} fieldWidget Field widget
12198 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
12199 * @param {Object} config
12200 */
12201 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
12202 // Allow passing positional parameters inside the config object
12203 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
12204 config = fieldWidget;
12205 fieldWidget = config.fieldWidget;
12206 buttonWidget = config.buttonWidget;
12207 }
12208
12209 // Parent constructor
12210 OO.ui.ActionFieldLayout.parent.call( this, fieldWidget, config );
12211
12212 // Properties
12213 this.buttonWidget = buttonWidget;
12214 this.$button = $( '<span>' );
12215 this.$input = this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
12216
12217 // Initialization
12218 this.$element.addClass( 'oo-ui-actionFieldLayout' );
12219 this.$button
12220 .addClass( 'oo-ui-actionFieldLayout-button' )
12221 .append( this.buttonWidget.$element );
12222 this.$input
12223 .addClass( 'oo-ui-actionFieldLayout-input' )
12224 .append( this.fieldWidget.$element );
12225 this.$field.append( this.$input, this.$button );
12226 };
12227
12228 /* Setup */
12229
12230 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
12231
12232 /**
12233 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
12234 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
12235 * configured with a label as well. For more information and examples,
12236 * please see the [OOUI documentation on MediaWiki][1].
12237 *
12238 * @example
12239 * // Example of a fieldset layout
12240 * var input1 = new OO.ui.TextInputWidget( {
12241 * placeholder: 'A text input field'
12242 * } );
12243 *
12244 * var input2 = new OO.ui.TextInputWidget( {
12245 * placeholder: 'A text input field'
12246 * } );
12247 *
12248 * var fieldset = new OO.ui.FieldsetLayout( {
12249 * label: 'Example of a fieldset layout'
12250 * } );
12251 *
12252 * fieldset.addItems( [
12253 * new OO.ui.FieldLayout( input1, {
12254 * label: 'Field One'
12255 * } ),
12256 * new OO.ui.FieldLayout( input2, {
12257 * label: 'Field Two'
12258 * } )
12259 * ] );
12260 * $( document.body ).append( fieldset.$element );
12261 *
12262 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
12263 *
12264 * @class
12265 * @extends OO.ui.Layout
12266 * @mixins OO.ui.mixin.IconElement
12267 * @mixins OO.ui.mixin.LabelElement
12268 * @mixins OO.ui.mixin.GroupElement
12269 *
12270 * @constructor
12271 * @param {Object} [config] Configuration options
12272 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset.
12273 * See OO.ui.FieldLayout for more information about fields.
12274 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon
12275 * will appear in the upper-right corner of the rendered field; clicking it will display the text
12276 * in a popup. For important messages, you are advised to use `notices`, as they are always shown.
12277 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
12278 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
12279 */
12280 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
12281 // Configuration initialization
12282 config = config || {};
12283
12284 // Parent constructor
12285 OO.ui.FieldsetLayout.parent.call( this, config );
12286
12287 // Mixin constructors
12288 OO.ui.mixin.IconElement.call( this, config );
12289 OO.ui.mixin.LabelElement.call( this, config );
12290 OO.ui.mixin.GroupElement.call( this, config );
12291
12292 // Properties
12293 this.$header = $( '<legend>' );
12294 if ( config.help ) {
12295 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
12296 $overlay: config.$overlay,
12297 popup: {
12298 padded: true
12299 },
12300 classes: [ 'oo-ui-fieldsetLayout-help' ],
12301 framed: false,
12302 icon: 'info',
12303 label: OO.ui.msg( 'ooui-field-help' ),
12304 invisibleLabel: true
12305 } );
12306 if ( config.help instanceof OO.ui.HtmlSnippet ) {
12307 this.popupButtonWidget.getPopup().$body.html( config.help.toString() );
12308 } else {
12309 this.popupButtonWidget.getPopup().$body.text( config.help );
12310 }
12311 this.$help = this.popupButtonWidget.$element;
12312 } else {
12313 this.$help = $( [] );
12314 }
12315
12316 // Initialization
12317 this.$header
12318 .addClass( 'oo-ui-fieldsetLayout-header' )
12319 .append( this.$icon, this.$label, this.$help );
12320 this.$group.addClass( 'oo-ui-fieldsetLayout-group' );
12321 this.$element
12322 .addClass( 'oo-ui-fieldsetLayout' )
12323 .prepend( this.$header, this.$group );
12324 if ( Array.isArray( config.items ) ) {
12325 this.addItems( config.items );
12326 }
12327 };
12328
12329 /* Setup */
12330
12331 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
12332 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.IconElement );
12333 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.LabelElement );
12334 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.GroupElement );
12335
12336 /* Static Properties */
12337
12338 /**
12339 * @static
12340 * @inheritdoc
12341 */
12342 OO.ui.FieldsetLayout.static.tagName = 'fieldset';
12343
12344 /**
12345 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use
12346 * browser-based form submission for the fields instead of handling them in JavaScript. Form layouts
12347 * can be configured with an HTML form action, an encoding type, and a method using the #action,
12348 * #enctype, and #method configs, respectively.
12349 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
12350 *
12351 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
12352 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
12353 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
12354 * some fancier controls. Some controls have both regular and InputWidget variants, for example
12355 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
12356 * often have simplified APIs to match the capabilities of HTML forms.
12357 * See the [OOUI documentation on MediaWiki] [2] for more information about InputWidgets.
12358 *
12359 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Forms
12360 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
12361 *
12362 * @example
12363 * // Example of a form layout that wraps a fieldset layout
12364 * var input1 = new OO.ui.TextInputWidget( {
12365 * placeholder: 'Username'
12366 * } );
12367 * var input2 = new OO.ui.TextInputWidget( {
12368 * placeholder: 'Password',
12369 * type: 'password'
12370 * } );
12371 * var submit = new OO.ui.ButtonInputWidget( {
12372 * label: 'Submit'
12373 * } );
12374 *
12375 * var fieldset = new OO.ui.FieldsetLayout( {
12376 * label: 'A form layout'
12377 * } );
12378 * fieldset.addItems( [
12379 * new OO.ui.FieldLayout( input1, {
12380 * label: 'Username',
12381 * align: 'top'
12382 * } ),
12383 * new OO.ui.FieldLayout( input2, {
12384 * label: 'Password',
12385 * align: 'top'
12386 * } ),
12387 * new OO.ui.FieldLayout( submit )
12388 * ] );
12389 * var form = new OO.ui.FormLayout( {
12390 * items: [ fieldset ],
12391 * action: '/api/formhandler',
12392 * method: 'get'
12393 * } )
12394 * $( document.body ).append( form.$element );
12395 *
12396 * @class
12397 * @extends OO.ui.Layout
12398 * @mixins OO.ui.mixin.GroupElement
12399 *
12400 * @constructor
12401 * @param {Object} [config] Configuration options
12402 * @cfg {string} [method] HTML form `method` attribute
12403 * @cfg {string} [action] HTML form `action` attribute
12404 * @cfg {string} [enctype] HTML form `enctype` attribute
12405 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
12406 */
12407 OO.ui.FormLayout = function OoUiFormLayout( config ) {
12408 var action;
12409
12410 // Configuration initialization
12411 config = config || {};
12412
12413 // Parent constructor
12414 OO.ui.FormLayout.parent.call( this, config );
12415
12416 // Mixin constructors
12417 OO.ui.mixin.GroupElement.call( this, $.extend( { $group: this.$element }, config ) );
12418
12419 // Events
12420 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
12421
12422 // Make sure the action is safe
12423 action = config.action;
12424 if ( action !== undefined && !OO.ui.isSafeUrl( action ) ) {
12425 action = './' + action;
12426 }
12427
12428 // Initialization
12429 this.$element
12430 .addClass( 'oo-ui-formLayout' )
12431 .attr( {
12432 method: config.method,
12433 action: action,
12434 enctype: config.enctype
12435 } );
12436 if ( Array.isArray( config.items ) ) {
12437 this.addItems( config.items );
12438 }
12439 };
12440
12441 /* Setup */
12442
12443 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
12444 OO.mixinClass( OO.ui.FormLayout, OO.ui.mixin.GroupElement );
12445
12446 /* Events */
12447
12448 /**
12449 * A 'submit' event is emitted when the form is submitted.
12450 *
12451 * @event submit
12452 */
12453
12454 /* Static Properties */
12455
12456 /**
12457 * @static
12458 * @inheritdoc
12459 */
12460 OO.ui.FormLayout.static.tagName = 'form';
12461
12462 /* Methods */
12463
12464 /**
12465 * Handle form submit events.
12466 *
12467 * @private
12468 * @param {jQuery.Event} e Submit event
12469 * @fires submit
12470 * @return {OO.ui.FormLayout} The layout, for chaining
12471 */
12472 OO.ui.FormLayout.prototype.onFormSubmit = function () {
12473 if ( this.emit( 'submit' ) ) {
12474 return false;
12475 }
12476 };
12477
12478 /**
12479 * PanelLayouts expand to cover the entire area of their parent. They can be configured with
12480 * scrolling, padding, and a frame, and are often used together with
12481 * {@link OO.ui.StackLayout StackLayouts}.
12482 *
12483 * @example
12484 * // Example of a panel layout
12485 * var panel = new OO.ui.PanelLayout( {
12486 * expanded: false,
12487 * framed: true,
12488 * padded: true,
12489 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
12490 * } );
12491 * $( document.body ).append( panel.$element );
12492 *
12493 * @class
12494 * @extends OO.ui.Layout
12495 *
12496 * @constructor
12497 * @param {Object} [config] Configuration options
12498 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
12499 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
12500 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
12501 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside
12502 * content.
12503 */
12504 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
12505 // Configuration initialization
12506 config = $.extend( {
12507 scrollable: false,
12508 padded: false,
12509 expanded: true,
12510 framed: false
12511 }, config );
12512
12513 // Parent constructor
12514 OO.ui.PanelLayout.parent.call( this, config );
12515
12516 // Initialization
12517 this.$element.addClass( 'oo-ui-panelLayout' );
12518 if ( config.scrollable ) {
12519 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
12520 }
12521 if ( config.padded ) {
12522 this.$element.addClass( 'oo-ui-panelLayout-padded' );
12523 }
12524 if ( config.expanded ) {
12525 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
12526 }
12527 if ( config.framed ) {
12528 this.$element.addClass( 'oo-ui-panelLayout-framed' );
12529 }
12530 };
12531
12532 /* Setup */
12533
12534 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
12535
12536 /* Static Methods */
12537
12538 /**
12539 * @inheritdoc
12540 */
12541 OO.ui.PanelLayout.static.reusePreInfuseDOM = function ( node, config ) {
12542 config = OO.ui.PanelLayout.parent.static.reusePreInfuseDOM( node, config );
12543 if ( config.preserveContent !== false ) {
12544 config.$content = $( node ).contents();
12545 }
12546 return config;
12547 };
12548
12549 /* Methods */
12550
12551 /**
12552 * Focus the panel layout
12553 *
12554 * The default implementation just focuses the first focusable element in the panel
12555 */
12556 OO.ui.PanelLayout.prototype.focus = function () {
12557 OO.ui.findFocusable( this.$element ).focus();
12558 };
12559
12560 /**
12561 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
12562 * items), with small margins between them. Convenient when you need to put a number of block-level
12563 * widgets on a single line next to each other.
12564 *
12565 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
12566 *
12567 * @example
12568 * // HorizontalLayout with a text input and a label
12569 * var layout = new OO.ui.HorizontalLayout( {
12570 * items: [
12571 * new OO.ui.LabelWidget( { label: 'Label' } ),
12572 * new OO.ui.TextInputWidget( { value: 'Text' } )
12573 * ]
12574 * } );
12575 * $( document.body ).append( layout.$element );
12576 *
12577 * @class
12578 * @extends OO.ui.Layout
12579 * @mixins OO.ui.mixin.GroupElement
12580 *
12581 * @constructor
12582 * @param {Object} [config] Configuration options
12583 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
12584 */
12585 OO.ui.HorizontalLayout = function OoUiHorizontalLayout( config ) {
12586 // Configuration initialization
12587 config = config || {};
12588
12589 // Parent constructor
12590 OO.ui.HorizontalLayout.parent.call( this, config );
12591
12592 // Mixin constructors
12593 OO.ui.mixin.GroupElement.call( this, $.extend( { $group: this.$element }, config ) );
12594
12595 // Initialization
12596 this.$element.addClass( 'oo-ui-horizontalLayout' );
12597 if ( Array.isArray( config.items ) ) {
12598 this.addItems( config.items );
12599 }
12600 };
12601
12602 /* Setup */
12603
12604 OO.inheritClass( OO.ui.HorizontalLayout, OO.ui.Layout );
12605 OO.mixinClass( OO.ui.HorizontalLayout, OO.ui.mixin.GroupElement );
12606
12607 /**
12608 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
12609 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
12610 * (to adjust the value in increments) to allow the user to enter a number.
12611 *
12612 * @example
12613 * // A NumberInputWidget.
12614 * var numberInput = new OO.ui.NumberInputWidget( {
12615 * label: 'NumberInputWidget',
12616 * input: { value: 5 },
12617 * min: 1,
12618 * max: 10
12619 * } );
12620 * $( document.body ).append( numberInput.$element );
12621 *
12622 * @class
12623 * @extends OO.ui.TextInputWidget
12624 *
12625 * @constructor
12626 * @param {Object} [config] Configuration options
12627 * @cfg {Object} [minusButton] Configuration options to pass to the
12628 * {@link OO.ui.ButtonWidget decrementing button widget}.
12629 * @cfg {Object} [plusButton] Configuration options to pass to the
12630 * {@link OO.ui.ButtonWidget incrementing button widget}.
12631 * @cfg {number} [min=-Infinity] Minimum allowed value
12632 * @cfg {number} [max=Infinity] Maximum allowed value
12633 * @cfg {number|null} [step] If specified, the field only accepts values that are multiples of this.
12634 * @cfg {number} [buttonStep=step||1] Delta when using the buttons or Up/Down arrow keys.
12635 * Defaults to `step` if specified, otherwise `1`.
12636 * @cfg {number} [pageStep=10*buttonStep] Delta when using the Page-up/Page-down keys.
12637 * Defaults to 10 times `buttonStep`.
12638 * @cfg {boolean} [showButtons=true] Whether to show the plus and minus buttons.
12639 */
12640 OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
12641 var $field = $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' );
12642
12643 // Configuration initialization
12644 config = $.extend( {
12645 min: -Infinity,
12646 max: Infinity,
12647 showButtons: true
12648 }, config );
12649
12650 // For backward compatibility
12651 $.extend( config, config.input );
12652 this.input = this;
12653
12654 // Parent constructor
12655 OO.ui.NumberInputWidget.parent.call( this, $.extend( config, {
12656 type: 'number'
12657 } ) );
12658
12659 if ( config.showButtons ) {
12660 this.minusButton = new OO.ui.ButtonWidget( $.extend(
12661 {
12662 disabled: this.isDisabled(),
12663 tabIndex: -1,
12664 classes: [ 'oo-ui-numberInputWidget-minusButton' ],
12665 icon: 'subtract'
12666 },
12667 config.minusButton
12668 ) );
12669 this.minusButton.$element.attr( 'aria-hidden', 'true' );
12670 this.plusButton = new OO.ui.ButtonWidget( $.extend(
12671 {
12672 disabled: this.isDisabled(),
12673 tabIndex: -1,
12674 classes: [ 'oo-ui-numberInputWidget-plusButton' ],
12675 icon: 'add'
12676 },
12677 config.plusButton
12678 ) );
12679 this.plusButton.$element.attr( 'aria-hidden', 'true' );
12680 }
12681
12682 // Events
12683 this.$input.on( {
12684 keydown: this.onKeyDown.bind( this ),
12685 'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
12686 } );
12687 if ( config.showButtons ) {
12688 this.plusButton.connect( this, {
12689 click: [ 'onButtonClick', +1 ]
12690 } );
12691 this.minusButton.connect( this, {
12692 click: [ 'onButtonClick', -1 ]
12693 } );
12694 }
12695
12696 // Build the field
12697 $field.append( this.$input );
12698 if ( config.showButtons ) {
12699 $field
12700 .prepend( this.minusButton.$element )
12701 .append( this.plusButton.$element );
12702 }
12703
12704 // Initialization
12705 if ( config.allowInteger || config.isInteger ) {
12706 // Backward compatibility
12707 config.step = 1;
12708 }
12709 this.setRange( config.min, config.max );
12710 this.setStep( config.buttonStep, config.pageStep, config.step );
12711 // Set the validation method after we set step and range
12712 // so that it doesn't immediately call setValidityFlag
12713 this.setValidation( this.validateNumber.bind( this ) );
12714
12715 this.$element
12716 .addClass( 'oo-ui-numberInputWidget' )
12717 .toggleClass( 'oo-ui-numberInputWidget-buttoned', config.showButtons )
12718 .append( $field );
12719 };
12720
12721 /* Setup */
12722
12723 OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.TextInputWidget );
12724
12725 /* Methods */
12726
12727 // Backward compatibility
12728 OO.ui.NumberInputWidget.prototype.setAllowInteger = function ( flag ) {
12729 this.setStep( flag ? 1 : null );
12730 };
12731 // Backward compatibility
12732 OO.ui.NumberInputWidget.prototype.setIsInteger = OO.ui.NumberInputWidget.prototype.setAllowInteger;
12733
12734 // Backward compatibility
12735 OO.ui.NumberInputWidget.prototype.getAllowInteger = function () {
12736 return this.step === 1;
12737 };
12738 // Backward compatibility
12739 OO.ui.NumberInputWidget.prototype.getIsInteger = OO.ui.NumberInputWidget.prototype.getAllowInteger;
12740
12741 /**
12742 * Set the range of allowed values
12743 *
12744 * @param {number} min Minimum allowed value
12745 * @param {number} max Maximum allowed value
12746 */
12747 OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
12748 if ( min > max ) {
12749 throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
12750 }
12751 this.min = min;
12752 this.max = max;
12753 this.$input.attr( 'min', this.min );
12754 this.$input.attr( 'max', this.max );
12755 this.setValidityFlag();
12756 };
12757
12758 /**
12759 * Get the current range
12760 *
12761 * @return {number[]} Minimum and maximum values
12762 */
12763 OO.ui.NumberInputWidget.prototype.getRange = function () {
12764 return [ this.min, this.max ];
12765 };
12766
12767 /**
12768 * Set the stepping deltas
12769 *
12770 * @param {number} [buttonStep=step||1] Delta when using the buttons or up/down arrow keys.
12771 * Defaults to `step` if specified, otherwise `1`.
12772 * @param {number} [pageStep=10*buttonStep] Delta when using the page-up/page-down keys.
12773 * Defaults to 10 times `buttonStep`.
12774 * @param {number|null} [step] If specified, the field only accepts values that are multiples
12775 * of this.
12776 */
12777 OO.ui.NumberInputWidget.prototype.setStep = function ( buttonStep, pageStep, step ) {
12778 if ( buttonStep === undefined ) {
12779 buttonStep = step || 1;
12780 }
12781 if ( pageStep === undefined ) {
12782 pageStep = 10 * buttonStep;
12783 }
12784 if ( step !== null && step <= 0 ) {
12785 throw new Error( 'Step value, if given, must be positive' );
12786 }
12787 if ( buttonStep <= 0 ) {
12788 throw new Error( 'Button step value must be positive' );
12789 }
12790 if ( pageStep <= 0 ) {
12791 throw new Error( 'Page step value must be positive' );
12792 }
12793 this.step = step;
12794 this.buttonStep = buttonStep;
12795 this.pageStep = pageStep;
12796 this.$input.attr( 'step', this.step || 'any' );
12797 this.setValidityFlag();
12798 };
12799
12800 /**
12801 * @inheritdoc
12802 */
12803 OO.ui.NumberInputWidget.prototype.setValue = function ( value ) {
12804 if ( value === '' ) {
12805 // Some browsers allow a value in the input even if there isn't one reported by $input.val()
12806 // so here we make sure an 'empty' value is actually displayed as such.
12807 this.$input.val( '' );
12808 }
12809 return OO.ui.NumberInputWidget.parent.prototype.setValue.call( this, value );
12810 };
12811
12812 /**
12813 * Get the current stepping values
12814 *
12815 * @return {number[]} Button step, page step, and validity step
12816 */
12817 OO.ui.NumberInputWidget.prototype.getStep = function () {
12818 return [ this.buttonStep, this.pageStep, this.step ];
12819 };
12820
12821 /**
12822 * Get the current value of the widget as a number
12823 *
12824 * @return {number} May be NaN, or an invalid number
12825 */
12826 OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
12827 return +this.getValue();
12828 };
12829
12830 /**
12831 * Adjust the value of the widget
12832 *
12833 * @param {number} delta Adjustment amount
12834 */
12835 OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
12836 var n, v = this.getNumericValue();
12837
12838 delta = +delta;
12839 if ( isNaN( delta ) || !isFinite( delta ) ) {
12840 throw new Error( 'Delta must be a finite number' );
12841 }
12842
12843 if ( isNaN( v ) ) {
12844 n = 0;
12845 } else {
12846 n = v + delta;
12847 n = Math.max( Math.min( n, this.max ), this.min );
12848 if ( this.step ) {
12849 n = Math.round( n / this.step ) * this.step;
12850 }
12851 }
12852
12853 if ( n !== v ) {
12854 this.setValue( n );
12855 }
12856 };
12857 /**
12858 * Validate input
12859 *
12860 * @private
12861 * @param {string} value Field value
12862 * @return {boolean}
12863 */
12864 OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
12865 var n = +value;
12866 if ( value === '' ) {
12867 return !this.isRequired();
12868 }
12869
12870 if ( isNaN( n ) || !isFinite( n ) ) {
12871 return false;
12872 }
12873
12874 if ( this.step && Math.floor( n / this.step ) !== n / this.step ) {
12875 return false;
12876 }
12877
12878 if ( n < this.min || n > this.max ) {
12879 return false;
12880 }
12881
12882 return true;
12883 };
12884
12885 /**
12886 * Handle mouse click events.
12887 *
12888 * @private
12889 * @param {number} dir +1 or -1
12890 */
12891 OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
12892 this.adjustValue( dir * this.buttonStep );
12893 };
12894
12895 /**
12896 * Handle mouse wheel events.
12897 *
12898 * @private
12899 * @param {jQuery.Event} event
12900 * @return {undefined/boolean} False to prevent default if event is handled
12901 */
12902 OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
12903 var delta = 0;
12904
12905 if ( !this.isDisabled() && this.$input.is( ':focus' ) ) {
12906 // Standard 'wheel' event
12907 if ( event.originalEvent.deltaMode !== undefined ) {
12908 this.sawWheelEvent = true;
12909 }
12910 if ( event.originalEvent.deltaY ) {
12911 delta = -event.originalEvent.deltaY;
12912 } else if ( event.originalEvent.deltaX ) {
12913 delta = event.originalEvent.deltaX;
12914 }
12915
12916 // Non-standard events
12917 if ( !this.sawWheelEvent ) {
12918 if ( event.originalEvent.wheelDeltaX ) {
12919 delta = -event.originalEvent.wheelDeltaX;
12920 } else if ( event.originalEvent.wheelDeltaY ) {
12921 delta = event.originalEvent.wheelDeltaY;
12922 } else if ( event.originalEvent.wheelDelta ) {
12923 delta = event.originalEvent.wheelDelta;
12924 } else if ( event.originalEvent.detail ) {
12925 delta = -event.originalEvent.detail;
12926 }
12927 }
12928
12929 if ( delta ) {
12930 delta = delta < 0 ? -1 : 1;
12931 this.adjustValue( delta * this.buttonStep );
12932 }
12933
12934 return false;
12935 }
12936 };
12937
12938 /**
12939 * Handle key down events.
12940 *
12941 * @private
12942 * @param {jQuery.Event} e Key down event
12943 * @return {undefined/boolean} False to prevent default if event is handled
12944 */
12945 OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
12946 if ( !this.isDisabled() ) {
12947 switch ( e.which ) {
12948 case OO.ui.Keys.UP:
12949 this.adjustValue( this.buttonStep );
12950 return false;
12951 case OO.ui.Keys.DOWN:
12952 this.adjustValue( -this.buttonStep );
12953 return false;
12954 case OO.ui.Keys.PAGEUP:
12955 this.adjustValue( this.pageStep );
12956 return false;
12957 case OO.ui.Keys.PAGEDOWN:
12958 this.adjustValue( -this.pageStep );
12959 return false;
12960 }
12961 }
12962 };
12963
12964 /**
12965 * @inheritdoc
12966 */
12967 OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
12968 // Parent method
12969 OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
12970
12971 if ( this.minusButton ) {
12972 this.minusButton.setDisabled( this.isDisabled() );
12973 }
12974 if ( this.plusButton ) {
12975 this.plusButton.setDisabled( this.isDisabled() );
12976 }
12977
12978 return this;
12979 };
12980
12981 }( OO ) );
12982
12983 //# sourceMappingURL=oojs-ui-core.js.map.json